Posts Tagged ‘.NET’

This week I came across a problem related to structuring an ASP.NET MVC Web application one development team was facing. What they were trying to do was quite simple: to create a folder structure each having their own subfolders for View/Controller/Scripts/CSS etc. The application resources like JS/CSS etc. were not getting rendered properly. The issue was due to Web.config file lying under the subfolder, which when moved to the Views folder under that subfolder things went fine. The purpose of this post is not to discuss about the details of that problem and it’s solution.But to discuss about how we can easily structure our ASP.NET MVC Web application as per different modules, which is an obvious need for any large application.

ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions works fine for a smaller application. But for relatively bigger one there is a need to customize.The framework also provides enough provisions for the same.You can have your own controller factory to have custom ways to creating the controller classes and custom view engine for locating the rendering the views. But if the requirement is to structure the application to different subfolders as per modules or subsites  I think the use of “Area” in ASP.NET MVC will be helpful to create a streamlined application.

You can add an Area to a ASP.NET MVC project in VS as shown below.

area1

area2

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

area3

The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration 
{ 
    public override string AreaName 
    { 
        get 
        { 
            return "Sales"; 
        } 
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    { 
        context.MapRoute( 
            "Sales_default", 
            "Sales/{controller}/{action}/{id}", 
            new { action = "Index", id = UrlParameter.Optional } 
        ); 
    } 
} 

System.Web.Mvc.AreaRegistration is the abstract base class use registering the areas into the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) needs to be overriden to register the area by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the necessary information (like Routes) required to register the area.

In Global.asax.cs Application_Start event we need to RegisterAllAreas() method as shown below:

AreaRegistration.RegisterAllAreas();  

The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

 

area4

Now I am trying to run the application and got the following error: [NOTE: This has nothing to do with areas but because I have two controllers with same type name i.e. HomeController]

Multiple types were found that match the controller named ‘Home’. This can happen if the route that services this request (‘{controller}/{action}/{id}’) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the ‘MapRoute’ method that takes a ‘namespaces’ parameter.

The request for ‘Home’ has found the following matching controllers:

AreasDemo.Controllers.HomeController

AreasDemo.Areas.Sales.Controllers.HomeController

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes) 
{ 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute( 
                "Default", // Route name 
                "{controller}/{action}/{id}", // URL with parameters 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults 
                new String[] { "AreasDemo.Controllers" } 
            ); 
}

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

 
<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);

For navigating within the “Sales” area however routeValues will not be required.

Advertisements

Custom Layout in WPF

Posted: March 14, 2010 in .NET, WPF
Tags: ,

The layout system in WPF is responsible for measuring and arranging the user interface elements within the panel and displaying them on screen.This is a two phase process.In the measure phase the panel will measure what is the amount of space required by each of it’s children, in order to find out the total space required.In the next arrange phase it will find out how much space it actually has and accordingly render the elements as per predefined logic.

(more…)

Covariance & Contravariance – Delegates in C#

Posted: November 30, 2008 in .NET
Tags: ,

In my last post I had discussed about delegates in C# but intentionally skipped the covariance and contravariance with respect to delegates.I would like to discuss the concepts of covariance and contravariance in general first and then correlate the same in context of C# delegates.The concept of covariance and contravariance I found a bit confusing and counterintuitive initially.

Let us consider a type/class P and let P” be a subtype/subclass of T.We will denote this relationship as P”->P for sake of discussion.Based on this inheritance relationship following statements are true:

  1. Domain of P is much broader than P”.
  2. Any context where P is expected we can substitute it by P” [Liskov Substitution Principle]

Similarly we have another pair of classes R and R” where R”->R.

Now we will consider a function f which type P as parameter and returns type R.We will denote this as R f(P).Similarly there is another function f” as R”f”(P”) which accepts P” as parameter and returns type R”.

Can we say that f”->f or we can replace f by f” in any context?

In order to replace f by f”, f” should be able to handle parameter of type P and return value of type R.

Now R” is a subclass of R,so R” is a type of R.Hence we can say f” basically returns a type R.This is covariance by which we can replace a method by another having a more derived return type.

Now let’s see can f” handle a parameter of type P.The answer is NO.The logic built into f” is only for the possible values of P” and P can have more possible values than P” as it is the super class.So f” will malfunction for all those values of P which are outside the range of P”.So f” can replace f only if parameter of f is more derived than that of f”.This is contravariance by which we can replace a method by another having parameter types that are less derived.

If we redefine f as R f(P”) and f” as R” f”(P) then we can say f”->f and can replace f in any context.

Now let us consider an example with some real life examples.

There is a base class called Order and Order can be of two derived types say SalesOrder and PurchaseOrder.Similarly there is a base class called AccountRecord and there are two derived classes say AccountPayable and AccountReceivable.

There are two methods

  1. M1 – AccountRecord GetAccountInfo(Order o)
  2. M2 – AccountPayable GetAccountInfo(PurchaseOrder po)

M2 cannot accept a variable of type O as parameter because if it is an instance of SalesOrder instead of PurchaseOrder this will fail.

But calling code which expects AccountRecord as output can very well handle both AccountPayable and AccountReceivable.

We can relate this to a delegate in the following way:

public delegate object ReadObjectDelegate(FileStream fs)

We can attach the following method to this delegate

public string Read(Stream s)

This is because Stream is less derived than FileStream and string is more derived than object

Delegates in C#

Posted: November 29, 2008 in .NET
Tags: ,

Most of us quite familiar with the delegate keyword in C#.Delegates provides us with a mechanism to encapsulate a method or multiple methods.These are quite like managed version of function pointers in C#.We normally use delegates to define callback methods.

First we need to define a delegate as a type with it’s signature as shown below.Note here the signature includes both parameters as well as return values.

public delegate void DemoDelegate(int i);

To use the delegate we need define a variable to type DemoDelegate ,instantiate the variable by passing a method name of matching signature and then invoke the delegate by passing suitable parameter values as shown in the snippet below:

class DelegateSample
   {
       public void ShowDemo()
       {
 
          DemoDelegate d = new DemoDelegate(Test); //Create instance
           d(10); //Invoke delegate
       }
       public void Test(int i)
       {
           Console.WriteLine(“Method Test called with parameter ” + i);
       }
   }

Now if we take close look into the syntactic details we see all the operation related to delegate closely resembles that of a reference type.So what’s going on inside.On taking a look into the IL code of the assembly we found a new class is generated as shown below:

.class /*02000003*/ public auto ansi sealed DelegateDemo.DemoDelegate
       extends [mscorlib/*23000001*/]System.MulticastDelegate/*01000002*/
{

……….
} // end of class DelegateDemo.DemoDelegate

So the C# compiler internally generates a class with the same name as the delegate type and it inherits from a class System.MulticastDelegate.The class System.MulticastDelegate is derived from base class System.Delegate.This method provides two public attributes

  1. Method – Metadata Method which is getting executed as an instance of System.Reflection.MethodInfo
  2. Target – Stores the instance on which delegate method executes.

Before we proceed further let us take a quick look into another feature of delegate chaining.Refer to the sample below and refer to the lines marked in red.

class DelegateSample
  {
      public void ShowDemo()
      {
          DemoDelegate d1 = new DemoDelegate(Test);
          DemoDelegate d2 = new DemoDelegate(Demo);
          Console.WriteLine(“Delegate Added”);
          DemoDelegate d3 = d1 + d2; //Two delegates are combined
          d3(10); //First method  Test and then Demo is invoked
          Console.WriteLine(“Delegate Removed”);
          DemoDelegate d4 = d3 – d1; //One delegate is removed from the combination
          d4(10);  //Only method Demo is invoked as delegate d1 is removed.
      }
      public void Demo(int i)
      {
          Console.WriteLine(“Method Demo called with parameter ” + i);
      }
      public void Test(int i)
      {
          Console.WriteLine(“Method Test called with parameter ” + i);
      }

What happens when I do + and – operation on delegates.Internally the methods System.Delegate.Combine and System.Delegate.Remove is invoked by the runtime.This we can see in the IL code of the show demo method:

.method public hidebysig instance void  ShowDemo() cil managed
{

  …………..

  IL_0028:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                          class [mscorlib]System.Delegate)
  ……………

  IL_0049:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
                                                                                         class [mscorlib]System.Delegate)
  ……………..

} // end of method DelegateSample::ShowDemo

WCF Web Model – POX/JSON Support

Posted: October 28, 2008 in .NET, WCF
Tags: , , , ,

For the past few days I was studying the details of the Web Programming Model of WCF.This feature enables WCF services to be called using simple HTTP requests i.e. without the messages wrapped in SOAP format.The messages can be POX(Plain Old XML) or JSON(JavaScript Object Notation).So the client for this kind of services does not need any specific proxy or WSDL.But how client is made aware of the service metadata is still a question to me.However parking that question aside for now let us get into, step by step how this feature is built using the extensibility points provided by WCF infrastructure.

Client Side

Let us first think of what the client is going to send to the service?Just a HTTP request.The method may be GET or POST.Suppose I am trying to access a service operation Add(int i,int j) .The client code in C# will be something like as shown below:

HttpWebRequest  request =  HttpWebRequest.Create(http://localhost:9001/Test/Add/?i=1&j=1) as HttpWebRequest;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Method = “GET”;
request.ContentType = “text/xml”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Before we proceed into the details of the service side let me note the down the questions that initially occurred to my mind.

  1. How the HTTP message will read and parsed in the service side?
  2. How from the URI the name of the method Add will be read and request will be dispatched to the correct operation?
  3. How the parameters will be parsed from the querystring?

In the subsequent sections I will try to answer these questions.

Service Side

Binding

In the server side there should be some program listening to a particular socket waiting for bytes to arrive.This is the job of the ChannelListener as I had discussed in one of my earlier posts titled ServiceHost & Channels.This ChannelListener should be able to read raw bytes and create channels to process the HTTP requests.But the channels are created by the specified binding.So we need a binding which can handle HTTP Transport and encode/decode POX and JSON messages.For this we have a binding provided by WCF called WebHttpBinding.This binding is primarily composed of HttpTransportBindingElement and WebMessageEncodingBindingElement.This WebMessageEncodingBindingElement inherits from TextMessageEncodingBindingElement and is a composite encoder which can handle plain text,XML,JSON and raw binary data.

So to make WCF Services available for basic HTTP clients we need to expose an endpoint with WebHttpBinding.

Endpoint

Now we have an service endpoint ,message is processed by channels created by WebHttpBinding and routed to the EndpointDispatcher via the ChannelDispatcher.But who reads the URI of the message and decides which service operation this is intended for?How the parameters values are parsed from the querystring?

The parsing of URI and determination of operation is done by public string SelectOperation( ref Message message ) method of a  WebHttpDispatchOperationSelector class implementing the IDispatchOperationSelector interface.

The querystring parsing and parameter processing is done by a dispatch formatter class implementing the IDispatchFormatter interface with methods:

void DeserializeRequest(Message message, object[] parameters)
Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)

How these two classes gets attached to the DispatchRuntime of the EndpointDispatcher.WCF allows to modify the behaviour of an endpoint using endpoint behaviours.The classes intending to so needs to implement the IEndpointBehavior interface.WCF provides WebHttpBehavior class for modifying the endpoint behavior to suit the needs of POX/JSON messages.This class has three methods to get the operation selector and formatters.

protected virtual WebHttpDispatchOperationSelector GetOperationSelector(ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)

In the operation ApplyDispatchBehavior these components are added to the DispatchRuntime

public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{

      endpointDispatcher.DispatchRuntime.OperationSelector = …
}

How the WebHttpBehavior is added to the ServiceEndPoint??

Host

WCF provides a class called WebServiceHost to host services for web based clients send POX/JSON messages.This class inherits from the ServiceHost class.This class makes sure that WebHttpBinding is properly used and attaches the WebHttpBehavior to the ServiceEndPoint.

Now the last things that I need to mention is the two Operation Behavior attributes that need to be applied to the Service operations:WebInvokeAttribute and WebGetAttribute.These two attributes are passive operation behavior and adds some additional metadata to the operation description.This information is used by the WebHttpBehavior for processing.WebGetAttribute allows only HTTP GET requests whereas WebInvokeAttribute has one Method parameter.This parameter is set to POST by default and can accept GET and PUT as well.

The method signature of the Service operation will look something like:

[OperationContract]
[WebGet/WebInvoke]
int Add(int x, int y);

We have covered almost the entire flow of POX/JSON messages from client to service.

In the next post I will discuss how to extend this framework and plug in custom functionalities…

WCF Sessions

Posted: September 7, 2008 in .NET, WCF
Tags: , ,

Whenever web developers hear the term session, we think of Http Session which is used to store data between multiple HTTP requests.That’s why many of us first get confused , when we hear about WCF Sessions.If we think in a more general term we can define session as something which correlates several messages together into a single conversation.

ASP.NET Sessions are:

  1. Always server-initiated.
  2. Implicitly unordered.
  3. Provide a way to preserve data across multiple requests.There is unique session id generated at the server and passed back and forth between client and server via URL or cookies.

WCF Sessions are

  1. Initiated and terminated by the calling application.
  2. Ordered message delivery
  3. Sessions correlate a group of messages into a conversation.This correlation depdending upon the binding can be taken care at message or transport level.
  4. No data storage is involved with WCF Session

To enable session for a WCF Service first thing that needs to be done is to set the SessionMode property of the ServiceContract attribute.
The three possible values of SessionMode are
1)NotAllowed – Session is prohibited.
2)Required – Session is mandatory.
3)Allowed – Session can be allowed.

Just setting this property is not sufficient to make the service, session enabled.The bindings of the exposed endpoints needs to support session.I developed a sample application to test out the features of WCF Session.I exposed an endpoint with BasicHttpBinding and set SessionMode to Allowed.The application was not throwing up any error but the session was not working.As I changed the SessionMode to Required I got the following error:

{“Contract requires Session, but Binding ‘BasicHttpBinding’ doesn’t support it or isn’t configured properly to support it.”}

This is because BasicHttpBinding does not support sessions.For this we have to choose wsHttpBinding or NetTcpBinding.WSHttpBinding binding, which contains support for both security sessions and reliable sessions.By default it uses only a secure session.The System.ServiceModel.NetTcpBinding binding supports transport level TCP/IP-based sessions.If we specifically turn off the message/transport level security of wsHttpBinding/NetTcpBinding and try to implement session the following exception message will appear:

Contract requires Session, but Binding ‘WSHttpBinding’ doesn’t support it or isn’t configured properly to support it.

As per default behaviour WCF uses the same service object to cater to all the requests within a session.This can be achieved through the attribute [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] We can mark some of the operations as Initiating/Terminating the session by using IsInitiating and IsTerminating properties of the OperationContract attribute.If IsInitiating/IsTerminating property is set then the SessionMode of the service has to Required.otherwise following exception message will appear:

{“The contract ‘ISessionDemo’ is not self-consistent — it has one or more IsTerminating or non-IsInitiating operations, but it does not have the SessionMode property set to SessionMode.Required.  The IsInitiating and IsTerminating attributes can only be used in the context of a session.”}

Initiating operations are those that must be called first. Non-initiating operations has to be be called only after at least one initiating operation has been called. Otherwise following exception message will come:

{“The operation ‘StartSession’ cannot be the first operation to be called because IsInitiating is false.”}

If I mark more than one method as Initiating then no exception will occur all of them will execute as part of the same session.Terminating operations, must be called as the last message in an existing session.After calling the Terminating method the service object and its context after the session with which the service was associated is closed. So if we try to invoke anyother method after the Terminating method the following exception message will come:

{“An operation marked as IsTerminating has already been invoked on this channel, causing the channel’s connection to terminate.  No more operations may be invoked on this channel.  Please re-create the channel to continue communication.”}

So we need to re-initilaize the proxy and related channel to invoke any other operations.

Another thing worth noting is how sessions behave when there is an exception.If there is an exception then the server channel will be faulted and the session will be destroyed along with that.This exception will be propagated to the client channel which in turn becomes faulted and proxy object instance cannot be used any further.If we try to invoke a method using this faulted channel following exception will occur

{“The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.”}

So as a good practice we should check the state of the proxy prior to making a method call.e.g.

if (proxy!=null && proxy.State == CommunicationState.Faulted)
{
   //call the method
}
else
{
 //Recreate the proxy
}

But if the exception is handled at the service end and FaultException is generated, then the channel is not faulted and session works fine for subsequent method calls.

These are things I have noted till now working with WCF sessions.I need to check how exactly message correlation is done by checking the traces.I will discuss that in my next post.

Yesterday I have come across very interesting question:Should one use raw XML as string or Objects as parameters of methods for passing data between tiers.I mostly use objects for doing so.Initially I had a bias towards that approach.But after pondering over the subject I found that both the approaches has it’s own pros and cons and one should choose based mostly on the non functional requirements(performance/maintainability/developer expertise) for the system under discussion.

Object Approach

Pros

  1. All the advantages of object oriented programming and design can be very well used.Code will be simpler and very easy to understand.
  2. When used in WebMethods the schema will be extracted via wsdl as XSD and it will be easier for the client code to interpret the meaning and purpose of the object.

Cons

  1. When the object is to be passed beyond process/machine boundary it will be serialized.
    • For Web Services .NET Framework will be using the XML Serializer.
    • For Remoting it can be the Binary as well as the SOAP formatter
    • .NET XML Serialization internally generates an assembly at runtime for serialization.There will be one assembly per type passed to the constructor of the XMLSerializer constructor.Naturally there is a performance hit because of this.However this assemblies can be generated before hand using the tool SGen.exe.The detailed tips for improvement of XML Serialization can found in the patterns & practices guide.
  2. For any change in the object structure the proxies needs to updated.

 XML Approach

Pros

  1. No additional serialization overhead.
  2. For any change in the object structure the proxies needs not be updated.However this can sighted as a disadvantage as well as the client contract will hazy.Client has to know before the xml structure.There is should be some XSD validation in the service as well.

Cons

  1. Program will be complex as one has to use XMLDOM and Xpath to parse and read/write the values from/into the XML.

That’s all I can think of at this point.

But I would still prefer objects with XMLSerializer unless my performance requirements vs server infrastructure is not at all able to take the load.