Enum.HasFlag method in C# 4.0

Enums in dot net programming is a great facility and we all used it to increase code readability. In earlier version of .NET framework we don’t have any method anything that will check whether a value is assigned to it or not. In C# 4.0 we have new static method called HasFlag which will check that particular value is assigned or not. Let’s take an example for that. First I have created a enum called PaymentType which could have two values Credit Card or Debit Card. Just like following.

public enum PaymentType
{
DebitCard=1,
CreditCard=2
}
Now We are going to assigned one of the value to this enum instance and then with the help of HasFlag method we are going to check whether particular value is assigned to enum or not like following.
protected void Page_Load(object sender, EventArgs e)
{
PaymentType paymentType = PaymentType.CreditCard;

if (paymentType.HasFlag(PaymentType.DebitCard))
{
Response.Write("Process Debit Card");
}
if (paymentType.HasFlag(PaymentType.CreditCard))
{
Response.Write("Process Credit Card");
}

}
Now Let’s check out in browser as following.

Enum.Has Flag in C# 4.0

As expected it will print process Credit Card as we have assigned that value to enum. That’s it It’s so simple and cool. Stay tuned for more.. Happy Programming..

Technorati Tags: ,,
Shout it

ASP.NET 4.0- Menu control enhancement.

Till asp.net 3.5 asp.net menu control was rendered through table. And we all know that it is very hard to have CSS applied to table. For a professional look of our website a CSS is must required thing. But in asp.net 4.0 Menu control is table less it will loaded with UL and LI tags which is easier to manage through CSS. Another problem with table is it will create a large html which will increase your asp.net page KB and decrease your performance. While with UL and LI Tags its very easy very short. So You page KB Size will also be down.

Let’s take a simple example. Let’s Create a menu control in asp.net with four menu item like following.

<asp:Menu ID="myCustomMenu"  runat="server" >
<Items>
<asp:MenuItem Text="Menu1" Value="Menu1"></asp:MenuItem>
<asp:MenuItem Text="Menu2" Value="Menu2"></asp:MenuItem>
<asp:MenuItem Text="Menu3" Value="Menu3"></asp:MenuItem>
<asp:MenuItem Text="Menu4" Value="Menu4"></asp:MenuItem>
</Items>
</asp:Menu>
It will render menu in browser like following.

asp.net menu control enhancement in vesion 4.0

Now If we render this menu control with tables then HTML as you can see via view page source like following.

Old menu in asp.net 3.5 with table.

Now If in asp.net 4.0 It will be loaded with UL and LI tags and if you now see page source then it will look like following. Which will have must lesser HTML then it was earlier like following.

MenuwithoutTable

So isn’t that great performance enhancement?.. It’s very cool. If you still like old way doing with tables then in asp.net 4.0 there is property called ‘RenderingMode’ is given. So you can set RenderingMode=Table then it will load menu control with table otherwise it will load menu control with UL and LI Tags.

That’s it..Stay tuned for more..Happy programming..

Technorati Tags: ,
Shout it

ASP.NET Error Handling: Creating an extension method to send error email

Error handling in asp.net required to handle any kind of error occurred. We all are using that in one or another scenario. But some errors are there which will occur in some specific scenario in production environment in this case We can’t show our programming errors to the End user. So we are going to put a error page over there or whatever best suited as per our requirement. But as a programmer we should know that error so we can track the scenario and we can solve that error or can handle error. In this kind of situation an Error Email comes handy. Whenever any occurs in system it will going to send error in our email.
Here I am going to write a extension method which will send errors in email. From asp.net 3.5 or higher version of .NET framework its provides a unique way to extend your classes. Here you can fine more information about extension method. So lets create extension method via implementing a static class like following. I am going to use same code for sending email via my Gmail account from here. Following is code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace Experiement
{
  public static class MyExtension
  {
      public static void SendErrorEmail(this Exception ex)
      {
          MailMessage mailMessage = new MailMessage(new MailAddress("from@gmail.com")
                                     , new MailAddress("to@gmail.com"));
          mailMessage.Subject = "Exception Occured in your site";
          mailMessage.IsBodyHtml = true;

          System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();

          errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>",
                       "Exception",ex.Message));
          errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>",
                       "Stack Trace", ex.StackTrace));

          if (ex.InnerException != null)
          {
              errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>",
                        " Inner Exception", ex.InnerException.Message));
              errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>",
                        "Inner Stack Trace", ex.InnerException.StackTrace));
          }

          mailMessage.Body = errorMessage.ToString();

          System.Net.NetworkCredential networkCredentials = new
          System.Net.NetworkCredential("youraccount@gmail.com", "password");
        
          SmtpClient smtpClient = new SmtpClient();
          smtpClient.EnableSsl = true;
          smtpClient.UseDefaultCredentials = false;
          smtpClient.Credentials = networkCredentials;
          smtpClient.Host = "smtp.gmail.com";
          smtpClient.Port = 587;
          smtpClient.Send(mailMessage);

        
      }
  }
}
After creating an extension method let us that extension method to handle error like following in page load event of page.
using System;

namespace Experiement
{
  public partial class WebForm1 : System.Web.UI.Page
  {
      protected void Page_Load(object sender,System.EventArgs e)
      {
          try
          {
              throw new Exception("My custom Exception");
          }
          catch (Exception ex)
          {
              ex.SendErrorEmail();
              Response.Write(ex.Message);
          }
      }

  }
}
Now in above code I have generated custom exception for example but in production It can be any Exception. And you can see I have use ex.SendErrorEmail() function in catch block to send email. That’s it.

Now it will throw exception and you will email in your email box like below.

Error Handling in ASP.NET

That’s its. It’s so simple…Stay tuned for more.. Happy programming..


ASP.NET Performance tip- Combine multiple script file into one request with script manager

We all need java script for our web application and we storing our JavaScript code in .js files. Now If we have more then .js file then our browser will create a new request for each .js file. Which is a little overhead in terms of performance. If you have very big enterprise application you will have so much over head for this. Asp.net Script Manager provides a feature to combine multiple JavaScript into one request but you must remember that this feature will be available only with .NET Framework 3.5 sp1 or higher versions.

Let’s take a simple example. I am having two javascript files Jscrip1.js and Jscript2.js both are having separate functions.

//Jscript1.js
function Task1() {
alert('task1');
}
Here is another one for another file.
////Jscript1.js
function Task2() {
alert('task2');
}
Now I am adding script reference with script manager and using this function in my code like this.
<form id="form1" runat="server">
<asp:ScriptManager ID="myScriptManager" runat="server" >
<Scripts>
<asp:ScriptReference Path="~/JScript1.js" />
<asp:ScriptReference Path="~/JScript2.js" />
</Scripts>
</asp:ScriptManager>
<script language="javascript" type="text/javascript">
Task1();
Task2();         
</script>
</form>
Now Let’s test in Firefox with Lori plug-in which will show you how many request are made for this. Here is output of that. You can see 5 Requests are there.LoriPlugin

Now let’s do same thing in with ASP.NET Script Manager combined script feature. Like following

<form id="form1" runat="server">
<asp:ScriptManager ID="myScriptManager" runat="server" >
<CompositeScript>
<Scripts>
<asp:ScriptReference Path="~/JScript1.js" />
<asp:ScriptReference Path="~/JScript2.js" />
</Scripts>

</CompositeScript>
</asp:ScriptManager>
<script language="javascript" type="text/javascript">
Task1();
Task2();         
</script>
</form>
Now let’s run it and let’s see how many request are there like following.LoriPlugin1

As you can see now we have only 4 request compare to 5 request earlier. So script manager combined multiple script into one request. So if you have lots of javascript files you can save your loading time with this with combining multiple script files into one request. Hope you liked it. Stay tuned for more!!!.. Happy programming..
Shout it

Programmatically updating one update panel elements from another update panel elements

While taking interviews for asp.net candidate I am often asking this question but most peoples are not able to give this answer. So I decided to write a blog post about this. Here is the scenario. There are two update panels in my html code in first update panel there is textbox hello world and another update panel there is a button called btnHelloWorld. Now I want to update textbox text in button click event without post back. But in normal scenario It will not update the textbox text as both are in different update panel. Here is the code for that.

<form id="form1" runat="server">
<asp:ScriptManager ID="myScriptManager" runat="server" EnableCdn="true"></asp:ScriptManager>
<asp:UpdatePanel ID="firstUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtHelloWorld" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="secondUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnHelloWorld" runat="server" Text="Print Hello World"
onclick="btnHelloWorld_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Here comes magic!!. Lots of people don’t know that update panel are providing the Update method from which we can programmatically update the update panel elements without post back. Below is code for that.

protected void btnHelloWorld_Click(object sender, System.EventArgs e)
{
txtHelloWorld.Text = "Hello World!!!";
firstUpdatePanel.Update();
}

That’s it here I have updated the firstUpdatePanel from the code!!!. Hope you liked it.. Stay tuned for more..Happy Programming..


Technorati Tags: ,

Shout it

Sending mail with Gmail Account using System.Net.Mail in ASP.NET

Any web application is in complete without mail functionality you should have to write send mail functionality. Like if there is shopping cart application for example then when a order created on the shopping cart you need to send an email to administrator of website for Order notification and for customer you need to send an email of receipt of order. So any web application is not complete without sending email. This post is also all about sending email. In post I will explain that how we can send emails from our Gmail Account without purchasing any smtp server etc.

There are some limitations for sending email from Gmail Account. Please note following things.

  1. Gmail will have fixed number of quota for sending emails per day. So you can not send more then that emails for the day.
  2. Your from email address always will be your account email address which you are using for sending email.
  3. You can not send an email to unlimited numbers of people. Gmail ant spamming policy will restrict this.
  4. Gmail provide both Popup and SMTP settings both should be active in your account where you testing. You can enable that via clicking on setting link in gmail account and go to Forwarding and POP/Imap.

So if you are using mail functionality for limited emails then Gmail is Best option. But if you are sending thousand of email daily then it will not be Good Idea.

Here is the code for sending mail from Gmail Account.

using System.Net.Mail;

namespace Experiement
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender,System.EventArgs e)
{
MailMessage mailMessage = new MailMessage(new MailAddress("from@gmail.com")
,new MailAddress("to@yahoo.com"));
mailMessage.Subject = "Sending mail through gmail account";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "<B>Sending mail thorugh gmail from asp.net</B>";

System.Net.NetworkCredential networkCredentials = new
System.Net.NetworkCredential("yourgmailaddress@gmail.com", "yourpassword");

SmtpClient smtpClient = new SmtpClient();
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = networkCredentials;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Send(mailMessage);

Response.Write("Mail Successfully sent");

}
}
}

That’s run this application and you will get like below in your account.


SendMail


Technorati Tags: ,,
Shout it

The remote host closed the connection. The error code is 0x80070057

While creating a PDF or any file with asp.net pages I was getting following error.

Exception Type:System.Web.HttpException
The remote host closed the connection
. The error code is 0x80072746.
at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status,
Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async)
at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)
at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpResponse.Flush()
at System.Web.UI.HttpResponseWrapper.System.Web.UI.IHttpResponse.Flush()
at System.Web.UI.PageRequestManager.RenderFormCallback(HtmlTextWriter writer,
Control containerControl)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection
children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer,
ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter
adapter)
at System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer)
at
System.Web.UI.HtmlFormWrapper.System.Web.UI.IHtmlForm.RenderControl(HtmlTextWriter
writer)
at System.Web.UI.PageRequestManager.RenderPageCallback(HtmlTextWriter writer,
Control pageControl)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection
children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer,
ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter
adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)
Exception Type:System.Web.HttpException
The remote host closed the connection. The error code is 0x80072746.
at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status,

After searching and analyzing I have found that client was disconnected and still I am flushing the response which I am doing for creating PDF files from the stream.

To fix this kind of error we can use Response.IsClientConnected property to check whether client is connected or not and then we can flush and end response from client.

Here is the sample code to fix that problem.

 if (Response.IsClientConnected)
           {
               Response.Flush();
               Response.End();
           }

That’s it Hope this will help you..Stay tuned for more.. Till that Happy Programming!!


Request format is unrecognized for URL unexpectedly ending exception in web service.

Recently I was getting error when I am calling web service using Java script. I searching on net and debugging I have found following things.

Any web service support three kinds of protocol HttpGet,HttpPost and SOAP. In framework 1.0 it was enabled by default but after 1.0 framework it will not be enabled by default due to security issues and WS-Specifications. So we have to enabled them via putting configuration settings in web.config. Here is the code for that.

<configuration>
<system.web>
<webservices>
<protocols>
<add name="HttpGet"></add>
<add name="HttpPost"></add>
</protocols>
</webservices>
</system.web>
</configuration>
Hope this will help you. Stay tuned for more. Till that Happy programming!!!.

Technorati Tags: ,,,

Shout it

ASP.NET MVC 3 RC2 Razor- Syntax Intellisense in view.

Microsoft has recently launched Razor view engine with ASP.NET MVC RC2. It’s going to be promising one. There are lots of features bundled with this view engine. But in earlier version of ASP.NET 3 MVC. We were are not having Synatx intellisense provided for asp.net mvc views in Visual Studio 2010. So either we have to depend third party tools like Resharper or we have to manage it without intellisesnse. But with ASP.NET MVC 3 RC2 Microsoft has moved one step forward and its providing syntax intellisense without installing any third party addons in Visual Studio. Here is example of it.

Syntax
Hope you liked it. Stay tuned for more.. Happy Programming..

Shout it

ASP.NET 4.0 Script Manager Enhancement Part-2 AjaxFrameworkMode Property

This will be a second part of ASP.NET 4.0 Script Manager enhancement. In this post I am going to explain about AjaxFrameworkMode Property. In Earlier asp.net version of script manager it will load entire Microsoft Ajax library whether its required or not. In asp.net 4.0 script manager we are having AjaxFrameMode property where we can set mode as explicit and we add only js that are required or not.

There are three values of AjaxFrameworkMode properties supported in asp.net

  1. Enabled- Specified that ASP.NET 4.0 scriptmanager will automatically load MicrosoftAjax.js file which is core element of Microsoft Ajax library.
  2. Disabled- This Specified that Microsoft Ajax Script features are disabled and script manager will not have any reference to any javascript files.
  3. Explicit- Specifies that you will explicitly include script references to individual framework core script file that your page requires, and that you will include references to the dependencies that each script file requires.

So here is example if require only Microsoftcore.js then we can use this explicitly without loading other unnecessary files.

<asp:ScriptManager ID="myScirptManager" AjaxFrameworkMode="Explicit" runat="server">

<Scripts>
<asp:ScriptReference Name="MicrosoftAjaxCore.js" />

</Scripts>
</asp:ScriptManager>


Hope this will help you increase your performance. Stay tuned for more..

Shout it

ASP.NET 4.0- ScriptManager Enhancement Part-I- Enable CDN Property.

ASP.NET 4.0 has been a great step forward to the programming. Microsoft has done incredible job with the performance. One of them is Enable CDN Property in asp.net 4.0 Script Manager. Let's explore it in details. As you all know that Microsoft is Providing Content Delivery Network for all the Ajax script that is used by Microsoft Ajax and All version of Jquery and JQuery UI. This Script manager enable cdn property will fetch all the script from that CDN Automatically. Developer don't have to worry about. As you know new generation browsers are like IE8 and Firefox are creating a new thread of each JS or CSS include in Webpage if they are coming from the CDN(Content Delivery Network). So this will be a great measure step towards it. Let's take an example to explore the things. I am taking one simple example which will demonstrate use of this. I am tasking a Textbox and Button. On the button click event it will update textbox's text property. I am going to use update panel to use Microsoft Ajax. For that first I need a script manager so I have taken script manager and and I have set its property EnalbleCdn=true. So without posting back whole it post back only that portion which are required. I have putted textbox in content template of update panel and I have created asynchronous post back trigger for button click event. So it will update the textbox text without creating post back. Let's how I have created. Following are Simple HTML for that.
<body>
<form id="form1" runat="server">
<div>

<asp:ScriptManager ID="cdnScriptManager" EnableCdn="true" runat="server">
</asp:ScriptManager>  

<asp:UpdatePanel ID="cdnUpdatePanel" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtHelloWorld" runat="server"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnHelloWorld" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<BR />
<asp:Button ID="btnHelloWorld" runat="server" onclick="btnHelloWorld_Click"  Text="Hello World!!"/>


</div>
</form>
</body>

Now I am going to create a click event which will change textbox text’. Following is a code for that.

protected void btnHelloWorld_Click(object sender, EventArgs e)
{
txtHelloWorld.Text = "Hello World";
}

That’s it Let’s run that with Ctrl+ F5 and It will look in firefox browser like following.


ScriptManager4.0, ASP.NET 4.0 Enhacement


Now Let’s see its view source and see how it’s look like. Following is a screenshot of view source.


ViewSource

As you can see its fetching all the JS from Microsoft Ajax Content delivery network. Isn’t that great. You just to have enable CDN Property =true and It will do rest of Job. That’s power of asp.net 4.0. Hope you liked it. Stay tuned for more in Part 2.
Shout it

DotNetQuiz 2011 on BeyondRelational.com- Want to be quiz master or participant?

Test your knowledge with 31 Reputed persons (MVPS and bloggers) will ask question on each day of January and you need to give reply on that. You can win cool stuff.My friend Jacob Sebastian organizing this event on his site Beyondrelational.com to sharpen your dot net related knowledge. This Dot NET Quiz is a platform to verify your understanding of Microsoft .NET Technologies and enhance your skills around it. This is a general quiz which covers most of the .NET technology areas.

Want to be Quiz Master?

Also if you are well known blogger or Microsoft MVP then you can be Quiz master on the dotnetquiz 2011. Following are requirements to be quiz master on beyondrelational.com. I am also a quiz master on beyondrelational.com and

Quiz master eligibility:

You will be eligible to nominate yourself to become a quiz master if one of the following condition satisfies:

  • You are a Microsoft MVP
  • You are a Former Microsoft MVP
  • You are a recognized blogger
  • You are a recognized web master running one or more technology websites
  • You are an active participant of one or more technical forums
  • You are a consultant with considerable exposure to your technology area
  • You believe that you can be a good Quiz Master and got a passion for that

 

Selection Process:

Once you submit your nomination, the Quiz team will evaluate the details and will inform you the status of your submission. This usually takes a few weeks.

Quiz Master's Responsibilities:

Once you become a Quiz Master for a specific quiz, you are requested to take the following responsibilities.

  • Moderate the discussion thread after your question is published
  • Answer any clarification about your question that people ask in the forum
  • Review the answers and help us to award grades to the participants

For more information Please visit following page on beyondrelational.com

http://beyondrelational.com/quiz/nominations/0/new.aspx

Hope you liked it. Stay tuned!!!

Shout it

Microsoft silverlight 5.0 features for developers

Recently on Silverlight 5.0 firestarter event ScottGu has announced road map for Silverlight 5.0. There will be lots of features that will be there in silverlight 5.0 but here are few glimpses of Silverlight 5.0 Features.

Improved Data binding support and Better support for MVVM:

One of the greatest strength of Silverlight is its data binding. Microsoft is going to enhanced data binding by providing more ability to debug it. Developer will able to debug the binding expression and other stuff in Siverlight 5.0. Its also going to provide Ancestor Relative source binding which will allow property to bind with container control. MVVM pattern support will also be enhanced.

Performance and Speed Enhancement:

Now silverlight 5.0 will have support for 64bit browser support. So now you can use that silverlight application on 64 bit platform also. There is no need to take extra care for it.It will also have faster startup time and greater support for hardware acceleration. It will also provide end to end support for hard acceleration features of IE 9.

More support for Out Of Browser Application:

With Siverlight 4.0 Microsoft has announced new features called out of browser application and it has amazed lots of developer because now possibilities are unlimited with it. Now in silverlight 5.0 Out Of Browser application will have ability to Create Manage child windows just like windows forms or WPF Application. So you can fill power of desktop application with your out of browser application.

Testing Support with Visual Studio 2010:

Microsoft is going to add automated UI Testing support with Visual Studio 2010 with silverlight 5.0. So now we can test UI of Silverlight much faster.

Better Support for RIA Services:

RIA Services allows us to create N-tier application with silverlight via creating proxy classes on client and server both side. Now it will more features like complex type support, Custom type support for MVVM(Model View View Model) pattern.

WCF Enhancements:

There are lots of enhancement with WCF but key enhancement will WSTrust support.

Text and Printing Support:

Silverlight 5.0 will support vector base graphics. It will also support multicolumn text flow and linked text containers. It will full open type support,Postscript vector enhancement.

Improved Power Enhancement:

This will prevent screensaver from activating while you are watching videos on silverlight. Silverlight 5.0 is going add that smartness so it can determine while you are going to watch video and while you are not going watch videos.

Better support for graphics:

Silverlight 5.0 will provide in-depth support for 3D API. Now 3D rendering support is more enhancement in silverlight and 3D graphics can be rendered easily.

You can find more details on following links and also don’t forgot to view silverlight firestarter keynot video of scottgu.

http://www.silverlight.net/news/events/firestarter-labs/

http://blogs.msdn.com/b/katriend/archive/2010/12/06/silverlight-5-features-firestarter-keynote-and-sessions-resources.aspx

http://weblogs.asp.net/scottgu/archive/2010/12/02/announcing-silverlight-5.aspx

http://www.silverlight.net/news/events/firestarter/

http://www.microsoft.com/silverlight/future/

Hope this will help you. Stay tuned!!!.

Shout it
kick it on DotNetKicks.com

New blogger template for My blog - DotNetJaps

I have changed my blogger template to newer version of blogger. Hope you guys liked it. There are some difficulties over there but I still love the changes that blogger has offered. I know my old version of syntax highlighter is not working. But I am fixing that for all the older posts and already did it for some posts.

‘Change is in all things sweet.’

As a philosopher Aristotle has said we all should be ready to change. I have changed my blogger template due to following reasons.

  1. It’s more SEO Friendly. It is having less errors on w3c validations and It will increase search engine optimization for my blog. Still blogger template are not totally compliant like word press but blogger has decided to moved in that way so I am going to support that way.
  2. It has good way to monetize your blog.
  3. It has provided a new feature called ‘Pages’. You can create your own pages like I have created like asp.net interview questions etc. I will going to post some frequently asked interview questions over here.
  4. It has providing status same like Wordpress so its good be changed.

Above all, I have also changed my script high lighter version 3.0.83. So there might be some difficulties in older posts but I am going to fix one by one. If you found anything then please fill free to contact me via posting comment on my blog and I am going to fix that right away.

Here is screenshot my blog is look like.

MyBlog new blogger template

Please fill free to contact me if you have any question. I am going to start posting technical post soon. I need your support and I know you guys are going to provide me that.

Thanks once again all the readers who have made my blog successful.Keep reading it I will going to post more and more.

Technorati Tags: ,
Shout it

ASP.NET MVC Razor IsPost property with IF –Else loop

ASP.NET MVC Razor a new view engine from Microsoft looks very promising. Here are example of code where we can determine page is post back or not. It support a IsPost Property which will tell you whether page is post back or not. So based on that we can write code for handling post back. Also one of greatest feature of razor is we can write code for decision making like if else and other stuff with single @ statement isn’t that great stuff.

Here is the stuff how we can write the code with IsPost property.

@{
var Message="";
if(IsPost)
{
Message ="This is from the postback";
}
else
{
Message="This is without postback";
}
}
And we can now print that variable with following HTML Form.
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>
<p>@Message</p>
</form>

Here submit button will submit the form and based on that it will print message. Let’s see how it looks in browser before post back and after post back.

WithoutPostback

And After post back

AfterPostaback

So that’s it. Now you can do lots of stuff with IsPost property possibilities are unlimited!!. Hope this will help you..Happy Programming.

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com

Output caching with ASP.NET MVC Razor

Caching data greatly increase the website performance as its not going to do server round trip. I have already mentioned how you can use Output caching in web forms in earlier blog post here. Let’s see how we can do same thing with asp.net mvc. For this example I have used asp.net mvc razor. In asp.net mvc you can use OutputCache attribute to cache the output. Just like below.

[OutputCache(VaryByParam="none",Duration=60)]
public ActionResult Index()
{
ViewModel.Message = DateTime.Now.ToString();
return View();
}
Here it will cache the view for 60 second and will not go for server round trip. Let’s see How it will look into the browser.

Temp

You can also set the output caching in web.config and and create output cache profile which you can use any where like following.
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear/>
<add
name="MyOuputCacheProfile"
duration="60"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
Here how you can use that profile.

[OutputCache(CacheProfile = "MyOuputCacheProfile")]
public ActionResult Index()
{
ViewModel.Message = DateTime.Now.ToString();
return View();
}
It support four type of settings for output caching. VaryByContentEncoding, VaryByParam, VaryByCustom,VaryByHeader. Hope this will help you!! happy Programming.

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com

What is difference between HTTP Handler and HTTP Module.

Here are the difference between HTTP Handlers and HTTP Modules.

Http Handlers:

Http handlers are component developed by asp.net developers to work as end point to asp.net pipeline. It has to implement System.Web.IHttpHandler interface and this will act as target for asp.net requests. Handlers can be act as ISAPI dlls the only difference between ISAPI dlls and HTTP Handlers are Handlers can be called directly URL as compare to ISAPI Dlls.

Http Modules:

Http modules are objects which also participate in the asp.net request pipeline but it does job after and before HTTP Handlers complete its work. For example it will associate a session and cache with asp.net request. It implements System.Web.IHttpModule interface.

HTTP Handler implement following Methods and Properties

  1. Process Request: This method is called when processing asp.net requests. Here you can perform all the things related to processing request.
  2. IsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type.

Http Module implements following Methods and Properties.

  1. InIt: This method is used for implementing events of HTTP Modules in HTTPApplication object.
  2. Dispose: This method is used perform cleanup before Garbage Collector destroy everything.

An Http Module can Support following events exposed to HTTPApplication Object.

  1. AcquireRequestState: This event is raised when asp.net request is ready to acquire the session state in http module.
  2. AuthenticateRequest: This event is raised when asp.net runtime ready to authenticate user.
  3. AuthorizeRequest: This event is raised when asp.net request try to authorize resources with current user identity.
  4. BeginRequest: This event is raised when HTTP Modules receive new request.
  5. EndRequest: This event is raised before sending response to client.
  6. Disposed: This event is raised when http modules completes processing of request
  7. Error: This event is raised when any error occurs during processing of request.
  8. PreRequestHandlerExecute: This event is raised just before ASP.NET begins executing a handler for the HTTP request. After this event, ASP.NET will forward the request to the appropriate HTTP handler.
  9. PostRequestHandlerExecute: This event is raised when when HTTP Handler will finish the execution of current request.
  10. PreSendRequestContent: This event is raised just before ASP.NET sends the response contents to the client. This event allows us to change the contents before it gets delivered to the client. We can use this event to add the contents, which are common in all pages, to the page output. For example, a common menu, header or footer.
  11. PreSendRequestHeaders: This event is raised before asp.net Just send response header to client browser.
  12. ReleaseRequestState: This event is raised when asp.net runtime finishes handling of all the request.
  13. ResolveRequestCache: This event is raised to determine whether the request can be fulfilled by returning the contents from the Output Cache.
  14. UpdateRequestCache: This event is raised when ASP.NET has completed processing the current HTTP request and the output contents are ready to be added to the Output Cache.

Hope this will help you better understanding of HTTP Handler and HTTP Modules. I will post an real time implementation code in forthcoming blog post.

Shout it
kick it on DotNetKicks.com

GUID Vs Int data type as primary key

Recently one of my friend ask me when I should go for GUID and When I should go for Int as primary key in table. So decided to write a blog post for it. Here are advantages and disadvantage of the GUID and INT.

INT Data Type:

Advantages:

  1. Its required small space in terms of the storage it will only allocates 4 bytes to store data.
  2. Insert and update performance will be faster then the GUID. It will increase the performance of the application.
  3. Easy to index and Join will give best performance with the integer.
  4. Easy to understand and remember
  5. Support of function that will give last value generated like Scope_Indentity()

Disadvantages:

  1. If you are going to merge table frequently then there may be a chance to duplicated primary key.
  2. Limited range of uniqueness if you are going to store lots of data then it may be chance to run out of storage for INT data type.
  3. Hard to work with distributed tables.

GUID Data Type:

Advantages:

  1. It is unique for the current domains. For primary key is uniquely identifies the table.
  2. Less chances of for duplication.
  3. Suitable for inserting and updating large amount of data.
  4. Easy for merging data across servers.

Disadvantages:

  1. Bigger storage size (16bytes) will occupy more disk size then integer.
  2. Hard to remember and lower performance with Join then integer.
  3. Don’t have function to get last uniquely generated primary key.
  4. A GUID primary Key will added to all the other indexes on tables. So it will decrease the performance.

Conclusion:

From above the advantages and disadvantages we can conclude that if you are having very large amount of data in table then go for the GUID as primary key in database. Otherwise INT will give best performance. Hope this will help you. Please post your opinion as comment.

Shout it
kick it on DotNetKicks.com