Sunday, 7 February 2016

iIitializaing variable in c#.net ?

We are learning a new language daily so we need to remember how too initialize variables in c#.net so bookmark this and use it as your daily guidebook to initialize variable in c#.net.

Initialize variables in C#.net

Single Dimensional Array 
Integers
<code>
int[] n1= new int[4]{2,3,1,4};
int[] n2= new int[]{1,2,3,4};
int[] n3= {1,2,3,4,};
</code>

Strings
<code>
string[] s1= new string[4]{"tom","jerry","harry","ben"};
string[] s2= new string[]{"tom","jerry","harry","ben"};
string[] s3= {"tom","jerry","harry","ben"};
</code>

Multi-dimensional array.
Integer
<code>
int[,] n1 = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
int[,] n2 = new int[,] { {1, 2}, {3, 4}, {5, 6} };
int[,] n3 = { {1, 2}, {3, 4}, {5, 6} };
</code>

String
<code>
string[,] n1 = new string["ben","tom"] { {"sam","joe"}, {"harry","jack"}, {"noa","nemo"} };
string[,] n2 = new string[,] { {"sam","joe"}, {"harry","jack"}, {"noa","nemo"}};
string[,] n3 = {{"sam","joe"}, {"harry","jack"}, {"noa","nemo"} };
</code>

Jagged array.
Integer
<code>
int[][] n1 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
int[][] n2 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
int[][] n3 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
</code>

String
<code>
string[][] n1 = new string[2][] { new string[] {2,4,6}, new string[] {1,3,5,7,9} };
string[][] n2 = new string[][] { new string[] {2,4,6}, new string[] {1,3,5,7,9} };
string[][] n3 = { new string[] {2,4,6}, new string[] {1,3,5,7,9} };
</code>


Filters in MVC5?

Filters: Filters in mvc are a way to implement cross cutting concerns which means Functionaity that is used aross the application based on different layers. These fnctionality includes logging, exception handling, cacheing, Authorization, Authentication etc.

These function are required to kept at single place so as to mkae changes easier.Advavntage that filters provide as they use common logic to implemented using cross cutting concerns that can be applied on different controllers and action methods.

There are generally two types of filters that are Global filters and Controller filters. 

We can create a Global filter by creating a class nad registering it as a global filter 
<code>
public class DemoGlobalFilterAttribute : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext context)
       {
           base.OnActionExecuting(context);
           context.RequestContext.HttpContext.Response.Write("This is global filter");
       }
   }
</code>

Then register global filter
<code>
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute());
</code>

Similary we can do for Controller Filters.


Filter Overrides in MVC 5: 
MVC5 gives a feature of filter override which can be applied to controllers and action methods which can override the golbal filter or the controller filter for the specified controller or the action method.

lets take a small example we want to override the contactus action method in the home controller.for this we only need to apply the OverrrideActionFilter attrinbute on the action method.Check the code below. 
<code>
[OverrideActionFilters]
public ActionResult ContactUs(){
ViewBag.Message = "This is the contact us page";
return View();
}
</code>
This can be usefull in different and multiple scenarios, Lets see a small scenario.
<code>
[Authorize(Users="Demo")]
[RoutePrefix("Prod")]
public class ProdController : Controller  
 {

[Route("Mob/{categoryId:maxlength(8)}")]
[OverrideAuthorization]
public ActionResult GetMobiles(string categoryId)
{    
    ViewBag.categoryId= t;      
    return View();
}
</code>

Here we have applied the authorize filter to the controller, then overridden the controller filter on GetMobiles action action method

We have filter overrides for each filter types
OverrideActionFilter         -  ActionFilter
OverrideAuthorizationFilter  -  AuthorizationFilter
OverrideAuthenticationFilter -  authenticationFilter
OverrideExceptionFilter      -  ExceptionFilter

Saturday, 6 February 2016

Attribute based routing in MVC 5 ?

Attribute Based Routing:Attribute based routing can defined as route configuration in the same place where action method is defined. This is way of setting the route configuration for every single action method in same section where action is defined for better usage and fast configuration.

To enable Attribute based routing we need to add a small section into the RouteConfig.cs file,

public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}

Optional Parameter: We can specify the optional parameters in the URL in route attribute only using "?" character.

[Route("Products/Electronics/{id?}")]
public ActionResult GetElectronicItems(int? id) {
ViewBag.Id = id; return View();
}


Route Constraints:  Specify parameter constraints placing the constraint name after the parameter name separated by colon.Here the action methods needs a id of int type to be worked upon.

[Route("Products/Electronics/{id:int}")]


Route Prefix: If there are a lot of action in a controller , then we can choose different prefix for them using Route Prefix attribute.

[RoutePrefix("Products")]

So now our Route attribute on our action method does not need to specify the common prefix

[Route("Electronics/{id}")]

Friday, 22 January 2016

Creating page for MVC in C#.net .

For this initially we need to have a model.
Let the model be Cust for Customer

public class Cust()
{
[DisplyName= "CustmerId"]
public int Cust_Id{get ; set;}
[DisplayName= "Cusotmer Name"]
public string Cust_Name {get; set;}
[DisplayName = "Cusomter Nick Name"]
public string Cust_Nickname{get; set;}
}

Now we need to create a controller . Let the controller name Be Customer
Initially we need to add the customer to the database

To create any customer using this application we need to create two action methods,
First will generate the html for the user to view the page to be created.
Another, this methods will take the arguments from the UI(creation page)

[HttpGet]
public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Create(Cust NewCustomer)
{
//var date= DateTime.Today; // this may be anything you nee to pass on to next method
// Do some thing on the code 

 return View("Cust");

//return RedirectToAction("ActionName Of same Controller");
//return RedirectToAction ("ControllerName" ,"Action");
//return RedirectToAction ("ControllerName" ,"Action" , new {mydate= date});
//return REdirectToAction("ActionName Of the cntroller" , New {mydate = date});
}

Now, we need to create a view the Create Action this view is a basic input screen for the customer.

// Create.cshtml

@model Model.Cust
@{
layout = null ;
}

@Html.BeginForm(){

@Html.DispalyFor(model=> model.Cust_Id):
@Html.TextBoxFor(model=> model.Cust_Id)

@Html.DispalyFor(model=> model.Cust_Name ):
@Html.TextBoxFor(model=> model.Cust_Name )

@Html.DispalyFor(model=> model.Cust_Nickname):
@Html.TextBoxFor(model=> model.Cust_Nickname)

<input type="Submit" value="Create">
}

Saturday, 19 December 2015

Create a DataTable from a Class using reflection .

There are many solution to this problem, For this we use a technical process called Reflection.

Reflection: To dynamically create an instance  of a type, bind the type to an existing  object ad invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.

1.Use AsEnumerable() method to support LINQ:

private List<T> ConvertToList<T>(DataTable dt)    {        var columnNames = dt.Columns.Cast<DataColumn>()            .Select(c => c.ColumnName)            .ToList();
        var properties = typeof(T).GetProperties();
        return dt.AsEnumerable().Select(row =>            {                var objT = Activator.CreateInstance<T>();
                foreach (var pro in properties)                {                    if (columnNames.Contains(pro.Name))                        pro.SetValue(objT, row[pro.Name]);                }
                return objT;            }).ToList();
    }