Wednesday, April 16, 2014

Url Rewriting using Global.asax file and System.Web.Routing

URL rewriting is the process of accepting the web request and redirect it to some resource.Most often url rewriting is used for making our urls SEO Friendly.
We can rewrite our Urls either by using

1) Http Context  in Application_BeginRequest in Global.asax file .
2) Use System.Web.Routing to register routes in routes collection and then redirect based on those routes.

Using Http Context:-

We can rewrite url using http context.Whenever a request is made to the server,application begin request is fired and in that we can get the path requested and redirect to that path.

protected void Application_BeginRequest(object sender,EventArgs e)
  {
HttpContext context = HttpContext.Current;
                string path = context.Request.Path.ToLower();
                if(path.Equals("/AP"))
                {
                    context.RewritePath("~/AndhraPradesh.aspx");
                }
  }

Using System.Web.Routing:-

To register and routes in routes collection the first most important step is to import System.Web.Routing in Global.asax file.

<%@ Import Namespace="System.Web.Routing" %>

Then we have to declare a method a method to register routes and call that method on
Application_Start


void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
        
    }
public static void RegisterRoutes(RouteCollection routes)
    {

        routes.MapPageRoute("", "", "~/Default.aspx");
        
        routes.MapPageRoute("", "seo/", "~/seo.aspx");
     }

The  various parameters in MapPageRoute are
routeName
Type: System.String
The name of the route.
routeUrl
Type: System.String
The URL pattern for the route.
physicalFile
Type: System.String
The physical URL for the route.
checkPhysicalUrlAccess
Type: System.Boolean
A value that indicates whether ASP.NET should validate that the user has authority to access the physical URL (the route URL is always checked). This parameter sets the PageRouteHandler.CheckPhysicalUrlAccess property.
defaults
Type: System.Web.Routing.RouteValueDictionary
Default values for the route parameters.

Note:-
1)We can ignore certain files from url rewrite by just passing them in Ignore method

routes.Ignore("{*alljs}", new { alljs = @".*\.js(/.*)?" });
        routes.Ignore("{*allpng}", new { allpng = @".*\.png(/.*)?" });
        routes.Ignore("{*allcss}", new { allcss = @".*\.css(/.*)?" });

The above code will ignore all js,css,png files from url rewrite.
2)We can also pass parameters as query string to a page when we do url rewrite
Suppose our page url looks like
product.aspx?id=C102

then we can rewrite it as
/product/C102

To achieve such type of Url rewrite we have to add route like this
 
routes.MapPageRoute("", "product/{Id}", "~/product.aspx");
        

In the product.aspx page we have to add reference to the System.Web>Routing Namespace and we can collect that id using RouteData.Values Method of Page class
if (Page.RouteData.Values["Id"] != null)
            {
                string id = Page.RouteData.Values["Id"].ToString();
}

Thursday, April 10, 2014

How to use connection string from config file in LINQ To SQL

Most of the time when we are working with Linq To SQL We come across a situation when our application takes the connection string of the database which we used while dragging tables or procedures on dbml designers.But this is not the right way to do.So what we can do in such situation??
Possible answer may be change the connection string in dbml.designer.cs.
But there is another work around and possibly the better approach.We should not modify our dbml designer.cs file manually(the reason is that it will be rewritten when we edit/add a table.Now what is to be done next--

1) Right click on the empty space in designer and view the properties and Set the connection property of your .dbml file to “none”



 2)Now add a separate partial class with same name as in dbml file(in the above example it will be "DataClassesDataContext" with a default parameter less constructor.

public partial class DataClassesDataContext
{
  public DataClassesDataContext() : base(ConfigurationManager.ConnectionStrings["ConnectionString Name"].ConnectionString)
  {
    OnCreated();
  }
}

3) Set the connection string in web.config file

<connectionStrings>
  <add name="democonnection"
  connectionString="Data Source=Rajeev-PC;Initial Catalog=testdb;Persist Security Info=True;Integrated Security="true"
  providerName="System.Data.SqlClient" />

</connectionStrings>

Note:The down side to this approach is that you have to set the Connection property to none every time  you add new objects to the dbml file, but it's not as bad as having to manage the connection string in multiple places.