how to encrypt query string parameters in asp.net ?


Hi

Here are some few steps do encryption of “query string” in asp.net

Step1. Create one class file in app_Code .

Step2: Keep this Code in that class

using System;
using System.Collections.Generic;
using System.IO;

using System.Security.Cryptography;
using System.Text;
using System.Web;

/// <summary>
/// Summary description for QueryStringModule
/// </summary>
public class QueryStringModule : IHttpModule
{
//  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));
#region IHttpModule Members

public void Dispose()
{
// Nothing to dispose
}

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}

#endregion

private const string PARAMETER_NAME = “enc=”;
private const string ENCRYPTION_KEY = “key”;

void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string query = string.Empty;
string path = string.Empty;

try
{
if (context.Request.Url.OriginalString.Contains(“aspx”) && context.Request.RawUrl.Contains(“?”))
{
query = ExtractQuery(context.Request.RawUrl);
path = GetVirtualPath();

if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
{
// Decrypts the query string and rewrites the path.
string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
context.RewritePath(path, string.Empty, decryptedQuery);
}
else if (context.Request.HttpMethod == “GET”)
{
// Encrypt the query string and redirects to the encrypted URL.
// Remove if you don’t want all query strings to be encrypted automatically.
string encryptedQuery = Encrypt(query);
context.Response.Redirect(path + encryptedQuery, false);
}
}
}
catch (Exception ex)
{
// m_Logger.Error(“An error occurred while parsing the query string in the URL: ” + path, ex);
context.Response.Redirect(“~/Home.aspx”);
}

}

/// <summary>
/// Parses the current URL and extracts the virtual path without query string.
/// </summary>
/// <returns>The virtual path of the current URL.</returns>
private static string GetVirtualPath()
{
string path = HttpContext.Current.Request.RawUrl;
path = path.Substring(0, path.IndexOf(“?”));
path = path.Substring(path.LastIndexOf(“/”) + 1);
return path;
}

/// <summary>
/// Parses a URL and returns the query string.
/// </summary>
/// <param name=”url”>The URL to parse.</param>
/// <returns>The query string without the question mark.</returns>
private static string ExtractQuery(string url)
{
int index = url.IndexOf(“?”) + 1;
return url.Substring(index);
}

#region Encryption/decryption

/// <summary>
/// The salt value used to strengthen the encryption.
/// </summary>
private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

/// <summary>
/// Encrypts any string using the Rijndael algorithm.
/// </summary>
/// <param name=”inputText”>The string to encrypt.</param>
/// <returns>A Base64 encrypted string.</returns>
private static string Encrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return “?” + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}

/// <summary>
/// Decrypts a previously encrypted string.
/// </summary>
/// <param name=”inputText”>The encrypted string to decrypt.</param>
/// <returns>A decrypted string.</returns>
private static string Decrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();

byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}

#endregion

}

Steps 3:

Add in web config like this

<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.0″ />
<httpModules>
<add type=”QueryStringModule ” name=”QueryStringModule “/>
</httpModules>
</system.web>

</configuration>

 

Now, while passing the parameter, you will get value in encrypted form.

Like this Image

Here is no need to call that class. It is one of the easiest method to encrypt the query string.

I hope this will help to some one.

How to Display Sum Total in the Footer of the GridView Control ?


Hi

Here are some few step to perform this task

Step1: Take one gridview and Sqldatasource control in default.aspx page

step2:  Configure the SqldataSource control and gridview control like this

<div>
<asp:GridView ID=”GridView1″  DataKeyNames=”Id” ShowFooter=”true”
runat=”server” AutoGenerateColumns=”False”
DataSourceID=”SqlDataSource1″ onrowdatabound=”GridView1_RowDataBound” >
<Columns>
<asp:BoundField DataField=”Id” HeaderText=”Id” InsertVisible=”False”
ReadOnly=”True” SortExpression=”Id” />
<asp:BoundField DataField=”EmpName” HeaderText=”EmpName”
SortExpression=”EmpName” />
<asp:BoundField DataField=”EmpSal” HeaderText=”EmpSal”
SortExpression=”EmpSal” />

</Columns>
</asp:GridView>

<br />
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:ConnectionString %>”
SelectCommand=”SELECT * FROM [tblEmp]”></asp:SqlDataSource>

</div>

Step3: Click on “RowDataBound” event of gridview like this

Step 4: Write the code like This

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
private decimal sum = 0;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
sum = sum + Convert.ToDecimal(e.Row.Cells[2].Text);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Text = “Total Rs”;
//e.Row.Cells[2].Text = sum.ToString(“c”, new CultureInfo(“hi-IN”));
e.Row.Cells[2].Text = sum.ToString();
e.Row.Font.Bold = true;
}

}
}

Step 5: Compile the code .You will Output like this

I hope this will help to some one.

How to fill gridview using WCF ?


Hi

This is the following steps to fill gridview using WCF

Step 1: Create one table i.e tblEmp which contain Id,EmpName,EmpSal field.

Step2. Add the “WCF Service File”.

Step3.Write the following code in Iservice.cs file

using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Data;

// NOTE: If you change the interface name “IService” here, you must also update the reference to “IService” in Web.config.
[ServiceContract]
public interface IService
{

[OperationContract]
Emp[] getAllEmpName();

}
[DataContract]
public class Emp
{
[DataMember]
public int EmpId { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public string EmpSal { get; set; }
}

Step4: Write the following Code in “Service.cs”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;

// NOTE: If you change the class name “Service” here, you must also update the reference to “Service” in Web.config.
public class Service : IService
{
public void DoWork()
{
}

#region IService Members

Emp[] IService.getAllEmpName()
{
SqlConnection con = new SqlConnection(“Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True”);
SqlCommand cmd = new SqlCommand(“Select *from tblEmp”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
int RCount=dt.Rows.Count;
Emp[] arrEmp=new Emp[RCount];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
arrEmp[i] = new Emp();
arrEmp[i].EmpId = Convert.ToInt32(dr[“Id”]);
arrEmp[i].EmpName = dr[“EmpName”].ToString();
arrEmp[i].EmpSal = dr[“EmpSal”].ToString();
i++;

}
return arrEmp;

}

#endregion
}

Step 5: Click on “Add service reference” then Click on “Discover” then

write the NameSpace Name Like this img

Step 6:Click on advance and set “asynchronous Communication” like this

Step6: Take one gridview control in default page. write the following code in code behind file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowEmpData.ServiceClient ws = new ShowEmpData.ServiceClient();
GridView1.DataSource = ws.getAllEmpName();
GridView1.DataBind();

}
}

Now compile the code. You will get output like this

WCF Sample code in asp.net 3.5


Hi

Here are some few steps to create WCF in asp.net 3.5

step1.

Create one asp.net project like this

Step2:

Add WCF file like this

Step 3:

Add the operation contract

int Add(int a, int b);

in  IService.cs file. as shown in Image

Step4

Go to Service.Cs file and click on “IService” as shown in Image

then Click on Explicitly Implement Interface.

then it will create interface add method.

Step 5: Write the code like this

int IService.Add(int a, int b)
{
return (a + b);
}

Step 6: For checking the service,click F5 you will get output like this

Step 7: Add Service Reference like this

Step 8:Click on Discover and Give the Namespace name like this

Step 9:Click on advance and Select “Generate Asyncronous Communication” like this

Step 10: Click ok.  Then Come to “Default page” and keep there 2 textbox and one Button control like this

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox>
<br />
<br />
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />
</div>
</form>
</body>
</html>

Step 11. Click on” Button 1″ on write the following code in code behind for calling WCF service.

protected void Button1_Click(object sender, EventArgs e)
{
WcfTest.ServiceClient ws = new WcfTest.ServiceClient();
int result = ws.Add(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text));
Response.Write(result);
ws.Close();
}

Step 12:

Now compile the code and pass the input in two textbox, you will get Output like this

I hope this will help to some one.

What is WCF (Window communication Foundation)?


What is WCF (Window communication Foundation)?

WCF is the .net framework Communication technologies. It is the combination of following technologies:

  • .Net Remoting
  • MSMQ(Microsoft message queuing)
  • Web services
  • COM+

Uses of  WCF

  • It is used to communicate between other applications which has been developed on other platforms and using other Technology.

For example, if  I have to transfer data from .net platform to other application which is running on  other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP)

Then it is only possible to transfer data using WCF.

Advantages:

  • Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
  • Security is very high as compare to web service

What is the difference between web service and WCF ?

1. Web service use only HTTP protocol while transferring data from one application to other application.

But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).

2. To develop a service in Web Service, we will write the following code

[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}

To develop a service in WCF, we will write the following code

[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}

3. Web Service is not architecturally more robust. But  WCF is architecturally more robust and promotes best practices.

4. Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is better in performance as compared to XmlSerializer?

5. For internal (behind firewall) service-to-service calls we use the net:tcp binding, which is much faster than SOAP.

WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25% faster than .NET Remoting.

For more detail, check this link   http://msdn.microsoft.com/en-us/library/aa738737.aspx


WCF Frameworks Architecture

WCF is the combination of 3 parts

  1. The Service
  2. One or more Endpoints
  3. Environment in which to host the service.

A service is a class that is written in one of the .NET-compliant languages. The class can contain one or more methods that are exposed through the WCF service. A service can have one or more endpoints. An Endpoint is used to communicate through the service to the client.

Endpoints themselves are also made up of three parts. These parts are usually defined by Microsoft as

the ABC of WCF.

➤ “A” is for address.

➤ “B” is for binding.

➤ “C” is for contract.

  • Address is a URL, which points to the location of the services.
  • Binding indicate how this end point can be accessed. It determines how the communication is done. It indicates regarding binding protocol in Service.
  • Contract defines the protocol, how the client should communicate with your service. It describes the parameter and return values for a method.

Creating WCF Services

You must have to perform 2 main tasks

  1. Create a service Contract
  2. Create a data Contract

The service contract is really a class with the methods that you want to expose from the WCF service.

The data contract is a class that specifies the structure you want to expose from the interface.

After you have a service class in place, you can host it almost anywhere

Hosting  options for WCF  Service

➤ Console applications

➤ Windows Forms applications

➤ Windows Presentation Foundation (WPF) applications

➤ Managed Windows Services

➤ Internet Information Services (IIS) 5.1

➤ Internet Information Services (IIS) 6.0

➤ Internet Information Services (IIS) 7.0 and the Windows Activation Service (WAS)

Binding in WCF

WCF provides nine built-in bindings:

  1. BasicHttpBinding: Basic web service communication. Exposes WCF services as legacy ASMX web services. Used for interoperability. No security by default.
  2. WSHttpBinding: Web services with WS-* support. Supports transactions and reliable messaging.
  3. WSDualHttpBinding: Web services with duplex contract and transaction support.
  4. WSFederationHttpBinding: Web services with federated security. Supports transactions.
  5. MsmqIntegrationBinding: Communication directly with MSMQ applications. Supports transactions.
  6. NetMsmqBinding: Communication between WCF applications by using queuing. Supports transactions.
  7. NetNamedPipeBinding: Communication between WCF applications on same computer. Supports duplex contracts and transactions.
  8. NetPeerTcpBinding: Communication between computers across peer-to-peer services. Supports duplex contracts.
  9. NetTcpBinding: Communication between WCF applications across computers. Supports duplex contracts and transactions.