System.NullReferenceException in viewList itemSource - xamarin.forms

Following this tutorial: https://learn.microsoft.com/pl-pl/xamarin/xamarin-forms/user-interface/listview/data-and-databinding
i'm getting this exeption:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
in line:
CategoryListView.ItemsSource = _category;
in the tutorial there is a warning which i guess is assiocciated with my problem, but i still have no clue how to solve the problem(i don't fully understand the warning)
namespace EduApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class QUIZListViewPage : ContentPage
{
ObservableCollection<Category> _category = new ObservableCollection<Category>();
//public ObservableCollection<Category> _Category { get { return _category; } }
public QUIZListViewPage()
{
CategoryListView.ItemsSource = _category;
_category.Add(new Category { categoryName = "first" });
InitializeComponent();
}
}
}
TY in advanced C:

Related

How to apply Command Design pattern with Dependency Injection using Generic Class?

i want to apply command Design pattern with dependency Injection in the following situation: i have three types of reports in my system (SubscriptionReport, SalesReport, SpechialistReport) so i created one interface IReportService
public interface IReportService<T> where T: class
{
public Task<GenericResponse<List<T>>> GetReport(string searchKey, DateTime from, DateTime to);
}
and to apply OCP i have implemented the GetReport function tree times for (SubscriptionReport, SalesReport, SpechialistReport)
public class SpechialistReportService : IReportService<SpechialistReportDTO>
{
public Task<GenericResponse<List<SpechialistReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
public class SubscriptionReportService : IReportService<SubscriptionReportDTO>
{
public Task<GenericResponse<List<SubscriptionReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
public class SalesReportService : IReportService<SalesReportDTO>
{
public Task<GenericResponse<List<SalesReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
after that i have added the dependency
services.AddScoped(typeof(IReportService<SpechialistReportDTO>), typeof(SpechialistReportService));
services.AddScoped(typeof(IReportService<SubscriptionReportDTO>), typeof(SubscriptionReportService));
services.AddScoped(typeof(IReportService<SalesReportDTO>), typeof(SalesReportService));
the problem is in calling the dependency in the controller constructor
private readonly IEnumerable<IReportService> _reportService; // Should be IReportService<dont know what class should i specify here>
public ReportController(IReportService<T> reportService)
{
this._reportService = reportService;
}
Any help would be appreciated thanks in advance,
Okay i solved this problem by removing the Generic and adding marker interface to the DTOs classes
public interface ReportRoot
{
}
public class SubscriptionReportDTO : ReportRoot
{
// Some data here
}
public class SalesReportDTO: ReportRoot
{
// Some data here
}
In ReportService Interface
public interface IReportService
{
public Task<GenericResponse<List<ReportRoot>>> Report();
}
public class SubscriptionReportService : IReportService {
public async Task<GenericResponse<List<ReportRoot>>> Report()
{
List<ReportRoot> subscriptionReportDTO = new List<ReportRoot>();
SubscriptionReportDTO test = new SubscriptionReportDTO();
test.SalesTax = "1000";
subscriptionReportDTO.Add(test);
return new GenericResponse<List<ReportRoot>>("1", subscriptionReportDTO.Count, "Success", subscriptionReportDTO);
}
}
public class SalesReportService : IReportService {
public async Task<GenericResponse<List<ReportRoot>>> Report()
{
List<ReportRoot> salesReportDTO = new List<ReportRoot>();
SalesReportDTO test = new SalesReportDTO ();
test.SalesTax = "1000";
salesReportDTO .Add(test);
return new GenericResponse<List<ReportRoot>>("1", salesReportDTO.Count, "Success", salesReportDTO );
}
}
In controller
private readonly IEnumerable<IReportService> _reportService;
public ReportController(IEnumerable<IReportService> reportService)
{
this._reportService = reportService;
}

How to get Binding-Context on creating DataTemplate

Is there a way to get the Binding-Context itself in an enumerated template?
this.CollectionView.ItemTemplate = new DataTemplate(() =>
{
var view = new SubView();
view.SetBinding(SubView.SourceProperty, new Binding()
{
Source = ??? // <- here
});
return view;
};
Note:
Path = "." works fine on Android. but on iOS, the source is duplicated.
I have already checked that there are no duplicates in CollectionView.ItemsSource.
I'm new to the platform I hope I can help.
I understand that you want to get the BindingContext of each element in the list. If I am interpreting correctly, then this is what you can do:
public partial class NotificationsPage : ContentPageBase
{
public NotificationsPage()
{
InitializeComponent();
CollectionView.ItemTemplate = new DataTemplate(() =>
{
return new Item();
});
}
}
public class Item : ContentView
{
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if (BindingContext is ItemModel item)
{
var name = item.Name;
}
}
}
public class ItemModel
{
public string Name { get; set; }
}
DataTemplate does not contain an accessible BindingContext, the BindingContext is passed to the element containing the DataTemplate.

'No Entity Framework provider found for the ADO.NET provider with invariant name 'FirebirdSql.Data.FirebirdClient'

By initializing the MYDbMigrator get the exception about provider not found. Is migration supported by firebird any other way to register the provider. Also tried to configure with appconfig but configuration section system.data cannot be recognized.
The big picture is i am trying to load the migrations from different assemblies and execute them in an order, but i am stuck in to register the provider. It cannot pass the DbConnection to TMigrationsConfiguration.TargetDatabase as it requires the DbConnectionInfo.
How to register the FirebiredSql.Data.FirebirdClinent so it could be found during application lifetime.
public abstract class MYBaseEntityContext : DbContext
{
protected MYBaseEntityContext() : base(connection, true)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
Configuration.AutoDetectChangesEnabled = true;
Configuration.ValidateOnSaveEnabled = true;
}
}
public class MYDbMigrator<TContext, TMigrationsConfiguration> : DbMigrator
where TContext : MYBaseEntityContext
where TMigrationsConfiguration : MYDataMigrationConfiguration<TContext>, new()
{
public MYDbMigrator(DbConnection connection)
: base(new TMigrationsConfiguration()
{
TargetDatabase = new DbConnectionInfo(connection.ConnectionString, "FirebirdSql.Data.FirebirdClient")
})
{ }
}
public class MYDataMigrationConfiguration<TDataContext> :
DbMigrationsConfiguration<TDataContext>
where TDataContext : MYBaseEntityContext
{
public MYDataMigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
SetHistoryContextFactory("FirebirdSql.Data.FirebirdClient", (connection, defaultSchema) => new BaseHistoryDataContext(connection, defaultSchema));
SetSqlGenerator("FirebirdSql.Data.FirebirdClient", new FbMigrationSqlGenerator());
}
}
private static FbConnection connection
{
get
{
FbConnectionStringBuilder b = new FbConnectionStringBuilder
{
ServerType = FbServerType.Embedded,
UserID = "sysdba",
Password = "masterkey",
DataSource = "localhost",
Database = "MYMigrations.fdb",
ClientLibrary = "fbclient.dll",
Dialect = 3
};
return new FbConnection(b.ToString());
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ZqwSn.png
public abstract class MYBaseEntityContext : DbContext
{
public class FirebirdConfiguration : DbConfiguration
{
public FirebirdConfiguration()
{
SetDefaultConnectionFactory(new FbConnectionFactory());
SetProviderFactory(FbProviderServices.ProviderInvariantName, FirebirdClientFactory.Instance);
SetProviderServices(FbProviderServices.ProviderInvariantName, FbProviderServices.Instance);
DbProviderFactories.RegisterFactory(FbProviderServices.ProviderInvariantName, FirebirdClientFactory.Instance);
}
}
}
MyApp.OnStartup(StartupEventArgs e)
{
...
DbConfiguration.SetConfiguration(new MYBaseEntityContext.FirebirdConfiguration());
...
}

ReactiveCommand in WPF throws exception with Subscribe

I have a simple demo application with ReactiveUI:
//in the viewmodel
class MainViewModel : ReactiveObject
{
public ReactiveUI.ReactiveCommand<Unit, Unit> MyReactiveCommand { get; }
public MainViewModel()
{
MyReactiveCommand = ReactiveCommand.Create(() => { MessageBox.Show("Hello"); }, outputScheduler: RxApp.MainThreadScheduler);
}
}
In the view XAML
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<WrapPanel HorizontalAlignment = "Left">
<Button Content="button" Command="{Binding MyReactiveCommand}"/>
</WrapPanel>
</Grid>
When you press the button there should be a Message Box but instead I get the following error:
System.InvalidOperationException: 'The calling thread cannot access
this object because a different thread owns it.'
I have tried returning a value and then subscribing like Glenn suggested but that had the same problem. At least with this code the Message Box opens before it crashes ;)
public class MainViewModel : ReactiveObject
{
public ReactiveCommand<Unit, Unit> MyReactiveCommand { get; }
public MainViewModel()
{
MyReactiveCommand = ReactiveCommand.CreateFromObservable(DoSometing);
MyReactiveCommand.Subscribe(x => { MessageBox.Show("Hello"); });
}
public IObservable<Unit> DoSometing()
{
return Observable.Start(() => { });
}
}
So a couple things to be aware of. ReactiveCommand.CreateFromObservable has a parameter called outputScheduler and this will be where the Subscribe's output will go to. You can pass RxApp.MainThreadScheduler here.
public class MainViewModel : ReactiveObject
{
public ReactiveCommand<Unit, Unit> MyReactiveCommand { get; }
public MainViewModel()
{
MyReactiveCommand = ReactiveCommand.CreateFromObservable(DoSometing, outputScheduler: RxApp.MainThreadScheduler);
MyReactiveCommand.Subscribe(x => { MessageBox.Show("Hello"); });
}
public IObservable<Unit> DoSometing()
{
return Observable.Start(() => { });
}
}
Note also make sure you have installed the NuGet package ReactiveUI.WPF

Invalid Column Name Discriminator when try to create Role

In my asp.net MVC 5 project, i cannot figure out why im getting this error:
Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'Description'.
Here is my code:
RoleManager<IdentityRole> _roleManager = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(new ApplicationDbContext()));
UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(new ApplicationDbContext()));
public bool CreateRole(string name, string description = "")
{
var idResult = _roleManager.Create(new IdentityRole(name)).Succeeded;
return idResult;
}
When i try to execute this method i get the invalid column error. what it could be?
EDIT:
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
EntityTypeConfiguration<ApplicationUser> table =
modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
table.Property((ApplicationUser u) => u.UserName).IsRequired();
modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
EntityTypeConfiguration<IdentityUserClaim> table1 =
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);
// Add this, so that IdentityRole can share a table with ApplicationRole:
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
// Change these from IdentityRole to ApplicationRole:
EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
}
}
When you modify Roles (for example add properties to your model in IdentityModels.cs like below):
public class ApplicationRole:IdentityRole
{
public string Description { get; set; }
public string AreaUsed { get; set; }
}
In code-first approach it will re-create database and 3 columns will be added to aspNetRoles instead of 2 (yes - I was surprised too). The additional column name is "Discriminator" type: nvarchar(128) not null.
When you're adding more roles it will automatically get value "IdentityRole".
I guess when automatic migrations are disabled this column is not being added and as a result you will be getting this error "Invalid column name". I had the same problem in my MVC 5.1 project with identity 2.0
Taking the previous response you have to do the following migration to get rid of this error
namespace Domain.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class YourMigration : DbMigration
{
public override void Up()
{
AddColumn("dbo.AspNetUsers", "Discriminator", c => c.String(nullable: false, maxLength: 128));
}
public override void Down()
{
DropColumn("dbo.AspNetUsers", "Discriminator");
}
}
}
I was having this issue and doing that fixed it.
I add this same issue to fix add [NotMapped] as attribute ApplicationRole
and ApplicationDbContext should inherit IdentityDbContext<TUser, IdentityRole, string>
[NotMapped]
public class ApplicationRole:IdentityRole
{
public string Description { get; set; }
public string AreaUsed { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{ ......
hope this help
more details can be found at
https://entityframeworkcore.com/knowledge-base/48712868/avoid--discriminator--with-aspnetusers--aspnetroles----aspnetuserroles

Resources