Skip to main content

Posts

Showing posts from 2016

Data seed through JSON files using EF or any ORM

Last time I had demonstrated a concept for Data Seed through any ORM or MongoDB. The idea is to feed the data to DB at first run or based on condition. The advantage is no one has to manage DB manually with SQL script which feels more natural with Code First approach and every developer can have their own copy with this approach.

I am going to extend the same idea by importing data from JSON file. There are few reasons to do through JSON file as we do not want to keep increasing our codes for data import which may end up with  Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals. Also in the case of a huge number of records it does not make sense and with newer development practice JSON feels more natural for data.

First please go to Data seed for the application with EF, MongoDB or any other ORM as I would be extending same items to allow it through JSON file.

It is always a great idea to have a base class for common items…

Data seed for the application with EF, MongoDB or any other ORM.

Most of ORMs has moved to Code first approach where everything is derived/initialized from codes rather than DB side. In this situation, it is better to set data through codes only. We would be looking through simple technique where we would be Seeding data through Codes.

I would be using UnitOfWork and Repository pattern for implementing Data Seeding technique. This can be applied to any data source MongoDB, EF, or any other ORM or DB.

Things we would be doing.
- Creating a base class for easy usage.
- Interface for Seed function for any future enhancements.
- Individual seed classes.
- Configuration to call all seeds.
- AspNet core configuration to Seed data through Seed configuration.
Creating a base class for easy usage public abstract class BaseSeed<TModel> where TModel : class { protected readonly IMyProjectUnitOfWork MyProjectUnitOfWork; public BaseSeed(IMyProjectUnitOfWork MyProjectUnitOfWork) { MyProjectUnitOfWork = …

ASP.NET Core environment aware strongly typed configuration in MongoDB

This is targetted to save in MongoDB but the technique can be used in any targetted backend with key value setting based on IConfigurationProvider Data property.

Basically, the provided interface works based Data property having a type as IDictionary<string, string>. So, whatever class we create it has to be serialized based on same. We would simplify this by creating an abstract class to have certain serialization logic.

This is sample setting for the application. If you check the structure,  Setting is the main class and nested items are Azure, Message, Email, Twilio. The key value needs to be composed based on parent and child classes separated by colons.



Just like above, we need to populate settings from our different setting classes.

Implementation can be grouped in these sections.
- Application level configuration classes.
- Registration of configuration on ASP.NET Core.
- Environment level configuration, this would little mixed with above.
Application level configuration…

Global exception handling and custom logging in AspNet Core with MongoDB

In this, we would be looking into logging and global exception handling in the AspNet Core application with proper registration of logger and global exception handling.

Custom logging
The first step is to create a data model that we want to save into DB.

Error log Data model
These are few properties to do logging which could be extended or reduced based on need.

public class ErrorLog { /// <summary> /// Gets or sets the Error log identifier. /// </summary> /// <value> /// The Error log identifier. /// </value> [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; /// <summary> /// Gets or sets the date. /// </summary> /// <value> /// The date. /// </value> public DateTime Date { get; set; } /// <summary> /// Gets or sets the thread. /// </summary> /// <v…

OpenId Authentication with AspNet Identity Core

This is a very simple trick to make AspNet Identity work with OpenId Authentication. More of all both approach is completely separate to each other, there is no any connecting point.

I am using Microsoft.AspNetCore.Authentication.OpenIdConnect package to configure but it should work with any other.

Configuring under Startup.cs with IAppBuilder
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, LoginPath = new PathString("/Account/Login"), CookieName = "MyProjectName", }) .UseIdentity() .UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = "<AzureAdClientId>", Authority = String.Format("https://login.microsoftonline.com/{0}", "<AzureAdTenant>"), ResponseType = OpenIdConnectResponseType.IdToken, PostLogoutRedirectUri = "<my website url>", Au…

LDAP with ASPNet Core Identity in MVC Core

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

AspNet Identity Core is a new offering from Microsoft in replacement of AspNet Identity for managing users.

In this tutorial, we would be looking for implementing LDAP with AspNet Identity Core to allow users to be able to log in through AD or AspNet Identity Core members.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functiona…

MongoDB navigation property or making it behave as ORM in .Net

This is an implementation to make models to have  navigation properties work like ORM does for us.

What actually happens in ORM to make navigation properties work? Entity Framework has proxy classes implementation to allow lazy loading and eager loading implementation. While creating proxy classes it also changes definitions for actual classes to make navigation properties work to get values based on Model's for navigation properties. Most of ORMs work in same fashion like Telerik DataAccess has enhancer tool which changes class definition at compile time to enable navigation properties.

In this implementation, we would retain the original class but we would have extension methods to allow initializing properties to have navigation proprieties work.

Let's first create desire model on which we need to implement. I am picking up simple one-to-many relationship example from Person to Address.

public class Person { public int PersonId { get; set; } public string Name …

Client side Validation for data driven view engine

The prerequisite for this is to have a designed database driven view engine. This can be a good guidance to implement DB driven view engine Data Driven Custom View Engine in ASP.NET MVC (http://www.dotnetcurry.com/aspnet-mvc/946/data-driven-custom-view-engine-aspnet-mvc).

If we talk about the concept then we can say for DB driven view engine a dynamic form/screen table would require along with the associate attribute set for controls. The controls, Attribute set can have constraints like Required, MaxLength, RegEx etc. similar to available DataAnnotation implementation, just that it has to come through DB.

The jQuery unobtrusive validation is all about adding certain HTML 5 data attributes. So, if we can find rules of the controls (required, max length etc) and set it to HTML attribute from view engine then we are done.

While designing DB driven view engine, there should be a place where we need to loop through available controls to identify it's type and write as HTML/element. A…