Thursday, November 30, 2017

Type of Entities

Fluent API

Fluent API is used to configure model class. While using Data Annotation we need to configure each property while using Fluent API we can configure multiple properties in a single line code.

https://www.tutorialspoint.com/entity_framework/entity_framework_fluent_api.htm

DbModelBuilder

DbModelBuilder is used to map CLR classes to a database schema. This code centric approach to building an Entity Data Model (EDM) model is known as 'Code First'.

DbContext.OnModelCreating Method (DbModelBuilder)

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

We use it to use EF's fluent API to refine our model.

Wednesday, November 29, 2017

How to use two object in a single view

There are multiple way to do is

1. Using ExpandoObject

ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime.

 public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to my demo!";  
        dynamic mymodel = new ExpandoObject();  
        mymodel.Teachers = GetTeachers();  
        mymodel.Students = GetStudents();  
        return View(mymodel);  
    }  

In View

@using MultipleModelInOneView;  
@model dynamic  
@{  
    ViewBag.Title = "Home Page";  
}


2. Using View Model


ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

public class ViewModel  
{  
    public IEnumerable Teachers { get; set; }  
    public IEnumerable Students { get; set; }  




Controller code

public ActionResult IndexViewModel()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewModel mymodel = new ViewModel();  
    mymodel.Teachers = GetTeachers();  
    mymodel.Students = GetStudents();  
    return View(mymodel);  
}  

In View

@using MultipleModelInOneView;  
@model ViewModel   
@{  
    ViewBag.Title = "Home Page";  
}  

3. Using ViewData 


Controller Code

public ActionResult IndexViewData()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewData["Teachers"] = GetTeachers();  
    ViewData["Students"] = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  


4. Using ViewBag


public ActionResult IndexViewBag()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewBag.Teachers = GetTeachers();  
    ViewBag.Students = GetStudents();  
    return View();  
}  

5. Using Tuple

A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to eight elements.

Using this tuple object we can pass multiple models from the controller to the view.

Controller Code

public ActionResult IndexTuple()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    var tupleModel = new Tuple, List>(GetTeachers(), GetStudents());  
    return View(tupleModel);  
}  

View Code

@using MultipleModelInOneView;  
@model Tuple , List >  
@{  
    ViewBag.Title = "Home Page";  
}  

6. Using Render Action Method

A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.

Controller Code

///
  
/// Render Teacher List  
///
  ///   
public PartialViewResult RenderTeacher()  
{  
    return PartialView(GetTeachers());  
}  
   
///
  
/// Render Student List  
///
  ///   
public PartialViewResult RenderStudent()  
{  
    return PartialView(GetStudents());  
}  

View Code

@{  
   ViewBag.Title = "PartialView";  

@ViewBag.Message

  

  

    @{  
        Html.RenderAction("RenderTeacher");  
        Html.RenderAction("RenderStudent");  
    }  


RenderTeacher.cshtml
RenderStudent.cshtml

http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/

Data Annotation

The Data annotations attribute classes are used to decorate the classes or properties. These attributes help Entity Framework Code First to apply pre-defined rules on entity models

We can devide data annotations into the following categories

1. Database Schema related
2. Validation attributes.


1. Database Schema related

1. Table Attribute : 

Provides the alternate table name and specify the schema.

2. Column Attribute : 

Provide alternate column name, order amd database type for column.

3. Key Attribute :

 By default a property with name Id or Class Name + Id is primary key in a class, but if you want to make another property as a primary key, you can use key attribute.

4. Composite Keys :

 Add keyy attribute to more than one column will behave as composite key.


The Timestamp attribute specifies the byte array (byte []) property / column that has a concurrency mode of "Fixed" in the model and it should be a Timestamp column in the stored model (database). It is not nullable.

5. ConcurrencyCheck Attribute : 

If you want to prevent conflict while updating data by two user than we use concurrency check for each filed , whose value we  want to compare with old one before updating.

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application


6. Timestamp Attribute : 

A timestamp value compare while updating the data to prevent conflict. Instead of marking each field concurrency check.

7. ForeignKey Attribute : 

This attribute specifies the foreign key for the Navigation property.

8. InverseProperty Attribute : 

Used when the same type takes part in multiple relationships. 


Using an InverseProperty attribute, we can specify which navigation property should be returned.



public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public List ContactsCreated { get; set; }
    public List ContactsUpdated { get; set; }
}

This model appears to fit the inverse navigation property convention for Entity Framework Core, but EF Core will raise an error when asked to map these relationships:

Unable to determine the relationship represented by navigation property 'Contact.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property from the model.
The InverseProperty attribute is applied to the navigation properties in the User class to specify their corresponding inverse navigation properties in the Contact class:

public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    [InverseProperty("CreatedBy")]
    public List ContactsCreated { get; set; }
    [InverseProperty("UpdatedBy")]
    public List ContactsUpdated { get; set; }
}

https://www.tektutorialshub.com/data-annotations-inverseproperty-attribute-in-entity-framework/

9. Index Attribute : 

The property of the model can be marked with an attribute and it should participate in a store index. The Index attribute allows us to create an index on one or more columns and we can specify the name of the index.

[Index("IX_Name_DepartmentMaster", IsClustered = false)]
public string Name { get; set; }

DatabaseGenerated Attribute : 

There are three type of DatabaseGenerated Attributes


Identity

The database generates the identity value when a row is inserted.

Computed

The database generates a value for the property when a row is inserted or updated.

None

The database does not generate a value for the property when the row is inserted or updated

10. ComplexType Attribute : 

If you are declaring a field whose data type is a class than you need to mark that field complex type.

11. NotMapped Attribute : 

If you want  your column should not be created in database than use NotMapped attribute.

2. Validation Attributes

StringLength: 

StringLength is user to define the length of string allowed in table

MinLength: 

MinLength define the minimum required length of string.

MaxLength: 

MaxLength define the minimum required length of string.

Required: 

The Required annotation will ensure that property has data in

Tuesday, November 28, 2017

No 'Access-Control-Allow-Origin' header is present on the requested resource

Google chorme does not allow to call local Web api if they are running on different port.
If you need to enable it tou need to install Microsoft.AspNet.Cors from nuget.

And need to write two lines in WebApiConfig file.


var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);

Sample code

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            var cors = new EnableCorsAttribute("*","*","*");
            config.EnableCors(cors);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                //routeTemplate: "{controller}/{id}",
               // routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes
                .Add(new MediaTypeHeaderValue("text/html"));
        }

Friday, November 24, 2017

Why Sessions are Not Recommended to use in MVC

One of the Fundamental Principal of Asp.Net MVC Framework is Web is Stateless And Asp .Net MVC is Stateless Asp .net Web Forms is a try to make Stateful Modal But Its difficult to maintain it as this modal does not exist . Sessions Create lot of load on Cache that was biggest problem .

Using Session in AspDotNet MVC is like Putting APPLE Logo on Asus Laptop and Calling it Apple Laptop . Reality does not change .


https://geeksprogrammings.blogspot.in/2016/05/tempdata-vs-session-in-aspnet-mvc.html

Difference Between TempData and Session

1. TempData allow us to persisting data for the duration of single subsequent request.
Session is able to store data much more long time, until user session is not expire.

2. TempData valid for only current and subsequent request only
Session valid for all requests.

3. TempData has Keep method to retention the value of TempData.

Example

TempData.Keep()

For Specific

TempData.Keep(“EmpName”)

4. TempData internally stored the value in to Session variable.
Session varible are stored in SessionStateItemCollection object (Which is exposed through the HttpContext.Session property of page).

Wednesday, November 22, 2017

OWIN

OWIN is not a framework. OWIN is a specification on how web servers and web applications should be built in order to decouple one from another and allow movement of ASP.NET applications to environments where at the current state it is not possible.

From Owin.org

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application.

Lack of ASP .Net

It had lacked some basic qualities like portability, modularity and scalability

What problems does it solve?

Before Owin ASP .Net application were tightly coupled  with IIS because of heavy dependency on System.Web.


System.Web which in turn heavily depends on IIS for providing many of the web infrastructure features like request/response filtering, logging, etc.

System.Web assembly also includes many default components that are plugged into the Http pipeline regardless of its usage in the application. This means there are some unwanted features  (such as Web Forms or URL Authorization) that are executed in the pipeline for every request which degrades the performance. This has made the current open source counter-parts like NodeJs, Ruby, etc. perform way better than Asp.Net framework.

So OWIN itself does not have any tools, libraries or anything else. It is just a specification.

What is Katana?

Katana on the other hand, is fully developed framework made to make a bridge between current ASP.NET frameworks and OWIN specification. 

Host Option

When deciding how will you host your web server, you had two options:

  • IIS
  • Self-Host

IIS is good, resourceful host for web servers. Entire ASP.NET performance issue with using IIS has deep roots in System.Web only. Up until the recent time, 

So if you wanted a performance, you'd go for self-host option. If you wanted a lot of out-of-the-box features that IIS provides, you'd go for IIS but you'd lose on performance.


Now, there is a 3rd option, a Microsoft library named Helios (current codename) which intends to remove System.Web out of the way, and allow you to use IIS on more "cleaner" way, without any unnecessary libraries or modules. Helios is now in pre-release version, and is waiting for more community feedback in order to make it fully supported Microsoft product.

OWIN components

There are only two main pieces in OWIN

An environment dictionary   This dictionary is passed to  our application by the server with request and response header and bodies.Our application works directly  with this dictionary instead of communicating with the server.It is this dictionary which helps create the decoupled OWIN architecture.

A generic Func delegate  This delegate takes as a parameter the above mentioned environment dictionary and returns a Task.We can plugin different middleware components using this.

The environment dictionary can contain only the designated keys.Some of the keys related to the Request are

Key 
Description

"owin.RequestBody"
A Stream with the request body

"owin.RequestHeaders"
A IDictionary containing request headers. 

"owin.RequestMethod"
A string containing the HTTP method of the request (GET, POST etc. )

"owin.RequestPath"
A string which contains the request path

"owin.RequestPathBase"
A string which contains the portion of the request path corresponding to the "root" of the application delegate

"owin.RequestProtocol"
A string which contains the protocol name and version (HTTP/1.0, HTTP/1.1  etc.)

Following happens when the host starts

  • The environment dictionary is created  by the Host and passed to the server.Host also populates this  ,prior to passing this to the server,to inform the server about itself.
  • Server populates this dictionary to announce  its capabilities to other OWIN components, like our application and the server.
  • Host passes the dictionary to our application's setup code.
  • Our application creates the request pipeline and returns the generic Func delegate.
  • Host now starts the server by launching the server startup code with the dictionary and the delegate.
After the above steps have completed the server is ready accept the requests using the delegate passed to it by our application.

As we saw host is responsible for creating the server ,as well as communicating with our application to create the  request pipeline.

Katana Implementation of  OWIN









Wednesday, November 15, 2017

Difference Between View Data/ViewBag and TempData

ViewData
  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null
ViewBag
  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type
TempData
  1. TempData is derived from TempDataDictionary class
  2. TempData is used to pass data from the current request to the next request
  3. It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
  4. It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

Tuesday, November 14, 2017

Difference between Implicit implementation and Explicit implementation of interface


In case of implicit public keyword is necessary in function definition while in case of Explicit declaration public keyword can not be use and we need to define it with Interface Name and this method will be public by default.

Explicit Implementation

 public interface IUser2
    {
        void Display();
    }

    public class User1 : IUser2
    {     
        void IUser2.Display()
        {
            throw new NotImplementedException();
        }
    }

In case of explicit implementation you can not use as below

User1 obj = new User1();
obj.Display(); //Error , event intellisence will not show method Dispaly with obj.

Correct use is

IUser2 obj = new User1();
obj.Display();

Implicit Implementation

public interface IUser2
    {
        void Display();
    }

    public class User1 : IUser2
    {     
        public void Display()
        {
            throw new NotImplementedException();
        }
    }

main ()
{
User1 obj = new User1();
obj.Display();
//Does compile successfully but should be avoided.

//Instead below code should be use
IUser2 obj = new User1();
obj.Display();
}

Conclusion about Explicit interfaces

  • Explicit interface should be avoided and ISP should be followed. In other words have different interfaces for different abstractions.
  • Explicit interfaces cannot be usedby the derived classes.
  • The only time it should be used when for reasons you want to implement the interface but the hide some methods and show methods via the class.

Followers

Link