Monday, June 29, 2015

Versioning with Override

Versioning with the Override and New Keywords (C# Programming Guide)

Visual Studio 2013
The C# language is designed so that versioning between base and derived classes in different libraries can evolve and maintain backward compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that hides a similarly named inherited method.
In C#, derived classes can contain methods with the same name as base class methods.
  • The base class method must be defined virtual.
  • If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.
  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
  • The base class method can be called from within the derived class using the base keyword.
  • The overridevirtual, and new keywords can also be applied to properties, indexers, and events.
By default, C# methods are not virtual. If a method is declared as virtual, any class inheriting the method can implement its own version. To make a method virtual, the virtualmodifier is used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class.
To demonstrate this in practice, assume for a moment that Company A has created a class named GraphicsClass, which your program uses. The following is GraphicsClass:
class GraphicsClass
{
    public virtual void DrawLine() { }
    public virtual void DrawPoint() { }
}
Your company uses this class, and you use it to derive your own class, adding a new method:
class YourDerivedGraphicsClass : GraphicsClass
{
    public void DrawRectangle() { }
}
Your application is used without problems, until Company A releases a new version of GraphicsClass, which resembles the following code:
class GraphicsClass
{
    public virtual void DrawLine() { }
    public virtual void DrawPoint() { }
    public virtual void DrawRectangle() { }
}
The new version of GraphicsClass now contains a method named DrawRectangle. Initially, nothing occurs. The new version is still binary compatible with the old version. Any software that you have deployed will continue to work, even if the new class is installed on those computer systems. Any existing calls to the method DrawRectangle will continue to reference your version, in your derived class.
However, as soon as you recompile your application by using the new version of GraphicsClass, you will receive a warning from the compiler, CS0108. This warning informs you that you have to consider how you want your DrawRectangle method to behave in your application.
If you want your method to override the new base class method, use the override keyword:
class YourDerivedGraphicsClass : GraphicsClass
{
    public override void DrawRectangle() { }
}
The override keyword makes sure that any objects derived from YourDerivedGraphicsClass will use the derived class version of DrawRectangle. Objects derived fromYourDerivedGraphicsClass can still access the base class version of DrawRectangle by using the base keyword:
base.DrawRectangle();
If you do not want your method to override the new base class method, the following considerations apply. To avoid confusion between the two methods, you can rename your method. This can be time-consuming and error-prone, and just not practical in some cases. However, if your project is relatively small, you can use Visual Studio's Refactoring options to rename the method. For more information, see Refactoring Classes and Types (Class Designer).
Alternatively, you can prevent the warning by using the keyword new in your derived class definition:
class YourDerivedGraphicsClass : GraphicsClass
{
    public new void DrawRectangle() { }
}
Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.

Override and Method Selection

When a method is named on a class, the C# compiler selects the best method to call if more than one method is compatible with the call, such as when there are two methods with the same name, and parameters that are compatible with the parameter passed. The following methods would be compatible:
public class Derived : Base
{
    public override void DoWork(int param) { }
    public void DoWork(double param) { }
}
When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived. Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters. For example:
int val = 5;
Derived d = new Derived();
d.DoWork(val);  // Calls DoWork(double).
Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int). There are two ways to avoid this. First, avoid declaring new methods with the same name as virtual methods. Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base. Because the method is virtual, the implementation of DoWork(int) on Derived will be called. For example:
((Base)d).DoWork(val);  // Calls DoWork(int) on Derived.

Polymorphism Example

Polymorphism (C# Programming Guide)

Visual Studio 2013
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:
  • At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
  • Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
  1. Create a class hierarchy in which each specific shape class derives from a common base class.
  2. Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such as RectangleCircle, and Triangle. Give the Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List<Shape> object and add a Circle, Triangle and Rectangle to it. To update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time type (the overridden version of the method in each derived class) that will be invoked.
public class Shape
{
    // A few example members 
    public int X { get; private set; }
    public int Y { get; private set; }
    public int Height { get; set; }
    public int Width { get; set; }

    // Virtual method 
    public virtual void Draw()
    {
        Console.WriteLine("Performing base class drawing tasks");
    }
}

class Circle : Shape
{
    public override void Draw()
    {
        // Code to draw a circle...
        Console.WriteLine("Drawing a circle");
        base.Draw();
    }
}
class Rectangle : Shape
{
    public override void Draw()
    {
        // Code to draw a rectangle...
        Console.WriteLine("Drawing a rectangle");
        base.Draw();
    }
}
class Triangle : Shape
{
    public override void Draw()
    {
        // Code to draw a triangle...
        Console.WriteLine("Drawing a triangle");
        base.Draw();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Polymorphism at work #1: a Rectangle, Triangle and Circle 
        // can all be used whereever a Shape is expected. No cast is 
        // required because an implicit conversion exists from a derived  
        // class to its base class.
        System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
        shapes.Add(new Rectangle());
        shapes.Add(new Triangle());
        shapes.Add(new Circle());

        // Polymorphism at work #2: the virtual method Draw is 
        // invoked on each of the derived classes, not the base class. 
        foreach (Shape s in shapes)
        {
            s.Draw();
        }

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

/* Output:
    Drawing a rectangle
    Performing base class drawing tasks
    Drawing a triangle
    Performing base class drawing tasks
    Drawing a circle
    Performing base class drawing tasks
 */

Static Class and Static Member

Static Classes and Static Class Members (C# Programming Guide)

Visual Studio 2013
static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.
double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

// Output:
// 3.14
// -4
// 3
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides. 
NoteNote
To create a non-static class that allows only one instance of itself to be created, see Implementing Singleton in C#.
The following list provides the main features of a static class:
  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization. For more information, see Static Constructors (C# Programming Guide).

Example

Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius:
    public static class TemperatureConverter
    {
        public static double CelsiusToFahrenheit(string temperatureCelsius)
        {
            // Convert argument to double for calculations. 
            double celsius = Double.Parse(temperatureCelsius);

            // Convert Celsius to Fahrenheit. 
            double fahrenheit = (celsius * 9 / 5) + 32;

            return fahrenheit;
        }

        public static double FahrenheitToCelsius(string temperatureFahrenheit)
        {
            // Convert argument to double for calculations. 
            double fahrenheit = Double.Parse(temperatureFahrenheit);

            // Convert Fahrenheit to Celsius. 
            double celsius = (fahrenheit - 32) * 5 / 9;

            return celsius;
        }
    }

    class TestTemperatureConverter
    {
        static void Main()
        {
            Console.WriteLine("Please select the convertor direction");
            Console.WriteLine("1. From Celsius to Fahrenheit.");
            Console.WriteLine("2. From Fahrenheit to Celsius.");
            Console.Write(":");

            string selection = Console.ReadLine();
            double F, C = 0;

            switch (selection)
            {
                case "1":
                    Console.Write("Please enter the Celsius temperature: ");
                    F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                    Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                    break;

                case "2":
                    Console.Write("Please enter the Fahrenheit temperature: ");
                    C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                    Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                    break;

                default:
                    Console.WriteLine("Please select a convertor.");
                    break;
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    /* Example Output:
        Please select the convertor direction
        1. From Celsius to Fahrenheit.
        2. From Fahrenheit to Celsius.
        :2
        Please enter the Fahrenheit temperature: 20
        Temperature in Celsius: -6.67
        Press any key to exit.
     */

Static Members

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
C# does not support static local variables (variables that are declared in method scope).
You declare static class members by using the static keyword before the return type of the member, as shown in the following example:
public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;

    // Other non-static fields and properties...
}
Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member, as shown in the following example:
Automobile.Drive();
int i = Automobile.NumberOfWheels;
If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

How to : Convert ASMX 2 WCF

Convert ASMX web services to WCF


WCF provided much more features and functionality than asmx service out of the box e.g. it implements standards like WS Security, WS Addressing, WS Transaction etc. Performance wise its better than asmx services. See following links for WCF benefits:

http://msdn.microsoft.com/en-us/library/ff648122.aspx

http://msdn.microsoft.com/en-us/library/bb310550.aspx

http://msdn.microsoft.com/en-us/library/aa480190.aspx

For converting an asmx service to WCF we need to take following steps, This approach will choose appropriate serializer depending on the types defined in your asmx service.
  • Create a .wsdl file from current asmx service, you can do this by typing the service url?wsdl in IE and then save the file as .wsdl extension
  • Go to Visual Studio Command Prompt
  • Go to the directory where you saved wsdl file and run svcutil.exe with wsdl file name as argument e.g. svcutil.exe Queue.wsdl
  • The svcutil will generate two files .cs file and .config file. The .cs file will contain your service contract.



  • Create a new WCF Service Application in your solution, This template creates a service1.svc in your project, remove all files associated with Service1
  • Add a new WCF Service by using add item and name it as your own service e.g. Queue
  • Delete the interface file created in above step.
  • Copy your .cs file generated by svcutil to your WCF service application folder and include it in your project. Change the file name to indicate it as an interface e.g. IQueue.cs. You need to change the class name also and its references in the class.
  • In your generated interface file, remove , ReplyAction = “*” string for each operation, see the screen shot:




  • Implement the above interface in your implementation class
  • Build your project, and you should be good to go. 
  • You can now implement your methods by copying your old code to new one or by writing it new.
  • In order test, browse your service in browser or add a service reference to a test project, and it should generate similar interface at your end.

How to: Migrate ASP.NET Web Service Code to the Windows Communication Foundation

How to: Migrate ASP.NET Web Service Code to the Windows Communication Foundation

The following procedure describes how to migrate an ASP.NET Web Service to Windows Communication Foundation (WCF).

Procedure

To migrate ASP.NET Web service code to WCF

  1. Ensure that a comprehensive set of tests exist for the service.
  2. Generate the WSDL for the service and save a copy in the same folder as the service’s .asmx file.
  3. Upgrade the ASP.NET Web service to use .NET 2.0. First deploy the .NET Framework 2.0 to the application in IIS, and then use Visual Studio 2005 to automate the code conversion process, as documented in Step-By-Step Guide to Converting Web Projects from Visual Studio .NET 2002/2003 to Visual Studio 2005. Run the set of tests.
  4. Provide explicit values for the Namespace and Name parameters of the WebService attributes if they are not provided already. Do the same for the MessageNameparameter of the WebMethodAttribute. If explicit values are not already provided for the SOAPAction HTTP headers by which requests are routed to methods, then explicitly specify the default value of the Action parameter with a SoapDocumentMethodAttribute.
    [WebService(Namespace = "http://tempuri.org/", Name = "Adder")]
    public class Adder
    {
         [WebMethod(MessageName = "Add")]
         [SoapDocumentMethod(Action = "http://tempuri.org/Add")]
         public double Add(SumInput input)
         {
              double sum = 0.00;
              foreach (double inputValue in input.Input)
              {
                  sum += inputValue;
              }
          return sum;
         }
    }
    
  5. Test the change.
  6. Move any substantive code in the bodies of the methods of the class to a separate class that the original class is made to use.
    [WebService(Namespace = "http://tempuri.org/", Name = "Adder")]
    public class Adder
    {
         [WebMethod(MessageName = "Add")]
         [SoapDocumentMethod(Action = "http://tempuri.org/Add")]
         public double Add(SumInput input)
         {
              return new ActualAdder().Add(input);
         }
    }
    
    internal class ActualAdder
    {
         internal double Add(SumInput input)
         {
              double sum = 0.00;
              foreach (double inputValue in input.Input)
              {
                  sum += inputValue;
              }
          return sum;
         }
    }
    
  7. Test the change.
  8. Add references to WCF assemblies System.ServiceModel and System.Runtime.Serialization to the ASP.NET Web service project.
  9. Run ServiceModel Metadata Utility Tool (Svcutil.exe) to generate a WCF client class from the WSDL. Add the generated class module to the solution.
  10. The class module generated in the preceding step contains the definition of an interface.
    [System.ServiceModel.ServiceContractAttribute()]
    public interface AdderSoap
    {
         [System.ServiceModel.OperationContractAttribute(
          Action="http://tempuri.org/Add", 
          ReplyAction="http://tempuri.org/Add")]
         AddResponse Add(AddRequest request);
    }
    
    Modify the definition of the ASP.NET Web service class so that the class is defined as implementing that interface, as shown in the following sample code.
    [WebService(Namespace = "http://tempuri.org/", Name = "Adder")]
    public class Adder: AdderSoap
    {
         [WebMethod(MessageName = "Add")]
         [SoapDocumentMethod(Action = "http://tempuri.org/Add")]
         public double Add(SumInput input)
         {
              return new ActualAdder().Add(input);
         }
    
         public AddResponse Add(AddRequest request)
         {
            return new AddResponse(
            new AddResponseBody(
            this.Add(request.Body.input)));
         }
    }
    
  11. Compile the project. There may be some errors due to the code generated in step nine that duplicated some type definitions. Repair those errors, usually by deleting the pre-existing definitions of the types. Test the change.
  12. Remove the ASP.NET-specific attributes, such as the WebServiceWebMethodAttribute and SoapDocumentMethodAttribute.
    public class Adder: AdderSoap
    {
         public double Add(SumInput input)
         {
              return new ActualAdder().Add(input);
         }
    
         public AddResponse Add(AddRequest request)
         {
              return new AddResponse(
             new AddResponseBody(
            this.Add(request.Body.input)));
         }
    }
    
  13. Configure the class, which is now a WCF service type, to require WCF ASP.NET compatibility mode if the ASP.NET Web service relied on any of the following:
    • The HttpContext class.
    • The ASP.NET Profiles.
    • ACLs on .asmx files.
    • IIS authentication options.
    • ASP.NET impersonation options.
    • ASP.NET globalization.
    [System.ServiceModel.AspNetCompatibilityRequirements(
      RequirementsMode=AspNetCompatbilityRequirementsMode.Required)]
    public class Adder: AdderSoap
    
  14. Rename the original .asmx file to .asmx.old.
  15. Create a WCF service file for the service, give it the extension, .asmx, and save it into the application root in IIS.
    <%@Service Class="MyOrganization.Adder" %>
    <%@Assembly Name="MyServiceAssembly" %> 
    
  16. Add a WCF configuration for the service to its Web.config file. Configure the service to use the <basicHttpBinding>, to use the service file with the .asmx extension created in the preceding steps, and to not generate WSDL for itself, but to use the WSDL from step two. Also configure it to use ASP.NET compatibility mode if necessary.
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
     <system.web>
      <compilation>
      <buildProviders>
       <remove extension=".asmx" />
       <add extension=".asmx" 
        type=
        "System.ServiceModel.Activation.ServiceBuildProvider,
        T:System.ServiceModel, Version=2.0.0.0, 
       Culture=neutral, 
       PublicKeyToken=b77a5c561934e089" />
      </buildProviders>
      </compilation>
     </system.web>
     <system.serviceModel>
      <services>
      <service name="MyOrganization.Adder "
        behaviorConfiguration="AdderBehavior">
       <endpoint 
        address="”
        binding="basicHttpBinding"
        contract="AdderSoap "/>
       </service>
      </services>
      <behaviors>
      <behavior name="AdderBehavior">
       <metadataPublishing 
        enableMetadataExchange="true" 
        enableGetWsdl="true" 
        enableHelpPage="true" 
        metadataLocation=
        "http://MyHost.com/AdderService/Service.WSDL"/>
      </behavior>
      </behaviors>
      <serviceHostingEnvironment 
       aspNetCompatibilityEnabled ="true"/>
     </system.serviceModel>
    </configuration>
    
    
  17. Save the configuration.
  18. Compile the project.
  19. Run the set of tests to make sure all the changes work.