ASP.NET Custom role provider

Easy guide to write your custom role provider

Merge splitted .mkv files

Learn how to merge splitted .mkv files (.mkv001,.mkv002...)

How to Zoom in and Zoom out your sql execution plan ?

Tool to tune your sql query

send .exe files with gmail

How to send files having blocked extension with Gmail ?

Multiple home pages in Internet explorer

How to set multiple home pages in internet explorer ?

2/12/2011

Query String Encryption using HTTP Module : ASP.NET Security

Most of times we tend to pass information between different web pages in the application with the help of query string. However query string offers direct visibility to the end user about the parameters your page might be expecting. If some one modifies your query string and pass the information to the page , it could become a potential security threat.

/technade.aspx/ID=123&Query=select

There are lot of ways you can normally encrypt your query string. But most of them don't help you in encrypting your query parameter. They only encrypt your values. However if someone tries with different algorithms, it could again lead to a security breach unless you did some very good exception handling.

/technade.aspx/ID=s1kokkkh1kjn&Query=kjoiujooijoi

If you encrypt your query string, everytime you want to access in your values, you have to decode it and access it. If you had already written some code, there is a great impact that you will have to adapt your code after the implementation. What if there is a way where you display in encrypted format to the user but for the code its still the same ?

What I mean is :

The user sees this

?Technade=VXzal017xHwKKPolDWQ

while your code sees

ID=123&Query=select and accesses it through Request.querystring["ID"]....

How to encrypt your query string in ASP.NET with the help of HTTP Module ?

Before we dive in, let me explain you what this HTTP module is !!

HTTP modules are one among the series of extensible objects that could be initiated by ASP.NET runtime to process a request. They are filters that can pre and post-process requests as they pass through the HTTP pipeline Many of the services provided in ASP.NET are exposed as HTTP modules esp the ones related to security.

So How do we use HTTP module for encrypting and decrypting query strings ?

Download the source code for the file here.

The source file in the above link contains the code for encryption and decryption of the query string.

How to use it ?

  • Include the file in your project and change the namespace accordingly.
  • Once you included the file in your project, please add the following tag to your Web.config in your section.

    <httpModules>
    <add name="EncryptDecryptModule" type=" Technade.Web.Core.Application.EncryptDecrypt"/> httpModules>
  • Make sure that you included correct type in the above line.
Thats it.. You are done . Now all the query string in your application will be automatically encrypted. Sometimes you may want to enable/disable query string encryption manually. The source code in the file does have the provision of enabling and disabiling query string encryption.

You will find the following line in the source code.

// 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);

Remove the line and the query strings will not be automatically encrypted. Instead you will have to call everytime manually as below whenever you want .

string querystring = EncryptDecrypt.Encrypt( "ID=123&query=select" );

But the decryption is automatic as it always checks for the encryption key that is appended before the query string in the code. So if the encryption key exists ,it will decrypt or else it will let it remain as it is. The file has been documented to a good extent. So it should not be too difficult for you to understand how it works.

Love ASP.NET tips ? For more Subscribe here or click here to get updates via email

1/30/2011

Session handling using facade design pattern : ASP.NET web development

I work with a team of x developers and I always see problems with the usage of session variables in the application. It introduces bugs in the application which can not be traced by Unit testing and may be not with any kind of testing that happens before deployment :). They surface only when application is deployed in production and its very difficult to trace such bugs which turns out to be a expensive. So how to best deal with session management ?

Let me give a small idea of how this session work. To store information that is specific to a user session , ASP.NET provides the HttpSessionState class to store session-state values. An instance of the HttpSessionState class for each HTTP request is accessible throughout your application using the static HttpContext.Current.Session property. Access to the same instance is made simpler on every Page and UserControl using the Session property of the Page or UserControl.

The HttpSessionState class provides a collection of key/value pairs, where the keys are of type String and the values are of type Object. This means that Session is extremely flexible and you can store just about any type of data in Session. You can store any Type in session variable and cast it back where ever required. This also brings a new problem of people not doing Type checks. They use the session key repeatedly instead of reusing and also store everything in sessions. When I want to see all the sessions used in my code in one place, I could never find them. To deal with all these things, we use a pattern called Facade pattern.

What is Facade design pattern ?

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

* make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
* make code that uses the library more readable, for the same reason;
* reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
* wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).


With this pattern, we can build simplified interfaces that points to different areas of complex code structure.

So How to we use this facade to do organized session management in our application ?

We make developers to only access the HttpSessionState from within one single static class in your application - the facade. There must be no direct access to the Session property from within code on pages or controls, and no direct access to HttpContext.Current.Session other than from within the facade.

All session variables should be exposed as properties of the facade class which gives us extra control over the different session variables used with in the application.

It also ensures the following :

  • Strong typing of what gets put into session variables.
  • No need for casting in code where session variables are used.
  • All the benefits of property setters to validate what gets put into session variables (more than just type).
  • All the benefits of property getters when accessing session variables. For example, initialising a variable the first time it is accessed.

An Example of Facade Class :

public static class SessionVars

{

///


///
///

///
///
///

internal bool SetHttpSessionObject(string key, object value)
{
bool writtenAck = false;
if (IsSessionValid)
{
HttpContext.Current.Session[key] = value;
writtenAck = true;
}

return writtenAck;

}

///


///
///

///
///

internal object GetHttpSessionObject(string key)
{
return IsSessionValid
? HttpContext.Current.Session[key]
: null;
}

///


///
///

public bool IsApprover
{
get
{
bool IsApprove = false;
object IsApproverVal = GetHttpSessionObject("IsApprover");
if (IsApproverVal != null)
{
IsApprove = bool.Parse(IsApproverVal.ToString());
}

return IsApprove;
}
set
{
SetHttpSessionObject("IsApprover", value);
}
}
///


///
///

public string UserID
{
get
{
string UserIDval = "";
object UserVal = GetHttpSessionObject("UserID");
if (UserVal != null)
{
UserIDval = UserVal.ToString();
}
return UserIDval;
}
set
{
SetHttpSessionObject("appUserID", value);
}
}

}

The above class demonstrates how we can define session variables in facade and make use of

HttpContext.Current.Session

Now let me explain how to make use of these properties in your Code which is quite simple.

string VirUser = SessionVars.UserID

This gives you the advantage of not casting the object everytime you use it. Also it does help you in isolating the internal implementation from the rest of your code.

Next time you choose to implement session in different way, All you have to do is change it here but not everywhere. Cool Ain't it ?

The technique seems quite simple but believe me , it has lot of added advantages for you.

The implementation of Session can be again separated from this class through the usage of partial class and could be made really isolated.I will talk about Singleton and Partial class integration in my next article. Stay tuned :)..

Love ASP.NET tips ? For more Subscribe here or click here to get updates via email

1/22/2011

How to find post back element id in asynchronous postback ( UpdatePanel ) ? ASP.NET

A day before I was playing with some functionality where I had to get the id of the element which caused the postback. If its a normal postback done with some control. We can retrieve the postback element with the code below.

string controlID = Page.Request.Params["__EVENTTARGET"];

If we use a UpdatePanel on the page, and if its a asynchronous postback with some control inside the Content template of Update panel, you will observe that EVENTTARGET parameter will be blank. So How to get the postback element id in asynchronous postback caused by Updatepanel in ASP.NET ?

Please use the function below to get the Async postback element id.

///
/// This function retrieves the ID of the control that caused the asynchronous postback.
///

///
public string GetAsyncPostBackControlID()
{
string smUniqueId = ScriptManager.GetCurrent(Page).UniqueID;
string smFieldValue = Request.Form[smUniqueId];

if (!String.IsNullOrEmpty(smFieldValue) && smFieldValue.Contains('|'))
{
return smFieldValue.Split('|')[1];
}

return String.Empty;
}


Hope it helps.

Love ASP.NET tips ? For more Subscribe here or click here to get updates via email

1/02/2011

Y.S.Jagan - Are you crazy ?

Y.S.Jagan Mohan Reddy - Son of former Chief Minister late Dr Y.S.Raja Sekhara Reddy , has made all his efforts to become the Chief Minister of the state (Andhra Pradesh) but he gained nothing...What went Wrong with Jagan ? Why could'nt he become a good leader or atleast a good politician ?

Jagan's political journey is quite short with most of it being governed by his father late YSR . Jagan started his political career in 2004 ( where he campaigned for congress in the elections ) and got himself projected as a leader for the youth wing of congress (We know how weak the wing is :)). He was elected as a Member of Parliament from Kadapa Constituency in 2009 (Where his family has a good foothold) and started his life as a active politician.

Other than this Jagan had no significant achievements being a politician. Jagan built up a business empire with the help of the power his father and he had in a very short span of time. Jagan started Sakshi Group, held a good amount of share in Bharati Cements, Sandoor Power, Jagathi Publications, Brahmani steels and other industries..... With the help of his fathers power, Jagan could get the Market capitalization of these companies increase in such a way that no other Corporate house could do in the last century... From what we hear from sources , Jagan is worth 1,00,000 crore approximately (20 Billion USD ??)... With the help of power, Y.S Raja Sekhara Reddy and his family acquired massive wealth in a short span of 5 years (Unbelievable but true..)..

After his fathers demise, Jagan didn't want to loose the power as managing his businesses and wealth will become difficult for him. Rather than feeling sorry about his fathers death, Jagan started crawling for the post of Chief Minister right from the day of his fathers death. He got signatures of the MLA's of the party so that he can show that he has strength to become the chief Minister..

This was Jagan's first mistake in the eyes of Higher Party authorities. From then on, Jagan tried all the ways in projecting himself as eligible candidate for the post of Chief Minister. He showed his interest in going to any extent to become a chief Minister. Being the son of a politician , Jagan should had understood that its not only the acceptance of MLA's but the acceptance of people that matters the most. Jagan should had got himself publicized as a leader of the masses just like his father with the help of media houses rather than appearing as a person crawling for power. Jagan should had taken a stand to wait until he gets the right projection as Peoples leader.

Jagan's aggressive ways to become CM has gained some negative image among the other communities. Jagan started with pleading the High Command but ended up in forcing them to make him the Chief Minister. To Silence Jagan, When Rosaiah was made CM, Jagan and his supporters did everything to not let Rosaiah continue in office. They portrayed him as a incapable person although he did a very good job in getting back states treasure into a acceptable position. Y.S.Raja Sekhara Reddy's schemes caused unacceptable damage to states treasury (Thats a complete different story :) ).

Jagan also planned a series of public events across the state under the Name " Odarpu Yatra"
where he wanted to meet people (who had been reportedly said to have committed suicide in response to his fathers death). The real motive was to get himself projected as a successor of his father. He wanted to do it with no publicity to Congress. When the higher party authorities asked him for the same, he started publicizing that the higher command is stopping him from doing this Odarpu Yatra. In last time elections, YSR got some of his relatives and close acquaintances elected as MLA's. Most of them were being supported by YSR family & Co. financially at the time of election. Jagan made some of them attend his "Odarpu Yatra" to show of his strength and to black mail the high command. Jagan tried to meet Sonia Gandhi again but she made it very clear that he stand nowhere now to become the Chief Minister.

With the inclination of higher command towards some other person even after Rosaiah's resignation, Jagan's aggression turned into craziness to become the chief Minister. Finally Jagan had to resign along with his mother and come out of congress as he could not climb the hill any more..

After his resignation, Jagan started to project himself as a Saviour of government today by saying that he is not going to ask his followers to resign.. but it appears more of blackmailing rather than saving the government. He asks his followers to stay with the government but he makes a announcement that he will roll out a party in 2 months.After that Jagan undertook a Fast for farmers and made 20 + MLA 's (his community leaders and relatives) attend it .

Jagan is trying every option so that he can get what he want. But he never got the fact that beyond all this its the people that matters. May be there are some loyalists of his father who might vote on his name but its not going to be everyone again. YSR with his good strategy and management got into peoples nerve and could win the last election. But who will vote for Jagan (May be some loyalists of his community ) ? What will people see in him to vote for ? A person crawling for power ? A corrupted politician riding on huge wealth ? A bad strategist who could not devise a single idea correctly ? A aggressive crazy person trying to get something he don't deserve ?

But Jagan should know this. Once he is out of Congress, the government will focus on his strengths so they can rip them of. They started to look for the answers to questions such as

1. How he accumulated so much wealth ? How to get it stripped of him ?
2. Who are his loyalists and How can they keep them away from him ?
3. How to retain other leaders from his community ?
4. How can Congress retain its name and get YSR & family co. not being projected as its captain anymore ?

The government needs some of Jagans loyalists today to run. But if elections happen next time , very few of these Jagan's loyalists will win again.

But Jagan might have a alternate plan to look towards BJP with the help of Bellary Reddy Brothers if Congress don't win majority of seats in elections. If Jagan gets even 5 MP seats with the help of his loyalists, he could play a key role at the centre. Thats why he made a announcement today that he will contest as a MP again.

Whatever he might think, but people should think before they vote for someone like him next time. There is a limit for everything and Jagan has crossed it. He don't deserve to be a leader with the kind of attitude he has. He is not going to serve the state. Say No to Corruption People. He is Crazyyyyyyyy..