Tuesday, July 19, 2011

How to create a generic type Single Linked List using C#.NET

// type parameter T in angle brackets
public class GenericList
{
// The nested class is also generic on T.

private class Node
{
// T used in non-generic constructor.
public Node(T t)
{
next = null;
data = t;
}


private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}

// T as private member data type.
private T data;

// T as return type of property.
public T Data
{
get { return data; }
set { data = value; }
}
}


private Node head;
// constructor
public GenericList()
{
head = null;
}

// T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}



public IEnumerator GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}


static void Main(string[] args)
{


// int is the type argument
GenericList list = new GenericList();

for (int x = 0; x < 10; x++)
list.AddHead(x);

foreach (int i in list)
System.Console.Write(i + " ");


System.Console.WriteLine("\nDone");
}

The Yield Statement in C#

Yield return statement. Semantically, the yield return statement is equivalent to a return statement (which passes control flow to the calling method), followed by a 'goto' to the yield statement in the next iteration of the foreach loop. This behavior does not exist in the Common Language Runtime, but is rather implemented by a class generated by the C# compiler, which is then executed and JIT-compiled by the CLR.

Another often overlooked C# statement that was introduced in .NET 2.0 is yield. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. That is a bit hard to wrap your head around, so as always, an example will help;

public static IEnumerable<int> Range( int min, int max )
{
   for ( int i = min; i < max; i++ )
   {
      yield return i;
   }
}

Each time Range is called, it will return one value in the given range. Of interest is that it maintains the state between calls. The best way to think of it is that for the first call to the method, execution starts at the first line and continues until it hits a yield statement at which time it returns the value. The subsequent runs through the method continue execution at the statement after the yield, continuing to yield values or exiting at the end of the method.
Using this, you can write the following code;

foreach ( int i in Range( 10, 20 ) )
{
   Console.Write( i.ToString() + " " );
}

Which will return the following;
10 11 12 13 14 15 16 17 18 19

Example 2:

 static void Main()
{
// Compute two with the exponent of 10.
foreach (int value in ComputePower(2, 10))
{
    Console.Write(value);
    Console.Write(" ");
}
Console.WriteLine();
    }

    public static IEnumerable<int> ComputePower(int number, int exponent)
    {
int exponentNum = 0;
int numberResult = 1;
//
// Continue loop until the exponent count is reached.
//

while (exponentNum < exponent)
{
   
//
    // Multiply the result.
    //

    numberResult *= number;
    exponentNum++;
   
//
    // Return the result with yield.
    //

    yield return numberResult;
}

}

Output:
2 4 8 16 32 64 128 256 512 1024

FYI

The yield is usually used in Enumerator.

Friday, July 15, 2011

URL Rewriting in ASP.NET 4.0

URL Rewriting - The name suggests it's all about rewriting the URL.


In the previous version of ASP.NET 4.0 you may need to create your own handler for URL rewriting but with the advent of ASP.NET 4.0 the URL Rewriting is just a little piece of code.


In ASP.NET 4.0 the URL Rewriting can be done with the help URL Routing.


FYI: For the further discussion we will be using URL Routing instead of URL Rewriting.


Advantages of URL Routing:
1. The long URL can be managed easily with the help of the compact URL Routing.
2. The actual physical URL can be hidden.
3. For security reason the actual structure of the application can be hidden.
4. The URL helps in SEO (Search engine optimization) and improve the page hits but put in the appropriate keywords.


Bi-Directional Routing
With the help of the Route table, we can not only decode the Routed URL with the Route table and with the help of other methods provided by the ASP.NET 4.0, we also generate the URL with the ASP.NET routing mechanism, which gives us the opportunity, not to hard code the URL at several places, rather it will be dynamically generating the URLs with the help of Routing Definition.



RoutingHandler

This is basically a normal HTTPHandler, which is responsible for looking into all the incoming URL requests, and looking for any Routing definition available for the URL, if yes, then pass the request and data to the corresponding resource.

Expression Builders

Expressions are provided with ASP.NET 4.0 to facilitate Bi-Directional Routing and more. Basically there are two types of ExpressionBuilders.
  1. RouteURLExpressionBuilder: As the name suggests, it provides the syntax which results in the value, i.e., URL based on RouteName and Parameter according to the Route definitions we have.
  2. RouteValueExpressionBuilder: As above, it generates the URL, RouteValueExpressionBuilderprovides a syntax which receives the value from the RouteName and Parameter from RoutedURL.
There are also a few new properties HttpRequest.RequestContext and Page.RouteData which facilitate the availability of the parameters to all resources.

Coding:

Step 1
Global.asax

  #region protected void Application_Start(object sender, EventArgs e)
        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);

          
        }
        #endregion


        #region private void RegisterRoutes(RouteCollection routes)
        private void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("Default", "Default","~/Default.aspx");
            routes.MapPageRoute("LearnMore", "LearnMore", "~/LearnMore2.aspx");           
            routes.MapPageRoute("Community", "Community", "~/community.aspx");
            routes.MapPageRoute("Contact", "Contact", "~/Contact.aspx");
            routes.MapPageRoute("Privacy", "Privacy", "~/Privacy.aspx");
            routes.MapPageRoute("Terms", "Terms", "~/Terms.aspx");
            routes.MapPageRoute("ForgotPassword", "ForgotPassword", "~/ForgotPassword.aspx");
            routes.MapPageRoute("Login", "Login/{er}", "~/Login.aspx");
           

            routes.MapPageRoute("Dashboard", "DashboardLogin", "~/Dashboard/Dashboard.aspx");

            routes.MapPageRoute("Signup-Order", "Subscriptions/Signup-Order", "~/Subscriptions/Signup-Order.aspx");           
            routes.MapPageRoute("SignUp", "Subscriptions/Signup", "~/Subscriptions/SignUp.aspx");
            routes.MapPageRoute("ThankYou", "Subscriptions/ThankYou/{na}/{ac}", "~/Subscriptions/Thankyou.aspx");
           
           routes.Ignore("{resource}.axd/{*pathInfo}");
        
        }
        #endregion

Step 2:
#region protected void Application_BeginRequest(object sender, EventArgs e)
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string requestUrl = Request.Url.ToString();
            if (requestUrl.ToLower().EndsWith("default.aspx"))
                Context.Response.RedirectToRoute("Default");
         
        }
        #endregion

Step 3:

In the presentation layer add the following
<asp:HyperLink ID="lnkForgotPassword" runat="server" NavigateUrl="~/ForgotPassword">Forgot your password?</asp:HyperLink>

passing parameter
<asp:HyperLink ID="lnkForgotPassword" runat="server" NavigateUrl="~/Login/s">Forgot your password?</asp:HyperLink>


FYI
1. The htm files will not be supported by URL Routing so try to use html files instead of that.

2. The css and script files will not be refferred properly so try to use <%=Page.ResolveUrl("~/Styles/Skin.css")%> instead in <link href="<%=Page.ResolveUrl("~/Styles/Skin.css")%>" rel="stylesheet" type="text/css" />

3. file In the local development IIS the Application_Start will not get fired so you have to initiate that process so how to do that -> 1. right click Global.asax -> Select View Mark up -> Apply Ctrl + S -> Refresh the page the Application_Start will get automatically get called -> Well you can go ahead debug that code as well.


Thursday, July 7, 2011

Calling a Javascript Function in asp.net

 Dim url As String = "Digital-signature.aspx?pono={0}&tskId=1"
            url = String.Format(url, e.CommandArgument)

            Dim script As String = "<script language='JavaScript' type='text/javascript'>open_win('{0}');</script>"
            script = String.Format(script, url)

            If Not ClientScript.IsClientScriptBlockRegistered("popup") Then
                ClientScript.RegisterClientScriptBlock(Page.GetType(), "popup", script)
            End If


window.js
-----------
function open_win(url_add)
   {
   window.open(url_add,'welcome',
   'width=300,height=200,menubar=yes,status=yes,
   location=yes,toolbar=yes,scrollbars=yes');
   }