Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, December 15, 2015

About Windows Azure (Cloud Computing)

Cloud computing is the delivery of computing as a service rather than a product. It is completely based on the Internet. Cloud Computing provides on-demand hardware (like Server), storage resources, services hosting and services management environment, and other devices as a utility or resource over a network, rather than having your local servers or personal devices to handle manage your services and applications.


Cloud


A Cloud is just a combination of hardware (computer, other devices), networks, storage, services, and interfaces that helps in delivering computing as a service. It has mainly three users - end user, business management user, and cloud service provider.
The end user uses the services provided by the cloud. The business management user takes care of the data and the services provided by the cloud. The cloud service provider is responsible for the maintenance of the IT assets of the cloud.


Cloud Service


A cloud service allows you to build cloud applications without installing it on the computer. It reduces the maintenance and support of the application as compared to the applications which are not developed by using the cloud service. The different kinds of users can use the application from the cloud service.


Windows Azure


Windows Azure is an open and flexible cloud platform that serves as the development, data storing, service hosting and service management environment. Windows Azure provides developers with on-demand compute and storage to host, scale, and manage web applications on the internet through Microsoft datacenters.


Advantage of Windows Azure

There are following advantages of Windows Azure-
  1. Reduce the effort and costs of IT management.
  2. Reduce costs of building and extending on-premises resources.
  3. Respond quickly to changes in your business and customer needs.
  4. Choose an on-premises or off-premises deployment model that best suits your needs.
  5. Scale your IT resources up and down based on your needs.
  6. Consume computing resources ONLY when the needs arise.
  7. Remove the need to manage hardware.
  8. Use your existing development skills to build cloud applications.
  9. Consistent development and management experience across on-premises and the cloud.

Thursday, October 29, 2015

ASP.net MVC Model Binder

Model Binders is a powerful extension point to the ASP.NET MVC. It allows you to define your own class which is responsible for creating parameters for your controller actions. Scott Hansleman had a good example showing how to decouple a controller from HttpContext's user property.

Recently I've started a new Proof of Concept site which is based upon REST. My goal was to build a single web site which would expose its resources as addressable items. That is the URL defines the resource. This site should also be able to serve multiple clients which want different representations of the same resource.

For example assume we have an Automobile Parts catalog. We might have the browser point to http://myPartsCatalog.com/Ford/OilFilters/ which would render an HTML page of all the ford oil filters. Now let us say we want to implement an AJAX callback on the page so as a user mouse overs a specific part, the site might send a request to http://myPartsCatalog.com/Ford/OilFilters/fl1a, with the intention of gathering additional data about the part to display to the user. For this request we don't want to get an HTML representation of the part, we want the part rendered as JSON or XML, which will let us programatically access the part information.

I have grown tired of having to support multiple sites / pages one that renders the HTML and another that provides an API and exposes the data. The natural seperation of concerns that the MVC model gives us makes this an ideal platform to build a single web site which can serve HTML, XML, JSON or any other content we could imagine (for example what about a PDF version of the HTML page for offline usages).

To do this imagine we have the following controller defined:


public class PartController : Controller
{
public ActionResult List(string oem)
{
}
public ActionResult Detail(string oem, string partnumber)
{
}
}


We need a way to determine how the client wants the data to be returned. We could put that in the URL; however, that doesn't feel very restful. A key idea of a REST implementation is leveraging the capabilities in the HTTP protocol to define the resource your requesting. One of the Http Header's is Accept.

The Accept header allows us to define the content type that the client is requesting. So we could indicate in our request that we want text/json or text/xml. We could then put the following code in our controller:



        public ActionResult List(string oem)
        {
            //Get the Model for OEM.
            switch (HttpContext.Request.AcceptTypes[0])
            {
                case "*/*":
                case "text/html":
                    return View("PartList.aspx");
                case "text/json":
                    return View("PartList.json.aspx");
            }
        }


Warning: I am not finished investgating how ASP.Net handles the Accept header and my switch statement might not work; however, this is an example to highlight the flexibility of ASP.Net MVC.

So this works great; except that we want to unit test our code to ensure we are returning the right view for each request; however our controller is bound HttpContext which can be difficult to unit test. So the question is how do we decouple our controller from HttpContext? IModelBinder's are the answer.

We can define a ModelBinder by implementing the IModelBinder interface. The interface requires a single method that takes a couple parameters which provide context about the request, and returns an object.



    public class ContentTypeModelBinder : IModelBinder
    {

        #region IModelBinder Members

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            return controllerContext.HttpContext.Request.AcceptTypes[0];
        }

        #endregion
    }



The return value from the function will be used to pass in to a parameter in a controller. This allows us to change our controller definition to:

        public ActionResult List(string oem, [ModelBinder(typeof(ContentTypeModelBinder))]string contentType)
        {
            //Get the Model for OEM.
            switch (contentType)
            {
                case "*/*":
                case "text/html":
                    return View("PartList.aspx");
                case "text/json":
                    return View("PartList.json.aspx");
            }
        }


The magic here is the ModelBinder attribute which is applied to the contentType parameter. This tells the ASP.Net MVC runtime to use our own custom IModelBinder to provide the value for the contentType attribute. 



The thing I don't like about this is that we have to use an attribtue in our controller. It is possible to indicate that all instances of a specific type use a specific binder. But I will leave that for a different article.

Enjoy..!!

Tuesday, October 6, 2015

Asynchronously Vedio streaming using ASP.NET Web API

A lot of people think that ASP.NET Web API is basically a fancy framework for building APIs – which couldn’t be further from the truth. Web API is mainly about the new .NET HTTP programming model it brings to the table – embracing HTTP to perform a whole magnitude of web related tasks; and APIs are just a small portion of that. Hopefully if you follow this blog, you have seen examples of that already, as we often wander in the unkown areas of ASP.NET Web API, beyond building “traditional” APIs.

Today, let’s go back to the HTTP programming model and use Web API to asynchronously stream videos.

More after the jump.

The concept of asynchronous streaming

To perform the async streaming task, we will revert to the class we already previously used on this blog – and that is PushStreamContent. It allows the developer to progressively push packets of data down to the receiving client. Previously, we used PushStreamContent and JavaScript’s Server Sent Events to create an HTML5 chat.

In our new scenario, we will read the video stream from the file on the server’s hard drive, and flush it down to the client (using PushStreamContent) in the packets of 65 536 bytes. The streaming video playback could then start immediately (client doesn’t have to wait for the entire video to be flushed down), without causing unnecessary load on our server, especially as the process of writing to the client happens asynchronously. Once the client disconnects, the writing stops.

Implementation

PushStreamContent takes an Action in its constructor:


public PushStreamContent(Action<Stream, HttpContent, TransportContext> onStreamAvailable);

This Action is called as soon as the output stream (HTTP content to be flushed to the client) becomes available.

Therefore, we could create a small helper class, which would read the from the disk, and expose this activity for PushStreamContent to call repeatedly.

public class VideoStream
{
   private readonly string _filename;

   public VideoStream(string filename, string ext)
   {
      _filename = @"C:UsersFilipDownloads" + filename + "."+ext;
   }

   public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
   {
      try
      {
      var buffer = new byte[65536];

      using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
      {
         var length = (int)video.Length;
         var bytesRead = 1;

         while (length > 0 && bytesRead > 0)
         {
            bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
            await outputStream.WriteAsync(buffer, 0, bytesRead);
            length -= bytesRead;
         }
      }
      }
      catch (HttpException ex)
      {
         return;
      }
      finally
      {
         outputStream.Close();
      }
   }
}

This class is obviously little simplified, for the sake of demo purposes, but hopefully you get the idea. We allow the consumer of the class to give as information about the file (for which we arbitrarily look in a specific location, the Downloads folder in this case). In the WriteToStream method, we proceed to read the file progressively and flush these bits to the output stream.

Notice that the signature of this method matches the Action expected by PushStreamContent and as a result can be used by it.

Now let’s move to the controller action, which, by now, will be very simple (all the heavy lifting happens in the above VideoStream class).


public class VideosController : ApiController
{
   public HttpResponseMessage Get(string filename, string ext)
   {
      var video = new VideoStream(filename, ext);

      var response = Request.CreateResponse();
      response.Content = new PushStreamContent(video.WriteToStream, new MediaTypeHeaderValue("video/"+ext));

      return response;
   }
}

We allow the client to pass video info (name, extension), construct the instance of VideoStream and then create and instance of PushStreamContent which gets returned to the client.

All we need now is just a route registration:

config.Routes.MapHttpRoute(
    name: "DefaultVideo",
    routeTemplate: "api/{controller}/{ext}/{filename}"
);

Consuming the asynchronous video stream

In this case, I will be requesting this video: C:UsersFilipDownloadsCkY96QuiteBitterBeings.webm.

If we run this in the browser that supports WebM, we could see that the video (especially if you open the network inspection console) is streamed rather than loaded at once. To better illustrate this, I have recorded a short video which shows the application in action. I’ve put a breakpoint inside WriteToStream method, to show that subsequent packets of video get sent down *after* the playback has already started; the client can commence the playback already after the first 64kB packet. Also, as soon as the breakpoint hits, nothing more gets sent to the client, yet the browser still continues the playback of what it has already received. 

Summary
While there are arguably many better solution for video streaming (media protocols, media servers and so on), in my opinion, this type of functionality is a pretty nifty example of how flexible Web API can be in terms of working with HTTP programming – and how many different things it can do.

On a side, PushStreamContent itself is a very interesting class, and if used correctly, can be a very powerful weapon in the arsenal of Web API developer. A very interesting article about a similar topic (async with PushStreamContent) can be found here, by Andrés Vettor. Really worth a read!

Thursday, August 13, 2015

LINQ First() vs FirstOrDefault() and Single() vs SingleOrDefault()

LINQ provides element operators which return a single element or a specific element from a collection. The elements operators are Single, SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault.

Single

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection.

SingleOrDefault

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if more than one match found for that element in the collection. A default value is returned, if no match is found for that element in the collection.
List<int> data = new List<int> { 10, 20, 30, 40, 50 };

//Try to get element at specified position
Console.WriteLine(data.ElementAt(1)); //result:20 

//Try to get element at specified position if exist, else returns default value
Console.WriteLine(data.ElementAtOrDefault(10)); //result:0, since default value is 0 

Console.WriteLine(data.First()); //result:10 
Console.WriteLine(data.Last()); //result:50

//try to get first element from matching elements collection
Console.WriteLine(data.First(d => d <= 20)); //result:10 

//try to get first element from matching elements collection else returns default value
Console.WriteLine(data.SingleOrDefault(d => d >= 100)); //result:0, since default value is 0 

//Try to get single element 
// data.Single(); //Exception:Sequence contains more than one element 

//Try to get single element if exist otherwise returns default value
// data.SingleOrDefault(); //Exception:Sequence contains more than one element 

//try to get single element 10 if exist
Console.WriteLine(data.Single(d => d == 10)); //result:10 

//try to get single element 100 if exist otherwise returns default value
Console.WriteLine(data.SingleOrDefault(d => d == 100)); //result:0, since default value is 0

First

- It returns first specific element from a collection of elements if one or more than one match found for that element. An exception is thrown, if no match is found for that element in the collection.

FirstOrDefault

  • It returns first specific element from a collection of elements if one or more than one match found for that element. A default value is returned, if no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault ?

  • You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:
  • When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  • When you want a default value is returned if the result set contains no record, use SingleOrDefault.
  • When you always want one record no matter what the result set contains, use First or FirstOrDefault.
  • When you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

  • FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.

Friday, July 24, 2015

Microsoft IE8 browser support ending in 17 months

Microsoft is ending support for Internet Explorer 8, announcing it would give users 17 months to stop using the version, which is the most popular version so far.

The post from Microsoft includes a list of operating systems and browser version combinations that would continue getting support, with Internet Explorer 8 not making the cut.

"After Jan. 12, 2016, only the most recent version of Internet Explorer available for a supported operating system will receive technical support and security updates," said Roger Capriotti, director of Internet Explorer, in the full blog post. "For example, customers using Internet Explorer 8, Internet Explorer 9, or Internet Explorer 10 on Windows 7 SP1 should migrate to Internet Explorer 11 to continue receiving security updates and technical support."

Microsoft



The news is especially big for businesses, many of which have not upgraded their systems to Windows 7 or 8 because it means that they would also have to upgrade Internet Explorer.

The post says Microsoft would only be supporting IE9 on Windows Vista, IE10 on Windows Server 2012 and IE11 on Windows 7 and Windows 8.1.

While the browsers will stop getting updates and technical support from Microsoft, they will continue to work on the systems they're installed on.

"Running a modern browser is more important than ever for the fastest, most secure experience on the latest Web sites and services," Capriotti continued in his blog post.

The news takes Microsoft in a different direction from its previous support policy, in which it promised to continue supporting a version of IE as long as an operating system was able to run it.

Under the old policy, IE7 was to continue getting support until 2017, which is when Windows Vista support was to end. IE8 would have continued to get support until 2020, when Windows 7 was to retire. IE10 was supposed to continue getting support until 2023, the end date for Windows 8.

Microsoft has essentially taken off a year of support for IE7, four years for IE8 and IE9 and seven years for IE10.

This news is especially surprising considering the user base and the rate of growth of IE8. The browser is being used by 37 percent of Internet Explorer users, which is a lot more than IE11's 29 percent. Not only that, but in the last month alone IE8 use has grown four times that of IE11.

While at first glance it may seem like Microsoft is losing its mind, the company suggests users will have a better web experience with new versions of Internet Explorer. Not only that, but the move will obviously also help cut Microsoft's support costs. 

LikeFollowShare(167)Tweet(47)Reddit9 Comments

Tuesday, March 31, 2015

How to get file size before upload using jquery

Fille uploading functionality is generally used by the developers. Before uploading file on the server, to know the size of file is a good practice. By knowing file size, we can restrict the end user to upload large size files on the server since we have limited space on the server. We should check uploaded file size on server side as well client side. In this article I am going to expose how you can get size of file before uploading on client side using JQuery. 

Example to get file size before upload using JQuery


 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Get File Size</title> 
 <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript" > </script>
 <script type="text/javascript">
 function GetFileSize(fileid) {
 try {
 var fileSize = 0;
 //for IE
 if ($.browser.msie) {
 //before making an object of ActiveXObject, 
 //please make sure ActiveX is enabled in your IE browser
 var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
 var objFile = objFSO.getFile(filePath);
 var fileSize = objFile.size; //size in kb
 fileSize = fileSize / 1048576; //size in mb 
 }
 //for FF, Safari, Opeara and Others
 else {
 fileSize = $("#" + fileid)[0].files[0].size //size in kb
 fileSize = fileSize / 1048576; //size in mb 
 }
 alert("Uploaded File Size is" + fileSize + "MB");
 }
 catch (e) {
 alert("Error is :" + e);
 }
}
 </script>
</head>
<body>
<form name="upload" action="">
<input type="file" name="fUpload" id="fUpload" />
<input type="button" value="Get File Size" onclick="GetFileSize('fUpload');" />
</form>
</body>
</html> 

Tuesday, March 3, 2015

Outlook Integration in .Net

First You have to add Microsoft.Office.Interop.Outlook using References.To do that go to Solution Explorer->Reference->Add Reference->.NET tab->Microsoft.Office.Interop.Outlook.

After that we will create a small class called SendEmails and we will implement a method called sendGroupmail.

Here the Implementation for SendEmails Class.

public class SendEmails
{
public int sendGroupMail(string recipientsList, string subject, string body)
{
Outlook.Application objectOutLook = new Outlook.Application();

try
{
Outlook.MailItem mailItem = objectOutLook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mailItem.Subject = subject;
mailItem.To = recipientsList;
mailItem.Body = body;
Outlook.NameSpace ns = objectOutLook.GetNamespace("mapi");
ns.Logon(Missing.Value, Missing.Value, true, true);
mailItem.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook.MailItem)mailItem).Send();
ns.Logoff();
return 1; 
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
return 0;
}

}
}

How to use this class.........

SendEmails newemail=new SendEmails();
int result = newemail.sendGroupMail("example@mail.com", "This is Subject", "This is Body");

Thursday, February 5, 2015

ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>    

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"

<Window x:Class="MyWPFSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click"
                Height="23"
                HorizontalAlignment="Left"
                Margin="77,45,0,0"
                Name="btnClick"
                VerticalAlignment="Top"
                Width="203"
                Command="{Binding ButtonCommand}"
                CommandParameter="Hai" />
    </Grid>
</Window>


ViewModel: ViewModel has namespace MyWPFSample, class as MainWindowViewModel and property as ButtonCommand. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace MyWPFSample
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));
        }
        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}

When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

RelayCommand Class

In this example RelayCommand class is used for implementing ICommad object. I think it's a simple and standard approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace MyWPFSample
{
    class RelayCommand : ICommand
    {
        private Action<object> _action;
        public RelayCommand(Action<object> action)
        {
            _action = action;
        }
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _action(parameter);
            }
            else
            {
                _action("Hello World");
            }
        }
        #endregion
    }
}

ICommand and RelayCommand keep track whether or not commands are available. If commands are not available, then all controls associated with that command are disabled. For example using command controls like button can be disabled if CanExecute() returns false. The Code that executes when command is invoked and is located in Execute event. handler. 

Tuesday, February 3, 2015

ref and out in c#.net

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword


public class Example
{
 public static void Main() //calling method
 {
 int val1 = 0; //must be initialized 
 int val2; //optional
 Example1(ref val1);
 Console.WriteLine(val1); // val1=1
 Example2(out val2);
 Console.WriteLine(val2); // val2=2
 }
 static void Example1(ref int value) //called method
 {
 value = 1;
 }
 static void Example2(out int value) //called method
 {
 value = 2; //must be initialized 
 }
}

Ref and out in method overloading


Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time. Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
 public void Method(out int a) // compiler error “cannot define overloaded”
 {
 // method that differ only on ref and out"
 }
 public void Method(ref int a) 
 {
 // method that differ only on ref and out" 
 }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
 public void Method(int a) 
 {
 }
 public void Method(out int a)
 {
 // method differ in signature.
 }
}

Monday, February 2, 2015

Action and Func Delegates in C# .NET

The Func and Action generic delegates were introduced in the .NET Framework version 3.5.

Whenever we want to use delegates in our examples or applications, typically we use the following procedure:

  1. Define a custom delegate that matches the format of the method.
  2. Create an instance of a delegate and point it to a method.
  3. Invoke the method.
  4. But, using these 2 Generics delegates we can simply eliminate the above procedure.
  5. Since both the delegates are generic, you will need to specify the underlaying types of each parameters as well while pointing it to a function.

 For example Action<type,type,type……>

Action<>


  • The Generic Action<> delegate is defined in the System namespace of microlib.dll
  • This Action<> generic delegate, points to a method that takes up to 16 Parameters and returns void.


Func<>


  • The generic Func<> delegate is used when we want to point to a method that returns a value.
  • This delegate can point to a method that takes up to 16 Parameters and returns a value.
  • Always remember that the final parameter of Func<> is always the return value of the method. (For examle Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and returns a string value.)

Let's look at an example to see the use of both Delegates.

Create a new project named “FuncAndActionDelegates” and create a new class that holds all your methods.

MethodCollections.cs

class MethodCollections  
    {  
  
        //Methods that takes parameters but returns nothing:  
   
        public static void PrintText()  
        {  
            Console.WriteLine("Text Printed with the help of Action");  
        }  
        public static void PrintNumbers(int start, int target)  
        {  
            for (int i = start; i <= target; i++)  
            {  
                Console.Write(" {0}",i);  
            }  
            Console.WriteLine();  
        }  
        public static void Print(string message)  
        {  
            Console.WriteLine(message);  
        }  
  
        //Methods that takes parameters and returns a value:  
  
        public static int Addition(int a, int b)  
        {  
            return a + b;  
        }  
  
        public static string DisplayAddition(int a, int b)  
        {  
            return string.Format("Addition of {0} and {1} is {2}",a,b,a+b);  
        }  
  
        public static string SHowCompleteName(string firstName, string lastName)  
        {  
            return string.Format("Your Name is {0} {1}",firstName,lastName);  
        }  
        public static int ShowNumber()  
        {  
            Random r = new Random();  
            return r.Next();  
        }  
    }  


Program.cs

class Program  
    {  
        static void Main(string[] args)  
        {  
            Action printText = new Action(MethodCollections.PrintText);  
            Action<string> print = new Action<string>(MethodCollections.Print);  
            Action<int, int> printNumber = new Action<int, int>(MethodCollections.PrintNumbers);  
  
            Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition);  
            Func<int, int, string> add2 = new Func<int, int, string>(MethodCollections.DisplayAddition);  
            Func<string, string, string> completeName = new Func<string, string, string>(MethodCollections.SHowCompleteName);  
            Func<int> random = new Func<int>(MethodCollections.ShowNumber);  
  
            Console.WriteLine("\n***************** Action<> Delegate Methods ***************\n");  
            printText();    //Parameter: 0 , Returns: nothing  
            print("Abhishek");  //Parameter: 1 , Returns: nothing  
            printNumber(5, 20); //Parameter: 2 , Returns: nothing  
            Console.WriteLine();  
            Console.WriteLine("**************** Func<> Delegate Methods *****************\n");  
            int addition = add1(2, 5);  //Parameter: 2 , Returns: int  
            string addition2 = add2(5, 8);  //Parameter: 2 , Returns: string  
            string name = completeName("Abhishek", "Yadav");    //Parameter:2 , Returns: string  
            int randomNumbers = random();   ////Parameter: 0 , Returns: int  
  
            Console.WriteLine("Addition: {0}",addition);  
            Console.WriteLine(addition2);  
            Console.WriteLine(name);  
            Console.WriteLine("Random Number is: {0}",randomNumbers);  
  
            Console.ReadLine();  
        }  

    }  

Output :

Friday, January 30, 2015

S.O.L.I.D Architecture principle in C# (Part 5)

Continue to Thursday, January 29, 2015
------------------------------------------------------

Dependency Inversion Principle (DIP)


Dependency Inversion Principle or DIP states that:

High-level modules should not depend on low-level modules. Both should depend on abstractions. 
Abstractions should not depend on details. Details should depend on abstractions.

Consider that you are developing an application that deals with user management (creating a user, managing their passwords, etc.). After every user management task you wish to send a notification to the user as well as to the administrator about the activity performed. The following code shows a simplified implementation of this system.

public class EmailNotifier
{
    public void Notify(string email, string message)
    {
        //send email here
    }
}

public class UserManager
{
    EmailNotifier notifier = new EmailNotifier();

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        notifier.Notify(email, "User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        notifier.Notify(email, "Password changed successfully");
    }
}
The EmailNotifier class has just one method - Notify() that accepts an email address and a notification message. Inside, it sends an email to the specified address notifying the user of the change. The UserManager class declares an instance of EmailNotifier class and uses it in methods such as CreateUser() and ChangePassword(). So far so good. Now assume that instead of email notification you want to send SMS based notifications. To cater to this change you not only need to write another class (say SMSNotifier) but also need to change UserManager class because UserManager uses EmailNotifier. This problem arises due to the fact that high level module UserManager depends on a concrete low level module EmailNotifier.

Let's change our classes to follow DIP.

public abstract class NotifierBase
{
    public abstract void Notify(string message);
}

public class EmailNotifier:NotifierBase
{
    public string EmailAddress { get; set; }
    public override void Notify(string message)
    {
        //send email here
    }
}

public class SMSNotifier : NotifierBase
{
    public string MobileNumber { get; set; }
    public override void Notify(string message)
    {
        //send SMS here
    }
}

public class UserManager
{
    public NotifierBase Notifier { get; set; } 

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        Notifier.Notify("User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        Notifier.Notify("Password changed successfully");
    }
}
Now, the code defines an abstract class NotifierBase that defines the Notify() method. The two classes EmailNotifier and SMSNotifier inherit from the NotifierBase class and provide the necessary implementation details. More importantly the UserManager class no longer uses a specific concrete implementation. It uses a NotifierBase abstraction in the form of the Notifier public property. This public property can be set by the consumer of the UserManager class either to an instance of EmailNotifier class or to an instance of SMSNotifier class or any other class that inherits from NotifierBase class. Thus our code now depends on abstractions and not on the concrete implementation.

Summary

SOLID principles of object oriented programming allow you to write structured and neat code that is easy to extend and maintain. SOLID principles include Single Responsibility Principle (SRP), Open/Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP) and Dependency Inversion Principle (DIP).