ObservableCollection list is unable to find method AddRange - c#

I am using Xamarin.Forms MVVM and sqlLite-net to make a Shared Mobile App.
I am getting an error bc 'AddRange' doesn't exist in ObservableCollection or I am using that function wrong.
All I want to do is to fill my ObservableCollection list. do I have to manually Add using loop? its weird ObservableCollection has a 'Add' method but no way to fill
Error: 'ObservableCollection' does not contain a definition for 'AddRange' and no accessible extension method 'AddRange' accepting a first argument of type 'ObservableCollection' could be found (are you missing a using directive or an assembly reference?)
using following refs:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TestApp01_MVVM_Basic.Models;
using Xamarin.CommunityToolkit.ObjectModel;
using Xamarin.Forms;
using System.Collections.Specialized;
using TestApp01_MVVM_Basic.Services;
using System.Collections.Generic;
using System.Linq;
Below I am creating my ObservableCollection. I am getting my error on line: AddRange()
public ObservableCollection<ProductModel> ProductsList { get; set; }
public ProductViewModel()
{
ProductsList = new ObservableCollection<ProductModel>();
}
public async Task MyDisplayList()
{
var getData = ProductService.DisplayProduct();
ProductsList.AddRange(getData);
}
In Servies Class, I have following DisplayProduct() method. that returns a list from database
public static async Task<IEnumerable<ProductModel>> DisplayProduct()
{
await Init();
var GetProduct = await db.Table<ProductModel>().ToListAsync();
return GetProduct;
}

What you are looking for is implemented on Xamarin community toolkit package: ObservableRangeCollection which sub-class System.Collections.ObjectModel.ObservableCollection<T>, you can use ObservableRangeCollection<ProductModel> instead of ObservableCollection<ProductModel> since the latter does not implement such method.
public ObservableRangeCollection<ProductModel> ProductsList { get; set; }
public ProductViewModel()
{
ProductsList = new ObservableRangeCollection<ProductModel>();
}
public async Task MyDisplayList()
{
var getData = await ProductService.DisplayProduct();
ProductsList.AddRange(getData);
}
public static async Task<IEnumerable<ProductModel>> DisplayProduct()
{
await Init();
var GetProduct = await db.Table<ProductModel>().ToListAsync();
return await Task.FromResult(GetProduct);
}

Related

Why am I getting the error CS0051 C# Inconsistent accessibility: parameter type 'user' is less accessible than method? [duplicate]

This question already has answers here:
Inconsistent Accessibility: Parameter type is less accessible than method
(13 answers)
Closed 2 years ago.
When I am running this code, one is the interface other is the class. I am getting this error.
CS0051 C# Inconsistent accessibility: parameter type 'user' is less
accessible than method 'cuserepository.Insert user'
This is the code for class cuserrepository:
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace signup_form
{
public class cuserrepository : userrepository
{
public async Task<bool> Insert(user user)
{
using (IDbConnection db = new SqlConnection(Apphelper.ConnectionString))
{
var result = await db.ExecuteAsync(signup_form.Properties.Resources.InsertUser, new { username = user.username, fullname = user.Fullname, email = user.Email, password = user.Password });
return result > 0;
}
}
}
}
This is the code for the interface:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace signup_form
{
interface userrepository
{
Task<bool> Insert(user user);
}
}
Can anyone tell me what is the problem?
The interface has no accessor on it so it will default to internal. You should make this public as outlined below.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace signup_form
{
public interface userrepository
{
Task<bool> Insert(user user);
}
}
You should also read up on Encapsulation to understand what is happening.
Also check out this answer What are the default access modifiers in C#?

AddAsync() method is missing

I am using Entity Framework Core. I want to create an async method which will create new user in my database, i have included all the libraries I need, but some methods that are supposed to work with database are missing, I have almost every async method but i am missing AddAsync and RemoveAsync. When I type AddAsync manually I get the following error message: "Error CS1061 'DbSet' does not contain a definition for 'AddAsync' and no accessible extension method 'AddAsync' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)"
The class where the method is created has following code and libraries included:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data;
using Microsoft.EntityFrameworkCore;
namespace ClassLibrary
{
public class Class1 : Interface1
{
public async Task AddKorisnik(Korisnici k)
{
using (ExtentEntities context = new ExtentEntities())
{
context.Korisnici.AddAsync();
await context.SaveChangesAsync();
}
}
}
}
The class where the DbContext is used is following:
namespace ClassLibrary
{
using System;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class ExtentEntities : DbContext
{
public ExtentEntities()
: base("name=ExtentEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Korisnici> Korisnici { get; set; }
}
}
There is nothing asynchronous with adding an object to an in-memory DbSet<T>. You should use the synchronous Add method to do this.
SaveChangesAsync() is the method that actually connects asynchronously to the underlying database.

OData Obsolete Code

I am trying to follow along this tutorial to create an OData service. I am looking at this topic about navigation properties:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4
It appears some of this code is obsolete (the article is from 2014, but I'm using Visual Studio 2017).
I have quite a few red underlines on my Helper class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Routing;
using System.Web.OData.Extensions;
using System.Web.OData.Routing;
using Microsoft.OData;
using Microsoft.OData.UriParser;
namespace ProductService
{
public static class Helpers
{
public static TKey GetFromUri<TKey>(HttpRequestMessage request, Uri uri)
{
if(uri == null)
throw new ArgumentException("uri");
var urlHelper = request.GetUrlHelper() ?? new UrlHelper(request);
string serviceRoot = urlHelper.CreateODataLink(
request.ODataProperties().RouteName,
request.ODataProperties().PathHandler, new List<ODataPathSegment>());
var odataPath = request.ODataProperties().PathHandler.Parse(
request.ODataProperties().Model,
serviceRoot, uri.LocalPath);
var keySegment = odataPath.Segments.OfType<KeyValuePathSegment>()
.FirstOrDefault();
if (keySegment == null)
throw new InvalidOperationException("The link does not contain a key.");
var value = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value,
ODataVersion.V4);
return (TKey)value;
}
}
}
I have problems with three pieces of code on this class:
request.ODataProperties().PathHandler
and
request.ODataProperties().Model
I get errors:
'HttpRequestMessageProperties' does not contain a definition for 'PathHandler' and no extension method...
It is also unable to find the KeyValuePathSegment class.
Is there a way to rewrite this class to keep it current?
#Pizzor2000
Some breaking changes introduced in Web API OData library from 5.x to 6.x version. All the changes you can find from release note at :https://github.com/OData/WebApi/releases/tag/v6.0.0
for your examples:
you can call extension methods to get the original properties, for example:
https://github.com/OData/WebApi/blob/master/src/System.Web.OData/Extensions/HttpRequestMessageExtensions.cs#L307 to get the IEdmModel.
https://github.com/OData/WebApi/blob/master/src/System.Web.OData/Extensions/HttpRequestMessageExtensions.cs#L352 to get the PathHandler.
Besides, KeyValuePathSegment is removed, Web API OData uses the https://github.com/OData/odata.net/blob/master/src/Microsoft.OData.Core/UriParser/SemanticAst/KeySegment.cs#L22 instead.
Hope it can help you.
Hoping that it might save some time I post here the same piece of code corrected with the new API.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.OData;
using Microsoft.OData.UriParser;
namespace ProductService
{
public static class Helpers
{
public static TKey GetKeyFromUri<TKey>(HttpRequest request, Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
var oDataPathHandler = request.GetPathHandler();
var oDataLink = request.GetUrlHelper().CreateODataLink(request.ODataFeature().RouteName, oDataPathHandler, new List<ODataPathSegment>());
var odataPath = oDataPathHandler.Parse(oDataLink, uri.AbsoluteUri, request.GetRequestContainer());
var keySegment = odataPath.Segments.OfType<KeySegment>().FirstOrDefault();
if (keySegment?.Keys == null || !keySegment.Keys.Any())
{
throw new InvalidOperationException("The link does not contain a key.");
}
return (TKey)keySegment.Keys.FirstOrDefault().Value;
}
}
}

How to make a call to outside function from the controllers/models in C# MVC?

I am new to C# MVC. I am trying to create a class where can I can put all the reusable functions and I want to have the ability to call those functions from my controllers and models. Is it possible to do so?
Here is my project folder structure:
So I have created a Helpers folder and inside it I have a commonFunctions class.
For now I have one function inside it.
namespace myProject.Helpers
{
public class CommonFunctions
{
public static string GenerateSHA(string sString)
{
string result = "";
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] password = sha.ComputeHash(Encoding.Default.GetBytes(sString));
result = Encoding.Default.GetString(password);
return result;
}
}
}
I want to call that function from my model. How can I do so?
Thanks in advance.
You can easily call that function like this:
var sha = Helpers.CommonFunctions.GenerateSHA("Your String");
Or you can add using statement and call the function without namespace specification every time:
using myProject.Helpers;
// And somewhere in your classes
var sha = CommonFunctions.GenerateSHA("Your String");
It is a direct call like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace myProject.Models
{
public class YourViewModel
{
public YourViewModel()
{
//This is the constructor of the class
//Call the function you need
var tVar = Helpers.CommonFunctions.GenerateSHA("String to process");
}
}
}

return all IQueryable with Entity framework

I just switched from Linq to entities framework, and I'm having problems with methods that returns "all rows". I get: "The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced" error in my "service layer" that calls the data-layer.
I get an error on:
BookingObjectRepository _repository = new BookingObjectRepository();
public IQueryable<BookingObject> GetBookingObjects()
{
return _repository.GetBookingObjects();
}
and in the "data-layer" I have:
BookingsystemEntities _entities = new BookingsystemEntities();
public IQueryable<BookingObject> GetBookingObjects()
{
return from bo in _entities.BookingObjectSet
select bo;
}
UPDATE: Filter items, they are "physically" in Filters-folder but namespace is same as the emdx file uses.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BookingSystem.Data.Models
{
public static class BookingObjectFilters
{public static IQueryable<BookingObject> ByBookingObjectID(this IQueryable<BookingObject> qry, int bookingobjectID)
{
return from bo in qry
where bo.BookingObjectID == bookingobjectID
select bo;
}
Your system must have .NET 3.5 SP 1 or better installed, and your project must reference the System.Data.Entity assembly (look at the references node in Solution Explorer).
Do you have
using System.Data;
using System.Data.Objects.DataClasses;
in your usings?
and
public IQueryable GetBookingObjects() { return _repository.GetBookingObjects(); }
should probably be
public IQueryable<BookingObject> GetBookingObjects() { return _repository.GetBookingObjects(); }
Hope that helps,
Dan

Categories