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.

Tuesday, February 18, 2014

Enable copy & right -click in a webpage that is copy protected.

Many a times when we visit a webpage and try to copy some content from the page ,we are unable to copy that content. There are two possibilities that you are unable to copy.
1)Webpage has disabled the right click of the webpage.
2)The webpage has disabled select of the webpage.
Now here is the solution to these scripts .

For enabling right click just copy the below script and paste it in browser url of the same page

javascript:void(document.oncontextmenu=null)

For enabling copy just copy the below script and paste in browser url of same page


javascript:void(document.onselectstart=true)

Monday, February 17, 2014

WCF Web HTTP Service Help Page and Show Exception Detail when calling methods of WCF Service

WCF Help Page:

This functionality is turned off by default. When a user browses to a WCF WEB HTTP service and appends "/Help" on to the end of the a help page like the following is displayed.
The user can then click any method listed in the help page and detailed page for that operation is displayed showing more information about the method, including message formats and example responses. To enable the WCF WEB HTTP Help age in configuration, add an endpoint behavior with a <webhttp>  element, set enableHelp to true.


      <endpointBehaviors>

        <behavior name="Jsonbehavior">

          <webHttp helpEnabled="true" />

        </behavior>

      </endpointBehaviors>


Show Errors in WCF:

To show exact error in WCF Hosted on IIS we need to set service debug includeExceptionDetailInFaults attribute to true.
    <behavior name="Service1">

                    <dataContractSerializer maxItemsInObjectGraph="2147483646" />

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="true" />



        </behavior>


Friday, February 14, 2014

Working with JSON in c# using using Newtonsoft.Json

JSON stands for "Java Script Object Notation".
JSON you need a lightweight, open, text-based platform independent data exchange format for transferring data back and forth between the client and server. Although XML works well for many application scenarios but it has an extra payload that is XML tags.So to overcome this drawback ,JSON was introduced.
 In this example i will be using a library to access a WCF Rest Service using Newtonsoft.json.dll.
Here is the simple code to access a JSON array Response in c#
Just include Newtonsoft.Json and Newtonsoft.Json.Linq namespaces

Code:


 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net;

using System.Web.Script.Serialization;

using System.Net.Json;

using System.IO;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using Jsonparse;

 namespace Jsonparse

 {

 class Program

 {

 static void Main(string[] args)

 {

 WebClient c = new WebClient();

var data=c.DownloadString("http://localhost:50766/Service1.svc/json/GetDispatchOrders");

//ordtrnh is my custom class declared in Jsonparse namespace

 List

myDeserializedObjList = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(List));

 foreach(ordtrnh o in myDeserializedObjList) 

 { 

 Console.WriteLine("Customer Id is {0}",o.custid); 

 Console.WriteLine("Order Date is {0}", o.orddate);

 Console.WriteLine("Customer Area is {0}", o.parea); 

Console.WriteLine("----------------------------------------------");

 } 

 Console.ReadLine(); 

 } 

 } 

}
Output:
You can download newtonsoft.json.dll from   Here

Wednesday, February 12, 2014

The maximum message size quota for incoming messages (65536) has been exceeded.(Error in WCF Test Client)

Sometimes when we invoke a method in WCF Test Client we get an error even though same restfull service when invoked in browser works fine.In WCF Test Client we are likely to get an error

"The maximum message size quota for incoming messages (65536) has been exceeded" after using the WCF Test Client utility to invoke a method on my service." 

There is nothing wrong with the service this is just the configuration change in WCF Test Client. In the wcf test client, after you add the service, you can notice there is a "config file" node at the end of the service tree: right click it and select "edit with SvcConfigEditor". You will get the exact configuration editor for the service side - just go to the binding settings and change the MaxReceivedMessageSize and save the changes.

Just put these values

maxBufferSize=”2147483647″
maxReceivedMessageSize=”2147483647″

Authentication issues in WCF(IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous.) on remote server

While hosting your Restful WCF Service on shared hosting you are more likely to get the error

IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used.

To overcome this error we have to make a small change in our web.config file as
<system.servicemodel="">
    <bindings>
      <webhttpbinding>
        <binding>
          <security mode="None">
            <transport clientcredentialtype="Windows">
          </transport></security>
        </binding>
      </webhttpbinding>
    </bindings>
  </system>



This will disable security of your service & your service doesn't need authentication