Wednesday, February 18, 2009

Passing security credentials to C# 2.0 Web Service using SOAP Header



In a project ,we had a web service that required the client to pass security credentials (user id and password) while calling some of the web methods. First we thought to add two additional parameters (user id and password) to every web method that required authentication. This strategy looked very repetitive and made the method parameter list longer. After exploring for a while we discovered a nice solution of passing credentials through SOAP header. To implement this we need to perform the following steps:

Web Service:

1. Inherit a class from the “System.Web.Services.Protocols.SoapHeader” class that contains the security credential related fields. Put this class into the same file that contains the web service class.

public class SecurityInfo : SoapHeader
{
public string UserID;
public string Password;
}

2. Add a public field into the web service class of the type “SecurityInfo”.

public SecurityInfo SecurityCredentials = new SecurityInfo();

3. Add a “SoapHeader” attribute to the web method that requires access to security credentials passed by the client application. The parameter name of the “SoapHeader” attribute must be same as the public field declared in the above step (“SecurityCredentials” in this case).


[WebMethod(Description = "A method that requires authentication")]
[SoapHeader("SecurityCredentials")]
public void PerformASensitiveTask()
{
//Call the authentication method here with the security credential.

Authenticate(SecurityCredentials);

}

[WebMethod(Description = "Another method that requires
authentication")]
[SoapHeader("SecurityCredentials")]
public void PerformAnotherSensitiveTask()
{
//Call the authentication method here with the security credential.
Authenticate(SecurityCredentials);

}


private void Authenticate(SecurityInfo credentials)
{
// validation logic goes here. An exception is thrown if not validated.
string userId = credentials.UserID;
string password = credentials.Password;
//.....
}


So the final web service code looks like this:


public class TestService : System.Web.Services.WebService
{
public SecurityInfo SecurityCredentials = new SecurityInfo();
public TestService()
{
}

[WebMethod(Description = "A method that requires authentication")]
[SoapHeader("SecurityCredentials")]
public void PerformASensitiveTask()
{
//Call the authentication method here with the security credential.
Authenticate(SecurityCredentials);
}

[WebMethod(Description = "Another method that requires authentication")]
[SoapHeader("SecurityCredentials")]
public void PerformAnotherSensitiveTask()
{
//Call the authentication method here with the security credential.
Authenticate(SecurityCredentials);
}

private void Authenticate(SecurityInfo credentials)
{
// validation logic goes here. An exception is thrown if not validated.
string userId = credentials.UserID;
string password = credentials.Password;
//.....
}

}

public class SecurityInfo : SoapHeader
{
public string UserID;
public string Password;
}


Web Service Consumer (Console App):

After adding a web reference to the web service, Visual Studio automatically adds a “SecurityInfoValue” property to the consumer-side proxy. The security credential class “SecurityInfo” is also exposed to the client application.We just need to instantiate an object of this class,set the credentials and set it into the “SecurityInfoValue” property of the client side proxy class of the web service.We can call multiple web methods after that with the same instance in the current scope.All the web methods will have access to the security credentials.The client code looks like this:



static void Main(string[] args)
{
TestWebService.TestService srvc = new
ServiceTest.TestWebService.TestService();

TestWebService.SecurityInfo sec = new
TestWebService.SecurityInfo();

sec.UserID = "ID";
sec.Password = "Password";
srvc.SecurityInfoValue = sec;

srvc.PerformASensitiveTask();

srvc.PerformAnotherSensitiveTask();

}


I think using “Soap Header” to pass credentials to multiple web methods of a web service is really an elegant solution.

Friday, February 6, 2009

When to apply OOAD concepts and Design Patterns?



I strongly believe that the concepts like OOAD (Object Oriented Analysis and Design) and Design Patterns contribute to make an application well designed and flexible in a very positive way. But over the years I have seen myself and some of my colleagues struggling to decide where to start first in the software design phase when a new project arrives.

Should we list all the memorized design patterns first and search in the requirement list for the scope to apply those?

Should we think of the basic OO concepts like encapsulation, polymorphism or inheritance (“is-a” or “has-a”) and start designing the classes according to those at the first place ?

Often many developers loose the way on their inability to prioritize these processes and thinks too much of theoretical Analysis and Design without concentrating on solving the problem on hand first. I have also faced this problem which is popularly termed as “Analysis Paralysis” in the Software Analysis and Design Books.

I have found an excellent guideline of prioritizing these processes in the book “Head First Object Oriented Analysis and Design” by O’Reilly publication. The guideline suggests that:

1. We should concentrate on solving the problem on hand first with the best possible algorithm and make sure that the software does exactly what the customer expects from it. In a nutshell, if the customer does not recognize the validity of the software, all hard work on Analysis, design, patterns, best practices, latest and greatest technologies gone in vain my friend.

2. After making the software workable, we should apply basic OO principles to make the software flexible by eliminating the duplicate codes and improving a bad design.

3. Finally we should strive for applying proven design patterns so that the software is easy to extend and reuse.


I just wanted to share these principles and priorities with you and believe that remembering the priorities will be helpful to choose the right path while designing and developing software.

Thursday, January 8, 2009

Tracking the completion of a file upload or copy using .NET FileSystemWatcher component



I had an assignment to process the files uploaded by users into a FTP location.Files used be removed removed after the processing was complete.I had developed a .NET Windows Service in the FTP server machine to watch the FTP directory for the uploaded files.The service used to track the files as soon uploaded and start processing.I had used the .NET "FileSystemWatcher" component to monitor the directory.The problem was that,as soon the file was created in the directory(the upload by user had just started), the service used to start processing it.Normally it takes a while for the completion of file upload specially if the size is larger.So the service was processing incomplete files before the upload is complete.After exploring the property,methods and events of the extremely useful "FileSystemWatcher" component, i found the solution to track when the file is completely uploaded.

To mark the upload completion, a temporary file with a ".flag" extension used to be created that matches exactly the name of the uploaded file.For example if the file name is "Data.zip", the name of the temporary file would be "Data.zip.flag".Any valid and unused extension other than ".flag" could have been used here.The service code is now changed to look for the files with ".flag" extension to understand that the file is fully uploaded or copied.It then extracts the file name from the ".flag" file name and starts the normal processing.

Here is the code:

static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\Temp";
watcher.Filter = "*.zip";
watcher.NotifyFilter = (NotifyFilters.LastWrite);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
Console.ReadLine();
}

static void watcher_Changed(object sender, FileSystemEventArgs e)
{
FileInfo fi = new FileInfo(e.FullPath);

if (fi.Length > 0 && !File.Exists(e.FullPath + ".flag"))
{

File.Create(e.FullPath + ".flag");

}

}

The "path" property of "FileSystemWatcher" component is used to mention the directory to watch for and the "filter" property is used to mention file name or file types.But the crucial property for this particular task is the "NotifyFilter" property that is set to "NotifyFilters.LastWrite" here. This will enable the component to notify when the final byte of the file is written to disk.

The "changed" event of the component is handled to get notified when the file upload is complete.Here we have checked the file size to be sure that it is not zero and also checking whether the temporary file exists.If the file has a size(greater than zero) and temporary file does not exist, we are creating the temporary file.The same event is fired multiple times by .NET Framework.So the checking is being done to create the temporary file only once.

Wednesday, January 7, 2009

Retrieve the name of the currently executing method inside the same method.



In one of my projects, the requirement was to log the error information inside a method if an exception occurs. I needed to record the current method name along with the error message. The code was like this:
public void DoSomething()
{
try
{
//The method code goes here.
}
catch (Exception ex)
{
WriteLog("DoSomething", ex.ToString());
//The first parameter of WriteLog method is the name of the current method.
}
}

I was not happy with the way I had to hard code the name of the current method(“DoSomething” here). This way I had to hard code the names of every method where I needed to log the error information.This required to change every method name in the lines of log writing if i had to change the method name.So I was looking for a built in feature that will provide me the current method name.I searched for a while and found a handy solution in the “System.Diagnostics” namespace of the .NET Framework.Here is the code to automatically get the name of the current method.

public void DoSomething()
{
try
{
//The method code goes here.
}
catch (Exception ex)
{
string currentMethodName = new
System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name;

//The "GetMethod" method returns a "MethodBase" object.With
//this we can access the name of the method and
//other valuable information like access
//modifier,parameters,return types e.tc.//

WriteLog(currentMethodName, ex.ToString());
}
}
I found the API provided by the “System.Diagnostics” namespace really interesting and useful.

Saturday, December 20, 2008

Using the ASP .NET "_doPostBack()" method reference in Javascript



I was assigned to do a task that will need to invoke a javascript method that will perform some client side control state changes and finally submit the page with the "_doPostBack" javascript function. This "_doPostBack" function template is auto generated by the ASP .NET framework and is called when a post back to the server is required as a result of the interaction between the user with the ASP .NET Server Controls(Ex:button click, drop down list selection changes) .

I had first gone for the easy solution and hard coded the function call like this:

<script>
function DoSomeTask()
{
//Do some client side tasks here.
__doPostBack('<control>','');//posts the page back
}
</script>

I then thought should i rely on the hard coded "__doPostBack" method call? What if This function is not generated by ASP .NET under certain conditions? What if the name of the function differs in different browsers? What if Microsoft replaces the function name in the next version of ASP .NET (this application was developed with 1.1) ?

So i searched on the net and found a nice solution. At the server side ,the "GetPostBackClientHyperlink" method of the "Page" object returns the correct script block that does the post back for the ASP .NET server controls. The syntax is:

Page.GetPostBackClientHyperlink(<control>,<argument>);

So i changed the previous javascript block as:

<script>
function DoSomeTask()
{
//Do some client side tasks here.
<%= GetDoPostBackMethodSignature() %>

}
</script>

Where the "GetDoPostBackMethodSignature()" method is declared at the code behind page as:

protected string GetDoPostBackMethodSignature()
{
return Page.GetPostBackClientHyperlink(<Server Control Instance >,string.Empty);

}

Now there is no confustion whether the generated function is named "__doPostBack" or "_sueBillGates".

I trust ASP .NET fully(have no other alternative at the moment though:) ) and sure that my client side codes will not complain about not finding the "_doPostBack" function.

Cheers!