Routing Feature in ASP.Net 4.0

Hi Friends,

Today, I would like to talk about the routing feature which is been introduced in the ASP.Net 4.0. here, in this case what happens basically, it will take an existing set of pages and re-write the urls in a frindly way. when i say friendly way it means user understandable, SEO optimized etc. so, the main enhancement which we see in asp.net 4.0 release is that routing module has been integrated by default for web forms. so, it has now become very easy to map the url request with the endpoints which we specify during configuring the same. so, what it exactly produce is come out with completely different kind of url scheme.

So, now see how does it work. well it uses the same pagerouteTable which ASP.Net MVC uses and in order for that to work, there is a handler PageRouteHandler which is automatically installed in ASP.Net 4. so, it’s job off course to dispatch requests onto pages. and the other interesting which is also included with this, is new function of RouteCollection is RouteCollection.MapPageRoute. basically, it defines the route. so, these things are pre-requisites for re-architecting the url scheme of the site.

routing1 routing2nd

now, in order to bring in routing i need to write the same in global.asax file.  below, you can see the definition of MapPageRoute function.

routing3rd

routing4th routing5th routing6th

 

but, here is catch i need to do one more configuration for running the same in IIS, i need to tell IIS to run managed Modules, otherwise, it would result me 404. here, it worked because i ran the same from my file system. so, we can instruct IIS from the web.config file by adding a simple entry as shown below.

routing7th

 

so, the above instruction will make sure, that it will pickup the managed module installed for routing engine in ASP.Net 4.0. so, these are the basics. now, let’s focus on certain key points like ordering of route entries. This is very crucial because the 1st match is going to win.

Other important thing is that physical file will still take the precedence over  route tables. so, it means using routing doesn’t change the existing functionality of ASP.Net means page based traversing, this will always remain as it is.

Another important thing is parameterized routes. it’s very much like query strings. so, rather than using query string, here we’ll be using segments of url, which is preferable as it is less prone to be hacked and understood by the hackers.

so, let’s see parameterized inputs. so, for this let me add one blank label on the page and the intention is just to grab the parameter value on the page load itself and the way i grab the value from the parameter is using the Page.RouteData to extract the data passed in the parameter like below

routing8th routing9th routing10th

so, as you see above, this is 3 steps technique. but the crucial thing is route definition and fetching the same. however, you could also map the same to 404 url, in case there are certain values coming which doesn’t satisfy the scheme.

so, with this i would like to wrap this. Till then say tuned and happy coding.

Thanks,
Rahul
Happy Coding

658 total views, no views today

Client ID Mode in ASP.Net 4.0

Hi Friends,

Just for the sake of simplicity, i thought to blog about New Client Id Mode which is been incorporated in the ASP.Net 4.0 Version.  So, Basically Client ID Mode lets you control Client Id’s of the server controls. It basically comes with 4 different flavors. These are
1) AutoID:- This one is the same as on 3.5 version or earlier one
2) Static:- What you type, that is going to be used.
3) Predictable:- Basically, concatenates the naming containers which one can set with new properties.
4) Inherit(Default):- So, this is the default one. This basically relies on whatever immediate parent specifies.

so, why basically client id controls are really important?

Hmmm, that’s because, the gradual shift of web programming towards client side like with the inclusion of jquery libraries, other 3rd party JS libraries, where in you need to couple the controls on the rendered page or before rendering with certain activity, may be to validate them or tweak the controls during load time, i mean whatever, but for handling the same you should be familiar with the naming conventions of the rendered client ids.

So, let’s go and try out Client ID Mode. So, am going to test the same with a very basic sample Asp.Net website template.

clientIDMode_2

 

Now, here in the above case i have set the clientIdMode=”AutoID”, which means the page will behave as it used to be in 3.5 version and earlier. So, now see that what kind of identifier was generated for the same.

clientIDMode_3rd

clientIDMode_4th see, this was the identifier which is being generated. so, @ this stage if i have do certain client side validations on these kind of ids, this is going to be real mess.

now, look @ the behavior in the default mode which is predictable mode.

clientIDMode_5th

since, am using master page, hence it took the content page name and concatenated with my label name, so this is somewhat very obvious which we can take into account and write the script terminology based on that.

However, my personal favorite is clientIdMode =”‘Static”  which means whatever am typing as my identifier name, same is going to be rendered in there on the page as shown below.

clientIDMode_6th

clientIDMode_7th

 

and in case of inherited, it is going to produce the same result as it produced in the case of Predictable, because i have set the same @ top level. hence that is going to inherit from the same. so, with this I would like to wrap this. Thanks for your time. Till then, stay tuned and happy coding.

Thanks,
Rahul
Happy coding

990 total views, no views today

Anonymous Types in C#

Hi Friends,

In today’s discussion, we’ll see anonymous types. Well by books, Anonymous types are strongly typed, immutable with a bunch of properties. we basically create the instance of anonymous types by basically providing properties value like shown below.

so, I have created a var person and created an instance the next thing is anonymous
initializer, and this is created a whole new class behind the scenes. In order to inspect the same what you can do is inspect the same in Reflector using Ildasm. It will show you a bunch of scary things out there. but, for this discussion, am keeping the things fairly simple and just focusing on the high level things.
var person= new { FirstName = “Rahul”, LastName = “Sahay” };

now, there are certain catch with the same, If i try to change the order of the same,
person = new { LastName = “scott”,FirstName = “dave” }; // will popup error

i cannot do that because, the 1st one which i created has got the same in reference like below

let me just show you the var indication.

anony1st

 

Now, when i run the same it will print the below output like below:

anony2nd

 

so, having said to my earlier statement anonymous types are strongly typed. you will get fairly good intellisense while writing the code as shown below.

anony3rd

also, one more point when i mentioned that anonymous types are immutable. this can be referred as below like

anony4th

 

so, it’s says that it’s a readonly property cannot be intervened again, once initialized.

now, we have liberty of having embedded anonymous types as well like shown below

anony5th

 

now, when i run the same, it will print the below string inside braces obviously.

anony6th

 

However, this is ok when i have to print one variable like person kind of thing,how about
when i have to take care of bunch of values, so in this case i need to consider Implicitly Typed Arrays like shown below

anony7th

obviously, since i have to loop through the array, so i have changed the printing condition and now, the output would go like this

anony8th

 

So, now with this i would like to wrap this discussion. Till then, stay tuned and Happy Coding.

Thanks,
Rahul
Happy Coding

737 total views, no views today

Posted in C#

View State Improvements in ASP.Net 4.0

Hi friends,

Today, in this discussion, i would like to stress upon View State improvements which is done in ASP.Net 4.0 series. So, it says basically, that view state can be disabled completely @ page level, but it can be enabled @ control level. so, it means you can disable the same @ top level and re-enable the same control level selectively. Initially, it was like disable view state or enable view state, means all or nothing.

so, let’s get started, let’s explain the same visual studio itself.

1st

so, here i have added 2 things, a simple label just to track the no of page loads and one table just to make the view state size huge.

2nd

 

so, when i do every time postback, it will increment the value by 1. so, viewstate is basically a mechanism for remembering the control state.

3rd 4th 5th 6th

 

so, as you see upon submitting that counter gets incremented, but when i saw the page source, i could see the real mess, here the thing, is on every subsequent request viewstate of the page is getting incremented and hence will cause page to load slow. this chunk is basically base 64 encoding which is basically view state encoding mechanism. so, basically what we used to do @ 1st attempt to disable the viewstate @ the page level likewise

7th

 

and that would certainly solve the problem as this will disable completely viewstate from the page and page gets optimized, bang we achieved to the solution. but, we certainly didn’t want this. we wanted to keep track of no of clicks, how would we achieve then, hmmm if you try doing enableViewstate=”True” @ control level, that would not work. so, what we would do instead, we would use ViewStateMode property as shown below.

8th

now, this will solve the problem. Now, new view state will look like this

9th

so, with this i would like to wrap, till then stay tuned and happy coding.

Thanks,
Rahul

809 total views, 1 views today

C# 4.0 Features Session 1

Hi Friends,

Today, we’ll discuss the basics of C#. I’ll be taking this on C# 4.0 features most of the time and some normal scenarios, which we generally encounter on daily basis like below. this is a simple example.

//Error, object doesn’t contain anything say Length
object a = “hello world”;
Console.WriteLine(a.Length);

Now, let’s try to fix this

// Valid One, how casting saves the code
object a = “hello world”;
string b = (string)a;
Console.WriteLine(b.Length);

so, now when i run this this will give me output 11 obviously length of the string. so, here casting saves us. Important point casting is evaluated @ run time.

so, now let me take one more example to prove my point that how casting is evaluated @ run time. let’s consider below scenario

// will throw error @ run time saying unable to cast object
//Unable to cast object of type ‘System.Collections.Generic.List`1[System.Int32]’ to type ‘System.String’.
object a = new List<int>();
string b = (string)a;
Console.WriteLine(b.Length);

when you compile the above code, this will compile well, but when you run the same, it will throw the above error.

Now, let’s consider another scenario. so, an object either be null or it’s a way to reach out there. so, if assign that object null and tried to walkthough that object and take out the length property even after casting, that would return exception not empty value.

// Null reference exception, tried to walkthough the null object.
object a = null;
string b = (string)a;
Console.WriteLine(b.Length);

Now, dynamic keyword resolves the thing @ run time. so, if you see below snippet, i tried to print the Length of the string, but while writing i didn’t get the intellisense also it evaluates the things correctly.  so, the thing is same object is utilized as string and also as object of int array and produced the correct result.

// Dynamic keyword sorts the thing out @ run time
dynamic a = “hello world”;
Console.WriteLine(a.Length);
a = new int[] { 1, 2, 3 };
Console.WriteLine(a.Length);

// Strongly typed, these are static types, hence opcode has been evaluted by compiler. -100 will o/p

int a = 100;
int b = 200;
Console.WriteLine(a-b);

// lazy typed
dynamic a = 100;
dynamic b = 200;
Console.WriteLine(a-b);

even this will do the same stuff, but there is whole lot of things going in, you can confirm the same from ILDASM. Important Point Dynamic comes with cost(performance cost).

Now, let’s talk about little bit about named arguments and optional parameters. Let’s consider the below scenario.

//Simple One
static void Main(string[] args)
{
x(“Hello C#”); // provided argument
}

static void x(string y) // declared parameter, kind of local variable
{
Console.WriteLine(y);
}

Now, in case of named arguments, i could go ahead and pass the value with variable name as shown below. also, it doesn’t matter how you are doing ordering and all. if you have assigned the same with name, that’s it your job is done. compiler will position it accordingly.

// Named Arguments
static void Main(string[] args)
{
x(z:”world”, y:”Hello”); // provided argument //named argument doesn’t matter ordering
}

static void x(string y, string z) // declared parameter, kind of local variable
{
Console.WriteLine(y+z);
}

//Optional Paramter, it helps us to skip writing additional overload methods like below
// here the output would be worldworld,rahulworld,daveworld,scottworld,helloworld
//but, the thing is you can’t have 1st paramter as optional if it’s alone
static void Main(string[] args)
{
x(“world”); // provided argument //named argument doesn’t matter ordering
x(“Rahul”);
x(“Dave”);
x(“Scott”);
x();
}

static void x(string y=”Hello”, string z=”World”) // declared parameter, kind of local variable
{
Console.WriteLine(y+z);
}

x(y:”world”); // provided argument //named argument doesn’t matter ordering
x(y:”Rahul”);
x(y:”Dave”);
x(y: “Scott”);
x();
// this will also produce you the same result.
// But, here is a catch you can’t put named parameter 1st and then the positional one, it will throw error
x(z: “Scott”, “tom”); // Invalid one

I hope, this session could have been useful. we’ll d deep dive in next C# sessions. Till then stay tuned and happy coding.

Thanks,
Rahul
Happy Coding

675 total views, no views today

Razor Views in ASP.Net MVC

Hi Friends,

Today, in this discussion, we’ll start with Razor views. The Razor view engine allows user to produce HTML output. Basically it’s a combination of data and html template. These are the basically files which endup with .cshtml extension. So, in order to put the data on the markup, I’ll use C# sharp code in the razor view.  Now, in  order to better explain the same let’s go ahead a movie reviews controller and select the option with empty read/write as shown below.

9th

 

Now, let me go ahead and one model class which will be used with my controller and i call this class as MovieReview and i’ll put certain property in there to expose the same as shown below.

10th

 

But, right now, in order to just test the same, we need some sort of in memory data. we’ll add the same in the controller itself as shown below.

11th

 

now, what i need to do is use the same code above in my index action to list the movie based on the name. so, for doing the same i’ll use a little linq query to achieve the same as shown below in the example

12th

 

Now, since i have not added view for the same so far, so i’ll add a view for the same so that it can be rendered in the browser. now, for doing the same i’ll rt-click on the index action and say Add view,  but this time i want to create an strongly typed view so that my model class gets available in my view like shown below and i’ll also select list from the scaffolding template so that it will generate code required for the same in the view as shown below.

13th

14th

 

15th 16th

so, this is a basic view which is strongly typed against the Movie Review. and now, this is simply going to create a table with all the properties in there. In the next section, we’ll see that how to optimize the view and play with the razor syntax. Till then stay tuned and happy coding.

Thanks,
Rahul
Happy Coding

529 total views, no views today

Global Filters with ASP.Net MVC

Hi Friends,

In today’s discussion, we’ll quickly see that how global filters make our life simple and easy by handling the unfortunate errors @ every controller level. so, before jumping into discussion, let’s 1st understand that what is global filter. A global filter for example HandleError attribute is something which displays a friendly error page to the user when something goes wrong. Let’s see the same in action. In the below snippet, I have commented out the [Authorize] attribute, and purposely thrown one exception at the beginning of the controller itself and the result as excepted, generic error handler page of .net as shown below.

1st 2nd

 

so, now how to fix this kind of handled situation. The very simple change which i could do here is set the custom errors attribute’smode to On. and then, just refresh the page, then we’ll see a friendly error page as produced below.

3rd 4th

 

But, the reason we end up here is primarily because of HandleError attribute. it is providing post processing logic on action and it actually decides if an exception is escaped from an action, it will display an error view instead of yellow screen. the error view basically resides in the application itself, so if you go to views –> shared –> Error.cshtml page. so, basically an error view is just a razor view.

5th

 

Now, let me show that thing from where, this view is getting triggered. This is from filterconfig.cs file under App_Start folder as shown below.

6th

 

Now, let me show, if i comment out the above line then what will happen.

7th 8th

 

so, it again landed in the .net generic error handler page. So, this was the Global Filters in a nut shell. In the next section, we’ll see more about MVC, Till then stay tuned and good bye.

Thanks,
Rahul
Happy Coding

625 total views, no views today

Action Filters with ASP.Net MVC

Hi Friends,

In this section am going to discuss brief about Action Filters and how this is applied in the ASP.Net MVC application. But, before jumping into the details of Action Filters, let’s look @ the definition of Action Filters:- “Action filters are the components that you want to apply to logics which are going to be used across multiple controllers. So, the significance of this, it actually prevents duplication of code inside each controller. ”

There, could be as many

Name Description
OutPut Cache Cache the Output of a controller
Authorize Technique to force only authentic user to login
ValidateAntiForgeryToken Prevents cross site forgeries
HandleError In case of unhandled exception, view can be specified
Validate Input Dangerous one, turn off request validation and allow any input

Now, in case of OutPut cache attribute,

This tells the run time that it’s allowed to cache the final output of some action and use it again till the specified time. when you apply these attributes to few places, you can dramatically increase the performance of the application. Another example could be authorize attribute, it’s job is to check whether authentic user is logged or not, this is many times tied up with roles as well.

Now, let’s look at the small example below for Authorize attribute

[Authorize]
[HttpGet]
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

Now, when i build and invoke the below url, it will

/Movie/Titanic

it will produce the login screen as shown below:-action filters

so, this is the action filter in brief. For the deep dive and know more about the Actions Filters in action subscribe to ONLINE ASP.Net MVC workshop. Till then stay tuned and happy coding.

Thanks,
Rahul

573 total views, 1 views today

Use of Http Accept Verbs in MVC

Hi Friends,

Let me give one scenario, where in it becomes very necessary to use HTTP Accept verbs to identify the action whether it’s a Get Request or Post or Delete or Put or combination of any these.

Let’s look @ the below example

public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

public ActionResult Search()
{

return Content(“Hello world”);
}

when you build the solution, it will build successfully, but when you invoke the app, it will give you below error as shown below.

MVC_accept_verb

Here, what happened exactly, MVC framework tries to invoke the search action but unable to distinguish between the same, hence produced the exception. so, for these kind of scenarios, we have HTTP Accept verbs which literally tells the C# compiler to treat one response for HTTP Get request and the other one for HTTP Post.

[HttpGet]
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

[HttpPost]
public ActionResult Search()
{

return Content(“Hello world”);
}

Now, when i do the build and refresh the browser, it will produce the desired result. Actual scenario, will be explained in a much cleaner way in the upcoming workshop for ASP.Net MVC. Till then stay tuned and happy coding.

Thanks,
Rahul

1,225 total views, no views today

Different Kinds of Action Results in action in MVC

Hi Friends,

I have just put a small snippet for different kinds of action results in MVC. Detailed sample will be explained in the up coming ASP.Net MVC.

public ActionResult Search(string name)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

//Movie/Titanic
routes.MapRoute(“movie”,
“movie/{name}”,
new { controller = “Movie”, action = “Search”, name=UrlParameter.Optional});

public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

// Redirect Permannent will return http status code 301 and temp redirect will return 302
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return RedirectPermanent(“http://myview.rahulnivi.net”);
}

// Redirect To action
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return RedirectToAction(“Index”, “Home”);
}
// Redirect To action with values
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return RedirectToAction(“Index”, “Home”, new { name=name});
}

// Redirect to Route
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return RedirectToRoute(“Default”, new { controller=”Home”, action=”About”});
}

// Return a file
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return File(Server.MapPath(“~/Content/Site.css”),”text/css”);
}

//Return JSON result

public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Json(new { Message = message, Name = “Rahul Sahay” }, JsonRequestBehavior.AllowGet);
}

Thanks,
Rahul
Happy Coding

648 total views, no views today