Friday, December 31, 2010

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
Share:

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
Share:

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("[email protected]")
                                     , new MailAddress("[email protected]"));
          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("[email protected]", "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..


Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews