Introduction to Asp.net Core 1.0

I had a privilege to be invited by Agile Testing Alliance , Vadodara chapter to talk about Asp.net Core 1.0 . It was very interactive sessions and the participants asked some really good questions.

Here is the synopsis of my talk

What is Asp.net Core ?

It is a lean stack from Microsoft to develop the modern web apps built from ground up and is most revolutionary version since asp.net first was released in 2002
Today it is available RC1 update 1 which comes with golive license so this means that this framework is production ready.

Cross platform

This is a game changer and USP about this framework.  It works seamlessly on Windows, OSX and Linux. The same code base runs directly on the metal, and remember this is different from the Mono Framework. In fact the CoreClr is around 11 meg and is shipped along with your application as a nuget package

Unified programming model

In previous versions of MVC 5 and webapi 2 each API existed in different namespaces but there are now one. So if you remember in previous version of mvc you need to inherit the class from the controller and when you need to develop a webapi you need to inherit from apicontroller. But now everything comes under one controller class. same applies to routing, actions, filters etc.

Modular components

Every feature now is shipped as a single nuget package. So if you want to use mvc features download it and register as middleware, You want identity authentication do the same and you are up and running. ConfigureServices where your register your middleware services and Configure is where you use them.  You can write your own custom middleware too.The sample code below give you fair idea of these methods

Middleware and built in Ioc

In previous versions of aps.net DI and IOC were optional but now it is part of the framework and it comes as a built in feature out of the box. You are free to replace it with your own favourite DI framework too.

Modern tooling

You can take the advantage of all the modern tooling which JavaScript world supports, In fact bower can be used for all client side packages whereas nuget can take care of server side packages and dependencies. Use Gulp or Grunt for task runners. Remember that in the older versions you had bundling and minification feature in mvc this is no more there now and it is replaced by this task runners to care of it

DNX context

 

DNX stands for Dot net Execution. The DNX and middleware works in hand to hand to process the request pipeline. Below diagram represents the complete picture.

image

Actually, when the request is made, it first arrives at the web server,web server then invokes the DNX which will load the CLR and then looks for an entry point, the Main method, in your application and executes it. The main method configures the pipeline by using the Startup class, and the request is pushed through the pipeline, processed by the middleware which will produce the response.

Cloud Optimized

As it has low footprint deployment it is your best choice for cloud based solutions.

Github OSS

 

We all know that Microsoft has embrace the OSS in a big way and asp.net core is no more different. If you wish to contribute to this you can very well do it. Just create a pull request or fork it on Github. There are really some very good contributions from community.

Easy install

get.asp.net site is a single source of truth for asp.net core. Right from documentation to tools everything is available here. It is quite smart to recognize your OS version and suggest the appropriate download link.

Multiple choice of IDEs

Though I gave the demo on Visual studio. You have plethora choice for IDE like Code , Atom and many others.

Presentation materials

The sample demo application and slide decks can be downloaded from my Github repo. I’ve heard that recording has also been done. I would check out with the organizers and will upload later once it is available to me.

Advertisements

Url rewriting with http module in asp.net

INTRODUCTION

I am highly impressed by Asp.net MVC framework. There are lot of exciting features into the framework but the one that excites me most is UrlRewriting module. Every url depends on the controller and its actions methods. The format of this url is something like this "{controllerclassname}/{actionmethodname}/{id}".  Moreover these pages doesn’t physically exists on the hard drive.  Cool very cool. This feature impressed me so much that I decided to implement the same into my one of the asp.net web forms project. In this post I introduce you to http modules and how you can unleash their power and do miracles in your solutions.

HTTP MODULES

HttpModules are extremely powerful feature of asp.net. They act like listeners to the request that your asp.net application receives. Most of built in functionality of asp.net like output cache, session management, authentication and authorization are developed on HttpModules. An http module is a class which implements IHttpModule .  This interface has two methods Init and Dispose. The Init method is where you have to write the code to implement your custom functionality. The below listing shows the list of events that are available in the Init method.

  • AcquireRequestState
  • AuthenticateRequestState
  • AuthorizeRequestState
  • BeginRequest
  • EndRequest
  • Disposed
  • Error
  • PreRequestHandlerExecute
  • PostRequestHandlerExecute
  • PreSendRequestContent
  • PreSendRequestHeaders

I won’t get into the details of each and every event and when they are triggered. You can read more about them here. This article focuses on the url rewriting and to do so we will be using the BeginRequest event. This event is raised when a new request is arrived. This is the best place to override the default functionality. Just creating the custom class doesn’t complete the work. You need to tell to the asp.net engine that I have a custom HttpModule. You can specify this in the web.config file under <httpModules> section. It should be written in the following format.

<add name ="YourmoduleName" type ="NamespaceName.ClassName,AssemblyName"/>

The next section in the post discusses my solution of url rewriting.

URL REWRITTING

This may not be a full fledge url rewriting solution. But this will help you to get started. Now let us talk about the solution I have two pages in my project

A Default page that displays the product categories and their description in the gridview. The category column is of type  HyperlinkField , clicking on this link will navigate to the Products page showing the relevant products that belongs to the category. A traditional solution would be of passing the querystring to the Products page and then displaying the records. But let us think how the asp.net mvc team thought, how about redirecting to the page which more user friendly something like “yourappname/Categories/Beverages”. Isn’t this more seo friendly and much pleasant than “yourappname/Products.aspx?Cn=Beverages”. So how do we do this ,well HttpModules can do it for you. Look at the sample code below.

public class myhttpModule :IHttpModule
    {
        private HttpApplication httpApp = null;
        #region IHttpModule Members

        void IHttpModule.Dispose()
        {
            throw new NotImplementedException();
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            httpApp = context;
        }

        /// <summary>
        /// This is the first event that triggers in request pipeline to //IIS. Best place to manipulate the output that is send to client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_BeginRequest(object sender, EventArgs e)
        {
            char[] seprator= {'/'};
            if (httpApp.Context.Request.Path.Contains("Categories")) //if the request url path consists of categories word then only we want to redirect otherwise normal processing should be done
            {
                string categoryName = httpApp.Context.Request.Path.Split(seprator, StringSplitOptions.None)[2]; //getting the required element from the array
                //redirecting to actual page with query string this will be sleath forwarding user wont notice query string in his browser address bar
                httpApp.Context.RewritePath("~/Products.aspx?cn=" + categoryName);
            }
        }

        #endregion
    }

As mentioned I use BeginRequest event and look for current requested page. Do some string manipulations and then using RewritePath method of the httpApplicaton context , I redirect to the actual page. But wait a minute will user be seeing this path or user friendly path in the address bar of the browser. The rewriter is smart enough it does a sleath forwarding so the user will never come to know what is the actual path the server has redirected to him.

CLOSURE

HttpModules can do amazing things for you. Download the sample code from here. You will be requiring Northwind sample database to run the solution. Please rename the file extension from .doc to .rar

Extending Asp.net Calendar

INTRODUCTION

Everyone of you is familiar with asp.net calendar control. I am sure you must have used in most of your projects. Working on my recent SharePoint project , I was required to develop a webpart which is the calendar that displays all the events from the table in the corresponding cell of the calendar control. Though there are many third party controls are available to do this job by setting the few properties here and there. But in this case my client had a limited budget (Indeed it is the fact the enterprises are shrinking their IT budgets), so he told me to use something that is readily available with some programming efforts. As the famous saying goes “THE CLIENT IS ALWAYS RIGHT” , I have to do whatever he had proposed. In this short post I shall be sharing my solution with you.

CLIENT REQUIREMENTS

Being Event Management company , the client wanted to display the upcoming events in the calendar. Here are the requirements in brief

  1. All the date cells of the events should be highlighted with some background color
  2. When user gets its mouse over on the date cell , a tooltip should be displayed of the title of the event
  3. When user clicks on the date cell , it should navigate to the details of the event.

MY APPROACH

Having worked with the calendar control in my past projects , I knew this could be easily achievable. The rich object model of calendar control exposes one of the event called
DayRender. This event gets triggered for each and every date cells that are being rendered in the browser. The DayRenderEventArgs which is the argument of this event add an icing to the cake. This class exposes the cell property , which of TableCell Type. This gives you the power to extend the calendar control by overriding the default render behavior of the date cell. So before diving into the code , let us look at the figure below which shows the Event table definition.

Events Table Structure

The code of my logic is shown below

protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
List eventList = new List();
eventList =(List)Session["Events"];
Event evt;
evt = eventList.Where(ed => Convert.ToDateTime(ed.EventDate).ToString("dd-MMM-yyyy") == e.Day.Date.ToString("dd-MMM-yyyy")).Select(ev => ev).FirstOrDefault();

if (evt != null)

{

e.Cell.Attributes.Add(“bgcolor”, “#faebd7”);

e.Cell.ToolTip = evt.EventTitle;

e.Cell.Attributes.Add(“onclick”, “javascript:goToUrl(‘” + evt.NavigationUrl + “‘)”);

e.Cell.Style.Add(“cursor”, “pointer”);

}

else

{

e.Cell.ToolTip = null ;

}

}

As I am using Linq to SQL in the page load event I retrieve all the events and store them in the session. The reason why I am doing so is that as mentioned above that the DayRender event of the calendar control fires for each and every date cell that is getting rendered on the browser. Hence it is not a good practice to create Linq Datacontext object everytime when the event gets fired this can be a disaster and can affect your application performance. Hence all the database operations are performed on the PageLoad event and the output is stored in the session variable. Then using the Linq Lambda expressions I find whether the date that is getting rendered is matching to my event date. If I find the matching record I override the default behaviour of that cell date.
Another thing that needs to be kept in mind is to set the calendar’s SelectionMode property to None. This is very important to avoid the postbacks on all the dates and user cannot click on any other dates except for the event dates. The event dates also that he clicks , the navigation happens through JavaScript and no postbacks happen.

CLOSURE

According to me the difference between average asp.net developer and smart asp.net developer is the knowledge of Javascript and Css. These two skills can make you distinct and you can do wonders in your application. You can even roll out your own custom controls library. Think about it.
Download the sample code. Please rename the file extension from .doc to .rar

How to enable asp.net application to use application services

Recently I was asked by one of my apprentice at Silicon India as how do I enabled my asp.net application to use services like Membership and roles.
I have prepared a small video to help her out. I taught it would be good idea to publish this video on my blog to help the community.
So here it is Enjoy…)
The tutorialvideo.rar file consits 2 files
1)tutotrial video (.wmv format)
2)Sample web.config file which shows all configuration settings.

Please note you need to change the extension of the downloaded file from .doc to .rar
Download now