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:
Thursday, December 30, 2010

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
Share:
Wednesday, December 29, 2010

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

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("[email protected]")
,new MailAddress("[email protected]"));
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("[email protected]", "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
Share:
Wednesday, December 22, 2010

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!!


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