Archive

Archive for the ‘Dot Net Tips’ Category

Using MemoryCache in .Net 4.0

November 27, 2011 2 comments

Since ASP.Net first came, it came up with a very powerful feature of in-memory object cache (System.Web.Caching.Cache) to store commonly used expensive data on server side. Almost every ASP.Net application/site uses this feature now. But it suffered from few shortcomings like-

  • It is available in ASP.Net only leaving WinForms or WPF clients puzzled.
  • It is not extensible to accommodate other demands to store cache objects in disk or Sql Server. However, MS after realizing these shortcomings, Caching Application Block library was included in its Enterprise Library.
  • .Net developers have to look for their own mechanisms to create logical in-memory partitions called regions to group or organize cache objects in memory.

However, .Net 4.0 came up with a new set of caching APIs in System.Runtime.Caching namespace that addresses all the above shortcomings. This new namespace can be found in System.Runtime.Caching.dll assembly. But this assembly reference is available only target framework of .Net Framework 4, not .Net Framework 4 Client Profile.

The System.Runtime.Caching namespace contains two core set of classes:

  • Concrete implementation of System.Runtime.Caching.MemoryCache class to support in-memory object cache. MemoryCache is closely modeled after old System.Web.Caching.Cache of ASP.Net. However, one does not have to rely upon System.Web assembly to use MemoryCache (We will see it through an example shortly).
  • Abstract types to build custom cache implementation other than in-built MemoryCache.

Now let’s move to try out an example to leverage MemoryCache features. First of all we will create a class library type project. Add a class MyCache and assembly reference of System.Runtime.caching.dll.

MyCache Code sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;

namespace DotNetCachingWrapper
{
public enum MyCachePriority
{
Default,
NotRemovable
}

public class MyCache
{
// Gets a reference to the default MemoryCache instance.
private static ObjectCache cache = MemoryCache.Default;
private CacheItemPolicy policy = null;
private CacheEntryRemovedCallback callback = null;

public void AddToMyCache(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, List<String> FilePath)
{
//
callback = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
policy = new CacheItemPolicy();
policy.Priority = (MyCacheItemPriority == MyCachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;
policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.00);
policy.RemovedCallback = callback;
policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

// Add inside cache
cache.Set(CacheKeyName, CacheItem, policy);
}

public Object GetMyCachedItem(String CacheKeyName)
{
//
return cache[CacheKeyName] as Object;
}

public void RemoveMyCachedItem(String CacheKeyName)
{
//
if (cache.Contains(CacheKeyName))
{
cache.Remove(CacheKeyName);
}
}

private void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
{
// Log these values from arguments list
String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), "
| Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ",
arguments.CacheItem.Value.ToString());
}

}
}

Build this class library to generate assembly name of MyCachingWrapper.dll. Now we are ready to use this library in all ASP.Net web, WinForms and WPF applications.

Now let’s see examples of how this library can be commonly used in both ASP.Net Web Form and WinForm after adding reference of MyCachingWrapper.dll.

ASP.Net Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
//
MyCache objCache = new MyCache();
String strUserName = objCache.GetMyCachedItem("USER_NAME") as String;
if (String.IsNullOrEmpty(strUserName))
{
List<String> lstFiles = new List<string>();
lstFiles.Add(HttpContext.Current.Request.MapPath("~/XmlFiles/ListOfUsers.xml"));

XElement x = XElement.Load(HttpContext.Current.Request.MapPath("~/XmlFiles/ListOfUsers.xml"));
var qry = from u in x.Elements("Users") where u.Element("UserCode").Value == "101" select u;
strUserName = qry.First().Element("UserName").Value;

// Add inside cache
objCache.AddToMyCache("USER_NAME", strUserName, MyCachePriority.Default, lstFiles);
}
this.lblUserName.Text = strUserName;
}

WinForm Form_Load:

private void frmDefault_Load(object sender, EventArgs e)
{
//
MyCache objCache = new MyCache();
String strFilePath =System.IO.Path.Combine(Environment.CurrentDirectory, "../../XmlFiles/ListOfUsers.xml");
String strUserName = objCache.GetMyCachedItem("USER_NAME") as String;
if (String.IsNullOrEmpty(strUserName))
{
List<String> lstFiles = new List<string>();
lstFiles.Add(strFilePath);

XElement x = XElement.Load(strFilePath);
var qry = from u in x.Elements("Users") where u.Element("UserCode").Value == "101" select u;
strUserName = qry.First().Element("UserName").Value;

// Add inside cache
objCache.AddToMyCache("USER_NAME", strUserName, MyCachePriority.Default, lstFiles);
}
this.lblUserName.Text = strUserName;
}

Sample ListOfUsers.xml File:

<?xml version="1.0"?>
<ListOfUsers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
<Users>
<UserCode>101</UserCode>
<UserName>Dan Brown</UserName>
</Users>
<Users>
<UserCode>102</UserCode>
<UserName>da Vinci</UserName>
</Users>
<Users>
<UserCode>103</UserCode>
<UserName>Monalisa</UserName>
</Users>
<Users>
<UserCode>104</UserCode>
<UserName>Shakespeare</UserName>
</Users>
<Users>
<UserCode>105</UserCode>
<UserName>William Wordsworth</UserName>
</Users>
</ListOfUsers>

Now we can debug above code and see other interesting things. You will see the usage of MemoryCache methods and its techniques to cache objects are similar to what we have been doing in ASP.Net cache so far. Also, we see how the same MyCache library is usable in both web and windows applications.

MemoryCache points worth mentioning:

  • MemoryCache.Default returns the single and same instance of in-memory ObjectCache through a static read-only property.

    public static MemoryCache Default { get; }

  • CacheEntryRemovedCallback signature is different than what we have seen in prior versions of ASP.Net. Refer to example. In the current callback method, one can see the following details when cache item is expired after 10 seconds.

CallbackArgumentsDetails

  • CacheItemPriority enum in .Net 4.0 is cleaner than what we have seen in prior versions of ASP.Net. Now, it is only Default and NotRemovable.
  • In prior version of ASP.Net, CacheDependency was used to monitor changes in any underlying objects like files, Sql database tables, rows, columns, etc. Now .Net 4.0 provides ChangeMonitor class which is ASP.Net neutral and has wider scope of monitoring dependent objects to expire cache items. However, CacheDependency is still there in ASP.Net 4.0. We should use other implementation of ChangeMonitor like HostFileChangeMontor in the above example.
  • The default implementation of MemoryCache does not give us flexibility to add regions along with keys. In order to use regions, you should extend MemoryCache.

Hope you all will appreciate .Net 4.0 caching feature.

Testing and Monitoring WCF Service using soapUI and Fiddler

September 3, 2011 Leave a comment

This article is not about understanding the details of .Net WCF service, soapUI and Fiddler as all these three are quite popular things among .Net developers. And tools like soapUI and Fiddler may already be in the arsenal of many web developers and QA engineers. Those who are new to these two tools should refer to following articles.

However, we will take a look into how Fiddler can be used to Monitor SOAP Request and SOAP Response transmitting behind the soapUI.

Let’s start with a simple WCF service in place. No need to have a WCF .Net Client as of now to test and monitor HTTP traffic of WCF service calls.

1. Open soapUI and set the following settings. Make sure the service’s wsdl path is correct.

Loading wsdl definition

2. After loading the definition of WSDL, service definitions will appear like shown below.

Service requests definitions

3. Double click on Request # node and navigate to the request window on the right.

Submitting the request

4. Fill the method parameters denoted by “?”.

5. Open Fiddler and make sure it is ready to capture HTTP(S) traffic.

6. Submit request to the specified endpoint and SOAP Response can be seen on the right pane.

Service Request-Response in soapUI

7. If you see the Fiddler window, there is no traffic captured. This is really frustrating if you have been testing your services using soapUI when you do not see the underlying details of the SOAP Request and SOAP Response in the wire.

8. All you need to do following proxy settings in the soapUI File –> Preferences –> Proxy Settings window.

soapUI Proxy Settings

9. Re-submit web service request on soapUI.

10. Now you see WCF Request-Response traffic in the Fiddler window Smile. You are now all in your territory to view the details of service request-response headers, body, and many more!

SOAP Request-Response view in Fiddler

But why did we add Port No. 8888 in the proxy settings of soapUI? It is because Fiddler by default listens on port no. 8888.

Fiddler default listening port no.

If you have configured your Fiddler proxy tool to listen on some other port no., then you should use that one.

I hope you enjoyed this testing tip. No need to reiterate how blissful it is to test web services using soapUI and Fiddler if you are a web service developer/provider to remote clients.

Strategy Design Pattern in .Net

September 26, 2010 Leave a comment

Strategy design pattern falls under the category of Behavioral Design Pattern. In this pattern, we capture abstraction in an Interface or Abstract class called Strategy Base, and we bury implementation details of algorithms in concrete classes called Concrete Strategy. Client code can then call such different implementation methods based upon some strategy or condition during run time. Client is not tied statically or bound to call fixed methods, rather it can change its strategy dynamically. This is because client never calls any methods directly by instantiating concrete classes. Client sets its strategy via some other class called Context.

Let’s see one such example of this pattern.

StrategyDesignPattern
Fig: Strategy Design Pattern showing all three main components- Strategy Base, Concrete Strategy and Context Classes.

Coming to code, we have:

namespace BehavioralDesignPattern.StrategyDesignPattern
{
public abstract class StrategyBase
{
public abstract long Calculate(int x,int y);
}

public class ConcreteAddStrategy : StrategyBase
{
public override long Calculate(int x, int y)
{
return x + y;
}
}

public class ConcreteSubtractStrategy : StrategyBase
{
public override long Calculate(int x, int y)
{
return x - y;
}
}

public class Context
{
public StrategyBase Strategy { get; set; }
public long CallCalculateMethod(int x, int y)
{
return (Strategy.Calculate(x, y));
}
}
}

We see each of the concrete strategy class implementing algorithm to calculate upon numbers in its own way- one doing addition, while other doing subtraction. But their over all capability to do arithmetic operations upon numbers is abstracted inside Calculate(int, int) method in StrategyBase class.

See the Context class above. It has a property Strategy to get-set of type StrategyBase type. Alternatively, Context class can get-set instance of StrategyBase by a constructor or some method as well like SetStrategy(StrategyBase objSB).

But why do we require this Context class? Because clients agree to call any ConcreteStrategy method not directly. Clients will only hint out for such concrete strategy. What does this mean? This means a lot- Strategy pattern lets you change the guts of an object.

See the client code below:

private void CallStrategyAddMethod()
{
//
Context objCtxt = new Context();
objCtxt.Strategy = new ConcreteAddStrategy();
// Now the object's strategy is to call Add method.
objCtxt.CallCalculateMethod(10, 15);
}

As seen from the above code, object “objCtxt” is able to call method in a concrete strategy class.

Whenever modeling a system after Strategy Design Pattern, one has to carefully think of a way to allow client to convey its strategy to context class.

That’s it.

Template Method Design Pattern in .Net

September 26, 2010 Leave a comment

Template method design pattern falls under the category of Behavioral Design Pattern. In this pattern, a template method defines a skeleton of an algorithm in terms of abstract operations. The template method can contain one or more steps. But these steps will have to be in abstract form only. That said, we cannot change the order of steps, and most importantly we cannot override the template method itself. Only the steps given in the skeleton of algorithm of template method need to be overridden in concrete classes.

Let’s see how classes can be designed in this template pattern.

emplateMethodPattern

Fig: High Level Class Diagram of Template Method Design Pattern

And see the code implementation below:

namespace BehavioralDesignPattern.TemplateMethod
{
public abstract class AbstractAlgorithmSkeleton
{
public void TemplateMethod()
{
// Template Method declaring algorithm
// in terms of abstract operations.
Step1();
Step2();
Step3();
}
public abstract void Step1();
public abstract void Step2();
public abstract void Step3();
}

# region "Concrete Implementations of abstract operations defined in Template Method"
public class ConcreteClassA : AbstractAlgorithmSkeleton
{
public override void Step1()
{
Console.WriteLine("ConcreteClassA, Step 1");
}

public override void Step2()
{
Console.WriteLine("ConcreteClassA, Step 2");
}

public override void Step3()
{
Console.WriteLine("ConcreteClassA, Step 3");
}

public void OtherMethodA()
{
//
}
}

public class ConcreteClassB : AbstractAlgorithmSkeleton
{
public override void Step1()
{
Console.WriteLine("ConcreteClassB, Step 1");
}

public override void Step2()
{
Console.WriteLine("ConcreteClassB, Step 2");
}

public override void Step3()
{
Console.WriteLine("ConcreteClassB, Step 3");
}

public void OtherMethodB()
{
//
}
}

# endregion "Concrete Classes Implementation"
}

We see the concrete classes are overriding the abstract operations defined by the template method in its algorithm. This way template method pattern provides an abstract view of algorithm.

So in practical scenario, this pattern fits only when different types of object instances are required to invoke methods or operations that differ sharply in implementation but the algorithm remaining same. Also, sometimes when are refactoring multiple classes, we can find template method pattern coming into picture.

Consuming the template method:

private void CallTemplateMethod()
{
AbstractAlgorithmSkeleton objTemplate = null;
objTemplate = new ConcreteClassA();
// Now this call to TemplateMethod() will direct calls
// to methods in ConcreteClassA.
objTemplate.TemplateMethod();
}

Important point to note here is: the way we are calling TemplateMethod() of ConcreteClassA from base class AbstractAlgorithmSkeleton reminds us of “The Hollywood Principle”- “Do not call us, we will call for you”. That is, child class method is being called from base class. This way of method call is also known as Inversion of Control.

That’s it.

Decorator Design Pattern in .Net

September 19, 2010 Leave a comment

Decorator design pattern falls under the category of Structural Design Pattern. Structural design pattern emphasizes upon the overall structure of classes and objects in the system either by doing class inheritance or by composing objects into larger structures using object composition. Decorator pattern comes handy when we want to add additional responsibilities to the object during run time.

  • Additional responsibilities can be added statically by class inheritance also. But this will create another problem when we want to add such responsibilities to objects of many classes. We may have to create many child classes to support additional new functions.
  • So instead of creating many child classes of already existing concrete classes, we create a new Decorator, and a new Concrete Decorator class that will add new methods and properties to the existing class object during run time. This way we are not modifying the existing concrete or legacy classes. Responsibilities to objects can be added during runtime because base class of the object and Decorator class share the same base type. And Concrete Decorator class extends the new Decorator.

This design pattern does not come initially during system design. It generally comes during maintenance phase or later in the development phase.

Now let’s see the example of decorator design pattern. We even use mobile phone to send text and multimedia messages. Once the message is sent, the Outbox becomes empty. But sometimes we want to save the sent content message. To do this, we need to select the option of “Send and Save”, and any message sent this way will be saved inside “Sent” folders. Here, even if the user may not always want to save the sent messages, it is for sure that he may definitely want to send messages. Keeping this use case in mind, let’s look into such a class design.

BaseMessage
Fig: Base class for SMS and MMS Concrete Classes

Decorator
Fig: Overall class structure after the introduction of Decorator

From the above diagram, we see two main concrete classes that are involved in sending messages- MobileMMS sends image as message content while MobileSMS send text. Both of the classes are doing well with SendMessage() method. SendMessage() is an abstract method in BaseMessage root class. Decorator, often called DecoratorBase, can be seen inheriting from the same base type of these two MobileMMS and MobileSMS classes, i.e.; inheriting from BaseMessage class. For a Decorator class this is important.

Then, we see MessageProcessor class (often called ConcreteDecorator) which is a concrete implementation of Decorator.

Note: BaseMessage, MobileMMS and MobileSMS are the original classes. Only due to SendAndSave option, a new responsibility SaveMessage() is now required to be added into the objects of MobileMMS and MobileSMS. This is how we see DecoratorBase and ConcreteDecorator need to be added later on.

Now let’s see the actual implementation of the classes.

namespace DecoratorPattern
{
abstract class BaseMessage
{
private string _sender;
private string _recipient;
public string MessageSender
{
get
{
return this._sender;
}
set
{
this._sender = value;
}
}
public string MessageRecipient {
get
{
return this._recipient;
}
set
{
this._recipient = value;
}
}
public abstract void SendMessage();
}
}
namespace DecoratorPattern
{
class MobileSMS: BaseMessage
{
private string _message;
public MobileSMS(string strSender, string strRecipient, string strMessage)
{
this.MessageSender = strSender;
this.MessageRecipient = strRecipient;
this.Message = strMessage;
}
public string Message
{
get
{
return this._message;
}
set
{
this._message = value;
}
}
public override void SendMessage()
{
//Send Text message
}
}
}
namespace DecoratorPattern
{
class MobileMMS:BaseMessage
{
private byte[] image;
public MobileMMS(string strSender, string strRecipient, byte[] image)
{
this.MessageSender = strSender;
this.MessageRecipient = strRecipient;
this.Image = image;
}
public byte[] Image
{
get
{
return this.image;
}
set
{
this.image = value;
}
}
public override void SendMessage()
{
//Send MMS message
}
}
}
namespace DecoratorPattern
{
class Decorator: BaseMessage
{
protected BaseMessage message;
public Decorator(BaseMessage message)
{
this.message = message;
}
public override void SendMessage()
{
message.SendMessage();
}
}
}
namespace DecoratorPattern
{
class MessageProcessor:Decorator
{
public MessageProcessor(BaseMessage message): base(message)
{
}
public void SaveMessage()
{
//Saves outgoing message
}
public override void SendMessage()
{
//
base.SendMessage();
SaveMessage();
}
}
}

Now see the SendSMS and SendMMS methods: how the constructor methods of MessageProcessor are accepting object instances. This is called object composition, and important for Concrete Decorator. This way MessageProcessor will be able to direct the call to the actual method of the class. See the SendMessage() method code above in MessageProcessor.

Client Code

namespace DecoratorPattern
{
class Program
{
public enum SendMessageOption
{
SendOnly = 0,
SendAndSave = 1
}
private void SendSMS(SendMessageOption option)
{
//Send SMS
MobileSMS sms = new MobileSMS("123", "456", "This is example of decorator pattern.");
if (option == SendMessageOption.SendOnly)
{
sms.SendMessage();
}
else if (option == SendMessageOption.SendAndSave)
{
MessageProcessor msgProcessor = new MessageProcessor(sms);
msgProcessor.SendMessage();
}
}
private void SendMMS(SendMessageOption option)
{
//Send MMS
MobileMMS mms = new MobileMMS("123", "456", new byte[] { 1, 2, 3, 4 });
if (option == SendMessageOption.SendOnly)
{
mms.SendMessage();
}
else if (option == SendMessageOption.SendAndSave)
{
MessageProcessor msgProcessor = new MessageProcessor(mms);
msgProcessor.SendMessage();
}
}

static void Main(string[] args)
{
//
Program obj = new Program();
obj.SendSMS(SendMessageOption.SendOnly);
obj.SendSMS(SendMessageOption.SendAndSave);
obj.SendMMS(SendMessageOption.SendOnly);
obj.SendMMS(SendMessageOption.SendAndSave);
//Wait for user enter key
Console.Read();
}
}
}

Hope the Decorator design pattern is now simple enough to understand.

Embedding and Using Resources from .Net Assembly

.Net Assemblies can contain various types of resources like images, icons, files, etc. Such resources are mostly static, i.e.; do not keep changing during run time or application wise. Also, such resources are not executable items. So while deploying such assemblies, we need to make sure those resources are intact with the packaged assemblies. Else, assemblies may blow up while executing the resource dependent methods. So as part of deployment strategy, we should embed such resources into the assembly itself.

Today we will see one such example of embedding Xml file into assembly.

  • Add one Class Library type project into the solution.
  • Add one Xml file as well. Fill Xml file with few data that the class library may use to query.
  • Right click on the Xml file, and select Properties –> Build Action. Out of several Build Action options, select Embedded Resource.

ResourceProperties

  • There you may see other properties as well like Copy to Output Directory. It has options like this:

ResourceSettings

  • If you select Do Not Copy, output of building the class library inside \bin\ folder will not have separate *.dll than embedded Xml file.
  • If you select Copy Always, output of building the class library inside \bin\ folder will always have *.dll and an embedded Xml file.

However, I prefer the first option. By this we make sure our distributable assembly is only one *.dll. This way the embedded resource Xml file cannot be modified, and our assembly can safely execute methods that depend upon this Xml file. I like to suggest one more tips here- rename this Xml file extension to *.config. Renaming Xml file extension to *.config makes file not browse able by Browser in web applications.

Here I have shown steps of embedding resource file into .Net assembly. This assembly can be either Class Library or Web application. We cannot embed resource file into web site type project as Web site does not produce assembly like Web application.

Now, let’s see how we can access embedded Xml file from assembly during runtime.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;
using System.IO;

namespace MathLibrary
{
public class MathLibrary
{
//
private const string strFileName = "XMLFile.config";

public System.Xml.XmlDocument GetXMLDocument()
{
//
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStreamthis.GetType(), strFileName);
var doc = new XmlDocument();

try
{
if (stream == null)
{
throw new FileNotFoundException("Couldnot find embedded mappings resource file.", strFileName);
}
doc.Load(stream);
}
catch (Exception ex)
{ throw ex; }
return doc;
}

public System.IO.Stream GetXMLStream()
{
//
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(this.GetType(), strFileName);

try
{
if (stream == null)
{
throw new FileNotFoundException("Couldnot find embedded mappings resource file.", strFileName);
}
}
catch (Exception ex)
{ throw ex; }
return stream;
}
}
}

There are two methods shown above- one returning XmlDocument object and other returning IO.Stream. Either of the return type can be used to construct XmlDocument object now at caller end of these methods.

Now let’s verify the assembly if it has any embedded resource or not. We can do this using either Reflector or Ildasm tool.

Reflector View:

ReflectorView

Ildasm View:

IldasmView

See resource name is qualified with assembly namespace name prefixed to it- MathLibrary.XMLFile.config.

Happy Coding!

Visual Studio 2010: Exporting and Importing Break-Points

Coding less and debugging more has always been part of programming. Debugging of code is always accompanied by locating appropriate break-points and inspecting program execution. But locating break points again and again whenever a solution is opened for debugging consumes time. When we feel the program execution is happening as expected, then we either delete break-points or disable them. Overall, programmers spend few minutes for break-points activities.

Visual Studio 2010 comes with new feature of exporting and importing break-points in an xml file. So when we are done with break-points, we can export and save at a physical location. Then, delete the break-points (Ctrl + Shift + F9). Whenever we require break-points again in code, we can import the settings file that we saved last time. This xml file contains all the required settings of break-points in the code like line number, file name, etc.

Snapshots shown below are self-explanatory for .Net programmers.

Open break-point window (Ctrl + Alt + B).

ExportBreakPoints
Fig 1: Exporting break-points

ImportBreakPoints

Fig 2: Importing break-points

After importing break-point xml file, the break-points are again set at lines and files where break-points were set originally.

BreakPoint-XmlStructure
Fig 3: Break-point xml structure

Cheers!

ASP.Net 4.0 New Features

ViewStateMode – ViewState for Individual Controls
ASP.Net 4.0 allows view state in a page to be more controllable from page to its child controls level. That is, view state of a control can be enabled or disabled irrespective of its parent control’s view state. Even if view state of a page is disabled, controls of the page can have their own view state individually enabled or disabled or even inherited from the page’s view state mode property.
This property if utilized properly can certainly boost performance of a page.

For example, we can individually enable or disable user control’s view state in a page.

ViewStateMode

By default, ViewStateMode is enabled for a page object, while controls have inherit mode.

Page.MetaKeywords and Page.MetaDescription – SEO Optimization Feature
ASP.Net 4.0 has come up with these two properties that will help developers add meta tags for keywords and description in the aspx pages in easier fashion. Web Search Engines really need these two meta tags for search indexing of any pages. These two properties can be used in a page in various ways. Inside <head> tag or in the code behind or even at <%@Page%> directive level.

However, setting meta keywords or description in code behind will be more useful when we have to add keywords and descriptions dynamically from source like database.

MetaKeyWords is used to store few useful keywords that will briefly highlight important information of a page by tags. From SEO perspective, meta keywords should contain keywords separated by spaces.

MetaDescription is used to add page description in short that will help Search Engines to quickly describe about the page links in search pages.

Prior to ASP.Net 4.0, we have to add meta tags using HtmlMeta control (public class HtmlMeta : HtmlControl) adding into page header as:

protected void Page_Load(object sender, EventArgs e)
{
//
HtmlMeta metakey = new HtmlMeta();
metakey.Name = "keywords";
metakey.Content = "ASP.Net 2.0 3.5";
HtmlMeta metadesc = new HtmlMeta();
metadesc.Name = "description";
metadesc.Content = "ASP.Net 2.0 3.5 Page Description...";
//Add to page header
Page.Header.Controls.Add(metakey);
Page.Header.Controls.Add(metadesc);
}


In ASP.Net 4.0, we can add in many ways.

protected void Page_Load(object sender, EventArgs e)
{
//Adding Page meta tags information
this.Page.MetaKeywords = "ASP.Net 4.0 SEO Meta Tag";
this.Page.MetaDescription = "Serializing and Deserializing Thoughts..";
}

Or,

<head runat="server">
  
<title>Feature: ViewStateMode</title>
<meta name="keywords" content ="ASP.Net 4.0 ViewStateMode"/>
<meta name="description" content="ViewStateMode feature in ASP.Net 4.0" />
</head>

Or inside Page directive,

MetaDescription

Response.RedirectPermanent – Search Engine Friendly Webpage Redirection

In classic ASP or ASP.Net earlier than 4.0, we used to redirect to new pages or links by setting Response.StatusCode to 301 before calling Response.AddHeader method. Now ASP.Net 4.0 has provided Response.RedirectPermanent method to redirect to new pages or links with StatusCode of 301 implicitly set. Search Engines use this 301 code to understand permanent redirection from old pages links.

For example,

Classic ASP method:

<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://www.new-page-url.com/"
%>


ASP.Net method prior to 4.0:

<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.new-page-url.com");
}
</script>


ASP.Net 4.0 method:

Response.RedirectPermanent("http://www.new-page-url.com ");


Web.Config Refactoring – Custom HttpHandlers and HttpModules

Web.config now looks cleaner as most of the settings are controlled from machine.config file as ASP.Net 4.0 is all set to benefit from IIS 7 and IIS 7.5 features. When IIS is set to use .Net 4.0 and Integrated Pipeline mode, <compilation> element holds .Net version attribute. And the traditional <httpHandlers> and <httpModules> section is now shifted out of <system.web> and added inside new section <system.webserver>. All the custom handlers are added inside <handlers>, and all the modules inside <modules> section.

<system.webServer>
<!-- Add the module for Integrated mode applications -->
<modules runAllManagedModulesForAllRequests="true">
<add name="MyModule" type="WebAppModule.MyCustomModule, WebAppModule" />
</modules>
<!-- Add the handler for Integrated mode applications -->
<handlers>
<add name="MyHandler" path="svrtime.tm" verb="GET" 
<type="WebAppModule.MyCustomHandler, WebAppModule"
preCondition="integratedMode" /> </handlers> </system.webServer>


Also,

<system.web>
<compilation debug="true" targetFramework="4.0" />


Interesting point is, when we add custom handlers and modules this way, we do not have to manually configure handlers and modules in IIS again. IIS will automatically refresh itself.

Exception Handling in WCF

We have been doing exception handling in managed application using try-catch block with Exception or its derived Custom Exception objects. But this mechanism is very much .Net Technology specific. When we develop SOA applications, our application is not limited to mere one technology or single loyal client. So the communication process of this service or service method level errors to client via wire becomes a little bit tricky. WCF has two types of error handling mechanism: one is by as usual Exception objects, and other is by SOAP fault message. SOAP fault is used to marshall .Net exceptions to client in much readable and convenient way to support interoperability. With use of SOAP fault, the verbose exception message is reduced to Code and Message. For this System.ServiceModel namespace comes FaultException class and FaultContract attribute.

Let’s come to see from example on how to do exception handling in WCF application. Before this, write our service first.

namespace WcfSvc
{
[ServiceContract]
public interface IBasicMathService
{
[OperationContract]
int Subtraction(int x, int y);

[OperationContract]
int Multiplication(int x, int y);

[OperationContract]
[FaultContract(typeof(BasicMathFault))]
int Addition(int x, int y);
}

[DataContract]
public class BasicMathFault
{
//
[DataMember]
public string Source;

[DataMember]
public string ExceptionMessage;

[DataMember]
public string InnerException;

[DataMember]
public string StackTrace;
}
}

And its implementation is as:

public class BasicMath : IBasicMathService
{
public int Addition(int x, int y)
{
//
int result = 0;
try
{
result = (x + y);
}
catch
{
BasicMathFault ex = new BasicMathFault();
ex.Source = "BasicMath.Addition method";
ex.ExceptionMessage = "Could not perform addition operation.";
ex.InnerException = "Inner exception from math service";
ex.StackTrace = "";
//Throwing strongly-typed FaultException
throw new FaultException(ex, new FaultReason("This is an error condition in BasicMath.Addition method")); }

return result;
}

public int Multiplication(int x, int y)
{
//Due to some calculation error condition, let’s assume we are throwing this error.
//Throwing simply FaultException
throw new FaultException(new FaultReason("Error occurred while processing
for the result"), new FaultCode("mutliplication.method.error"));
}

public int Subtraction(int x, int y)
{
//Exception we generally throw in managed application in the form of Exception object
throw new NotImplementedException("Method still not implemented");
}
}

This is our typical service related code. If we see IBasicMathService interface and its implementation in BasicMath class, we have:

Addition(x,y) method decorated with FaultContract attribute in IBasicMathService class,

Subtraction(x,y) method using simple Exception throwing mechanism,

Multiplication(x,y) method using simple FaultException object, and

Addition(x,y) method using strongly-typed fault of type BasicMathFault in FaultException object

So what does all this mean to client, and how exception is transmitted to client? Let’s answer with these three examples in our client code.

A) Throwing Simple Exception

private void SubtractIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Subtraction(10, 15);
}
catch (Exception ex)
{
Response.Write(ex.Message + "
");
}
}

When this method is called, client receives verbose error message from WCF as:

“The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.”

If we closely see this error information, we come across two things: turn on\off IncludeExceptionDetailInFaults value either through ServiceBehaviorAttribute of the class containing this method, or modify IncludeExceptionDetailInFaults value in configuration file or section of this service.

Either of these two things is pretty easy.

a) Decorate BasicMath class as:

[ServiceBehavior(IncludeExceptionDetailInFaults = false)]
public class BasicMath : IBasicMathService
{

b) Or, modify in config file

By default this key value is false. If we make it true, the verbose error message that we received will be reduced to human readable message that we passed in constructor of NotImplementedException.

“Method still not implemented”

While debugging WCF exception, one may encounter error in the service like “xyz exception unhandled by user code”. This is some what misleading, but no need to worry.

B) Throw exception of FaultException type

private void MultiplyIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Multiplication(10, 15);
}
catch (FaultException ex)
{
Response.Write(ex.Message + "");
}
}

On calling this method, WCF will serialize the exception as a Fault message and return to the client as:

“Error occurred while processing for the result”

However, client is unlikely to receive verbose error message if we throw exception of type FaultException even key IncludeExceptionDetailInFaults is true or false. If we see the exception thrown code,

throw new FaultException(new FaultReason("Error occurred while processing for the result"), new FaultCode("mutliplication.method.error"));

we have used FaultCode. Client can use this specific fault code contained in FaultException code to take decision, but this approach becomes more of procedural by many if-else condition to branch out code some thing like:

if (ex.Code.Name == "mutliplication.method.error")
{
Response.Write(ex.Message + "");
}

C) Throwing with strongly typed fault

private void AddIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Addition(10, 15);
}
catch (FaultException ex)
{
Response.Write(ex.Message + " ");
}
}

With this approach, client will be able to explicitly handle fault of only that type whose service method is to be used by client. Here, we are using BasicMathFault type. At the service level, the specific method has to be decorated with FaultContract attribute so that exception can be serialized as:

[OperationContract]
[FaultContract(typeof(BasicMathFault))]
int Addition(int x, int y);

The detail of fault type is up to our convenient level to let WCF serialize only needful information to client.

When we call this Addition(x,y) method, one may receive this error message if an exception occurs.

“This is an error condition in BasicMath.Addition method”

Thus, we see how we can do exception handling in WCF.

Designing Business Logic Layer: Some Guidelines

Business Logic Layer is a very crucial layer for any data base applications. A timely thought when applied to this layer from the beginning of application layers design can save lots of time and complexity. Software architects divide the software into modules, then different layers, and core functioning layers for important application features. But when actual development work starts, complexity of different layers and modules start crawling into code gradually.
Reason being:
• We try to mix business rules of different modules wishfully
• Writing methods with abundant codes
• Not clearly separating responsibilities of presentation and data access layers
• Creating code duplicity, i.e.; writing same set of code or methods at various places

Results are:
• Difficult to debug
• Difficult to understand the flow
• Difficult to maintain and modify business rules correctly when such rules exist across layers and modules
• Difficult to write Unit Tests

We can avoid these things if we take care of these things when writing codes.
• Write methods that do single meaningful task with one call. Do not mix other code logic with the methods. For example, if we write SavePayment() method, then this method should only focus on save task, and not update or delete or check connection status or read Xml files, etc. This is what we call Single Responsibility Principle.
• Encourage use of factory methods for object creation instead of writing lots of If-else constructs based upon some input type values.
• When you need data or result sets (DTO) of other modules, then preferably call business logic layer methods of that module instead of writing that module code logic into yours. This is quite important aspect for any business logic layer.
• Classes in this layer should be loosely coupled. For this different injection patterns like dependency injection or inversion of control, etc can help. Sometimes even a simple Enum type can come to a great rescue.
• Write business methods that accept valid entity class object or DTO object in business rather than single valued parameters like integer or string or array or even optional params. This ensures business logic layer code function even unmodified when there are database table and entity or DTO class changes in behind.
• Avoid lots of business rules in stored procedures or even in presentation UI.
• Business logic layer methods should not be aware of presentation UI controls’ properties or values. These methods should accept values in integer or string instead.

Let me explain all these points by one example. I worked in an accounting module of a project where customers can make payments of their bills in various ways. They can make either full payment or in-partial or even in installments. For each payment mode, there were different rules and validations. So this module had clear separation of implementation with rules of each mode functioning without depending upon others. This way our lots of coding and debugging time got saved.
Let’s see the code snippets.

Enum showing different Payment Mode

public enum PaymentMode

{
Normal,
Part,
Installment
}

Custome Bill DTO

public class CustomerBillDTO

{
private Int64 intBillNo;
private Int16 intBillMonth;
private Int16 intBillYear;
private double dblBillAmount;
private string strCustomerID;
private Int64 intPayAmount;
//And many other fields…
}

Payment Processor factory class

interface IPaymentProcessorFactory
{
//
IPaymentProcessor GetPaymentProcessor(PaymentMode mode);
}

public class PaymentProcessorFactory : IPaymentProcessorFactory
{
//
private IPaymentProcessor objPaymentProcessor = null;

public IPaymentProcessor GetPaymentProcessor(PaymentMode mode)
{
//
switch (mode)
{
case PaymentMode.Normal:
objPaymentProcessor = new NormalPaymentProcessor();
break;

case PaymentMode.Part:
objPaymentProcessor = new PartPaymentProcessor();
break;
case PaymentMode.Installment:
objPaymentProcessor = new InstallmentPaymentProcessor();
break;
}
return objPaymentProcessor;
}
}

Different Payment Processor class

public interface IPaymentProcessor

{
//
bool SavePayment(CustomerBillDTO Bill);
}

public class NormalPaymentProcessor:IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

public class PartPaymentProcessor : IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

public class InstallmentPaymentProcessor : IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

Main class that processes each payment

class PaymentProcess

{
private IPaymentProcessorFactory objProcessor = null;
public PaymentProcess(IPaymentProcessorFactory Processor)
{
//
this.objProcessor = Processor;
}

public bool ProcessPayment(CustomerBillDTO Bill, PaymentMode mode)
{
//
IPaymentProcessor objPaymentProcessor = this.objProcessor.GetPaymentProcessor(mode);
return objPaymentProcessor.SavePayment(Bill);
}
}

At the calling end, we simply make a generous call as:

private void BtnSave_Click(object sender, EventArgs e)
{
//
PaymentProcessorFactory objFactory = new PaymentProcessorFactory();
PaymentProcess objProcess = new PaymentProcess(objFactory);
bool result = objProcess.ProcessPayment(objCustomerBillDTO(), PaymentMode.Normal);
}

As we see this is how we have clearly separated each logical functioning of a SavePayment() method.
Even in future, if Part or Installment payment mode is stopped, we do not have to modify the code logic to add any If-else construct to branch out or skip any code flows. In case a new payment mode is added, then writing a new XModePaymenetProcessor class, adding one more Enum value and finally one more object instantiation code in factory class will do enough.

Adding or removing any Bill or Customer related fields in CustomerBillDTO do not even pose threat to this business logic layer.

Finally, one should always keep in mind that you write class and class methods for others. So you should be very clear here: what the class should offer and how.

Thanks.

Follow

Get every new post delivered to your Inbox.