Wednesday, October 29, 2014

Asynchronous Delegates

As the title the asynchronous delegate refer to invoke a function in async manner. The declaration is same as normal delegate.

        public delegate void mydelegate(string s);


Next thing we need a method to assign it in delegate invocation list. So I create a method named Function and sleep this method for 5 second to give an effect that this method need 5 second to  execute.

    class ABC
    {
        public void Function(string s)
        {
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine(s);
        }
    }


We need a another method which get executed after delegate invoked. This will be our callback method.

        
        static void callback(IAsyncResult result)
        {
            Console.WriteLine("delegate finished");
        }



Final thing we need is to create an instance of this delegate and assign the method to its invocation list and then start the invocation with BeginInvoke method.

        ABC a = new ABC();
        mydelegate del = new mydelegate(a.Function);

        IAsyncResult result = del.BeginInvoke("i am delegate", new AsyncCallback(callback), null);



If you see the BeginInvoke invoke method it has three argument. First one is the parameter need to send to the delegate method. Second is to attached and callback event. And last is the state. Here we leave it null. If your method has more than one parameter then number of parameters in BeginInvoke will increase. BeginInvoke starts the method execution in async manner. And the same time the caller method also runs. So we need some thing in caller method that make it wait for delegate method to finish. EndInvoke resolves this purpose.

        del.EndInvoke(result);

Here is the complete code

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

namespace TestDelegate
{
    class Program
    {
        public delegate void mydelegate(string s);
        static void Main(string[] args)
        {
            Console.WriteLine("-Start program-");
            ABC a = new ABC();
            mydelegate del = new mydelegate(a.Function);
            Console.WriteLine("delegate initilized");
            IAsyncResult result = del.BeginInvoke("I am Delegate",new AsyncCallback(callback), null);
            Console.WriteLine("main running");
            del.EndInvoke(result);
            Console.ReadLine();
        }

        static void callback(IAsyncResult result)
        {
            Console.WriteLine("delegate finished");
        }
    }

    class ABC
    {
        public void Function(string s)
        {
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine(s);
        }
    }
}


Output:
-Start program-    
delegate initilized
main running       
I am Delegate      
delegate finished 

 
Happy Coding ... :)

Monday, October 27, 2014

Anonymous Delegates

Anonymous delegates are the delegate where an anonymous method is embedded to its invocation list. Anonymous method do not have name, they have only code block called body. Three things involved in this process.

1. Delegate declaration

public delegate void mydelegate();


2. Create and object of this delegate and assign the anonymous method in it.

mydelegate del = delegate()
{
       Console.WriteLine("Anonymas delegate");
};


3. Invoke the method by the delegate.

del();


Output :
-start program-        
Anonymous delegate


Complete program is listed below

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

namespace TestDelegate
{
    public delegate void mydelegate();
    class program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("-start program-");
            mydelegate del = delegate()
            {
                Console.WriteLine("Anonymas delegate");
            };
            del();
            Console.ReadKey();
        }
    }
}




Happy coding ... :)

Learn EPiServer - Day 2

Creating a Start Page in EPiServer

Today we will create a page type and template for start page based on EPiServer Content model. And configure this page as start page for the site. 

1. Right click on Models -> Pages and select Add -> New Item -> EPiServer -> Page Type named it as HomePage.cs. And uncomment the code-block. We will discuss the details of code block later in this sequence.





2.Right click on Controller and select Add -> New Item -> EPiServer -> Page Controller(MVC) named it as HomeController.cs



There is a little bit changes in code. You need to add a namespace. And an attribute.

using EPiServerTest.Models.Pages;                                    
[TemplateDescriptor(Path="~/Views/Home/Index.cshtml")]

Here TempleteDescriptor attribute is used to tell controller which view to render using Path. You controller will look like this.



using EPiServer;
using EPiServer.Core;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web.Mvc;
using EPiServerTest.Models.Pages;

namespace EPiServerTest.Controllers
{
    [TemplateDescriptor(Path="~/Views/Home/Index.cshtml")]
    public class HomeController : PageController
    {
        public ActionResult Index(HomePage currentPage)
        {
            /* Implementation of action. You can create your own view model class that you pass to the view or
             * you can pass the page type for simpler templates */

            return View(currentPage);
        }
    }
}    
   




3. Create a folder named Home under Views. Now right click on View -> Home and select Add -> New Item -> EPiServer -> Page Partial View(MVC Razor) and named it as 

Index.cshtml. The all path and name needs to be exactly same as given in TemplateDescriptor Path.



You need to modify the model on view to @model EPiServerTest.Models.Pages.HomePage. Your view will like this.

@using EPiServer.Core
@using EPiServer.Web.Mvc.Html

@model EPiServerTest.Models.Pages.HomePage

<div>
  @Html.PropertyFor(m => m.MainBody)
</div>


5. Build the project and hit F5. Visual Studio will start IIS Express. Now you would be able to login using your windows credential in this url http://localhost:XXXX/episerver where XXXX is the IIS Express port number for this site.

6. Select Pages -> Root and then Add a new page and named as Start.




7. Most important thing you need to create a developer licence for you site. Go to EPiServer Licence Center and create a developer licence and past it in root of your project folder.

8. Now set Start page as site home page. Go to Admin -> Config -> Manage Sites -> Add Site. Fill the relevant information Name, URL and select the start page as Start.



9. You are all done. Now you can browse your site in using the url provided in URL field at step 7. In my case it is http://localhost:2242/



Happy Codding .... :) 

Delegates and Events

Events in C# are implemented with delegate. In Event delegate scenario there are two class involved. Publisher class and subscriber class. Publisher class define a delegate. And subscribing class create a method that matches the signature of the delegate. Then it create an instance of that delegate type and encapsulate the method with it. When the event is raised the subscriber class  method is invoked through that delegate.
 
Lets take a simple example. Create a delegate mydelegate with void return type and a single string parameter.
 
public delegate void mydelegate(string s); 

 
Next step is to create and publisher class. Here we create a class named ABC.
 
    class ABC
    {
        public event mydelegate myevent;
        private string _Message;
        public string Message
        {
            get
            {
                return _Message;
            }
            set
            {
                _Message = value;
                myevent(value);
            }
        }
    }

 
In this class we create an event myevent with mydelegate type. And call this event at the time of setting the property and we are done.
 
Now we need to create subscriber class. In this class create a method for delegate type mydelegate. In this example I have created the EventEvent method. Then the final thing. Create and object of class ABC and encapsulate this method with the event myevent.

        ABC a = new ABC();
        a.myevent += new mydelegate(EventEvent);

        public static void EventEvent(string s)
        {
            Console.WriteLine("New Message inserted : " + s);
        }

Build and run the program. The event will raised with the help of delegate at the time of assigning the value for Message property of class ABC.

Output :
-Start program-
New Message inserted : Welcome to event delegate


The complete program is listed below

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

namespace TestDelegate
{
    public delegate void mydelegate(string s);
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("-Start program-");
            ABC a = new ABC();
            a.myevent += new mydelegate(EventEvent);
            a.Message = "Welcome to event delegate" + Environment.NewLine;
            Console.ReadKey();
        }

        public static void EventEvent(string s)
        {
            Console.WriteLine("New Message inserted : " + s);
        }
    }

    class ABC
    {
        public event mydelegate myevent;
        private string _Message;
        public string Message
        {
            get
            {
                return _Message;
            }
            set
            {
                _Message = value;
                myevent(value);
            }
        }
    }
}


Happy Coding .... :)

Sunday, October 26, 2014

Learn EPiServer - Day 1

Introduction

EPiServer is an web content management system. It is an innovator in digital marketing and e-commerce solutions through .NET CMS and e-commerce platform. EPiServer helps bussiness to create unique customer experiences and identifying customer behaviour which generates bussiness results. 

EPiServer was founded in Sweden in 1994.It is an global company offices in many countries(United States, Sweden, Denmark, Norway, Finland, The Netherlands, South Africa, Australia, Spain, UAE and the United Kingdom) headquarters are located in the heart of Stockholm, Sweden.

I am assuming that you have basic knowledge of CMS and DOT NET framework. First thing I recommended you to create an account in EPiServer World. I found this site very helpful. You can read blogs, post your question on forum and etc.

You can install a EPiServer site from Developer Center. But I recommend you to install it through Visual Studio extension. Download it from here.

Create a EPiServer website using Visual Studio EPiServer Template

Creating an EPiServer website using Visual Studio EPiServer template is very easy. Visual Studio EPiServer template give choice to create a empty site contains only files need to run EPiServer run time and a sample site with sample data and pages. Here I will demonastrate you to create a site from scratch using empty template in MVC.

1. Go to "File -> New -> Project -> EPiServer -> EPiServer Web Site" and give name as EPiServerTest then click OK.





















2. Select template Empty and tick on MVC then press OK. This will create and EPiServer project for you.























Solution will looks like this.








































3. Build the project and hit F5. Visual Studio will start IIS Express. Now you would be able to login using your windows credential in this url http://localhost:XXXXX/episerver where XXXXX is the IIS Express port number for this site
.
























Next day we will learn how to create your first EPiServer page.

Happy Coding ... 


Friday, October 24, 2014

Unblock outlook's blocked attachments

Sometime outlook blocks attachments due to security reasons.  I found a way out may be this could help.

Step 1

Take a backup of your Registry. You will need this backup if any thing went wrong.

Step 2

Close Outlook.

Step 3

Open Registry Editor. 

Step 4

Go to HKEY_CURRENT_USER->Software->Microsoft->Office->14.0->Outlook->Security
(Here 14.0 is the version of outlook if you are using lower version then it might be 12.0 or vice versa)

Step 5

Then Edit -> New -> String Value.  And name the value "Level1Remove"





 
 
 
 
 
 
 
 
 
 
 
 
Step 6
 
Double click on Level1Remove and enter the extension including the "dot" that we want to open in Outlook and press ok. eg. (.exe, if multiples then separated by semi colon .exe;.asp;.aspx;.js;).


 







 
Close the registry editor and you are done. :)

Wednesday, October 15, 2014

Multicast Delegates

Multicast Delegates is an useful property of delegate object is to assign multiple objects into a single delegate object. The + operator is used to combine delegates. Same types of delegated can be combined. The multicast delegate contains a list of delegate which is called invocation list. When a multicast delegate is called it invoke delegates from the list in order.






















    public class Example_MulticastDelegate
    {
        public delegate void mydel(string s);

        static void Main(string[] args)
        {
            mydel del = new mydel(Method1);
            del += new mydel(Method2);
            del("Multicast Delegate");
            Console.ReadLine();
        }

        public static void Method1(string s)
        {
            Console.WriteLine("Hello " + s + " I am Method 1.");
        }
        public static void Method2(string s)
        {
            Console.WriteLine("Hello " + s + " I am Method 2.");
        }
    }
In the above program we have two methods, Method1 and Method2. And our objective is to call both methods with a single delegate.

Very first we declare a delegate mydel with void return type and a string parameter.

public delegate void mydel(string s);

Now we need to create an object of delegate mydel and assign Method1 and Method2 into its invocation list.

mydel del = new mydel(Method1);
del += new mydel(Method2);

Finally we need to call our method with the delegate mydel.

del("Multicast Delegate");

Output : 
Hello Multicast Delegate I am Method 1.
Hello Multicast Delegate I am Method 2.


Happy Coding....

Tuesday, October 14, 2014

Single Repository Principle

SRP

Single Repository Principle which is also known as Single Repository Pattern or in short SRP says a class should have one and only one reason to change.

Wikipedia says In object-oriented programming, the single responsibility principle states that every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.
To explain this further let’s assume we have a class to export dataset into excel and pdf.

    public class ExportDataGrid
    {
        public DataSet ds { get; set; }
        
        public void ExportToPDF()
        {
            // code for export to pdf
        }

        public void ExportToExcel()
        {
            // code for export to excel
        }
    }



The class ExportDataSet has two methods, ExportToPDF and ExportToExcel. Now think we want to add a new functionality in ExportToPDF method. We will change this method . And if we need to change something in ExportToExcel method then also ExportDataSet class got modified. So it has two reason to change the class. Here SRP come into picture. For removing this dependency we just split this class.

    public interface IExportDataGrid
    {
        void Export();
    }

    public class ExportToPDF: IExportDataGrid
    {

        public void Export()
        {
            // code for export to pdf
        }
    }
    public class ExportToExcel : IExportDataGrid
    {

        public void Export()
        {
            // code for export to excel
        }
    }



This is what SRP is all about. Happy Codding...