Tuesday, 5 May 2015

When to choose handler (ASHX) in ASP.NET

Every .NET developer has hear about Handler but do you know the main purpose of handlers why do we need to use them ? Why do we not replace them with normal ASPX form ?

In simple one line answer i would like to say ASPX pages are good to use when you have some controls on pages ( dynamic HTML controls ) but suppose if there is a requirement of  display dynamic images , views then it would be critical for web pages. In that scenario we use handlers for critical web pages.

There are two most important thing about Handlers that is :

First and foremost, HttpHandlers are far more reusable/portable than pages. Since there’s no visual element to an HttpHandler , they can easily be placed into their own assembly and reused from project to project or even sold as is. Secondly, the Page handler is relatively expensive. Going with the “Hello World” examples, if you do that in a page you’ll end up raising a number of events (onInit, onLoad, onPreRender, onUnload, …) and make use of a number of ASP.NET features such as viewstate and postback. In most cases, the performance hit is negligible, but it nonetheless highlights that you’re using the page framework when you have no need to.


Why not to use HttpHandlers

The biggest and very significant drawback of HttpHandlers is that they can only be used for extensions that are mapped to ASP.NET in IIS. It might be great to create a file download counter for your .zip files using an HttpHandler, but since IIS doesn’t go through ASP.NET to serve .zip files, it isn’t going to work. One solution is to map those extra extension to ASP.NET, but that might have undesirable side effects and might not even be possible for you (many developers don’t have direct access to IIS). In this case, the only solution is to create an ISAPI filter which is much more difficult. IIS 7 promises to let us write ISAPI filters in .NET (or extend HttpHandlers beyond the ASP.NET pipeline depending on how you look at it), but that’s still a ways away.

Monday, 12 January 2015

Get unread emails from Outlook on Web page

After completing my work on sending email web service. I thought if i want to read emails from my outlook then is there any way to display that on a normal HTML page ?

After re-searching about outlook and .net pipe, i have found a way to do that.
For displaying outlook emails on webpage. you have to write macro code on outlook. For this you need to open outlook and press ALT+F11 and write below code :

Sub MyRule(Item As Outlook.MailItem)

Dim strURL As String
Dim oApp As Object
Set oApp = CreateObject("InternetExplorer.Application")
strURL = "http://localhost:51049/Default2.aspx"  //Enter your path
oApp.navigate (strURL)
oApp.Visible = True

End Sub


Save the above code and open your visual studio and add webform :
Add below Javascript in your webform :

<script>
        function PopulateEmails() {
            var objOutlook = new ActiveXObject("Outlook.Application");
            var session = objOutlook.Session;
 
            for (var folderCount = 1; folderCount <= session.Folders.Count; folderCount++) {
                var folder = session.Folders.Item(folderCount);
                if (folder.Name.indexOf("Main folder Name") >= 0) {
                    for (var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++) {
                        var sampleFolder = folder.Folders.Item(subFolCount);
                        if (sampleFolder.Name.indexOf("Folder Name to display unread message") >= 0) {
                            for (var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++) {
                                var itm = sampleFolder.Items.Item(itmCount);
                                if (!itm.UnRead)
                                    continue;
                                var sentBy = itm.SenderName;
                                var sentDate = itm.SentOn;
                                var receivedBy = itm.ReceivedByName;
                                var receivedDate = itm.ReceivedTime;
                                var subject = itm.ConversationTopic;
                                var contents = itm.Body;
 
                                var tbl = document.getElementById('tblContents');
                                if (tbl) {
                                    var tr = tbl.insertRow(tbl.rows.length);
 
                                    if (tbl.rows.length % 2 != 0)
                                        tr.className = "alt";
 
                                    var tdsentBy = tr.insertCell(0);
                                    var tdsentDate = tr.insertCell(1);
                                    var tdreceivedBy = tr.insertCell(2);
                                    var tdreceivedDate = tr.insertCell(3);
                                    var tdsubject = tr.insertCell(4);
                                    var tdcontents = tr.insertCell(5);
 
                                    tdsentBy.innerHTML = sentBy;
                                    tdsentDate.innerHTML = sentDate;
                                    tdreceivedBy.innerHTML = receivedBy;
                                    tdreceivedDate.innerHTML = receivedDate;
                                    tdsubject.innerHTML = subject;
                                    tdcontents.innerHTML = contents;
                                }
                                itm.UnRead = false;
                            }
                            break;
                        }
                    }
                    break;
                }
            }
            return;
        }
 
    </script>


Add below code in body of web form :


<div id="divResult">
           <input type="button" value="Read" onclick="PopulateEmails();" /><br />
           <table cellpadding="3" cellspacing="3" border="1" id="tblContents">
               <tr>
                   <th>Sent By</th>
                   <th>Sent on</th>
                   <th>Recived By</th>
                   <th>Recived on</th>
                   <th>Subject</th>
                   <th>Content</th>
               </tr>
           </table>
       </div>

Now run web form in IE.
If you get an error related to ActiveXObject creation error then follow below steps :

 1) Go To Settings->Internet Options->Security Tabs.
  2)  You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites.
  3)  Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button.
  4) Opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.

enter image description here

enter image description here









Sunday, 11 January 2015

Interface in C#

Interface is one of the more overloaded and confusing concepts in object oriented programming. This article can help to understand Interfaces for those who have just started programming.

Interface in C#?

Let’s start with the short definitions for Interface:
  • An Interface is a way to achieve runtime polymorphism in C#.
  • An Interface is a collection of properties and methods declarations.
  • An Interface is a type declaration like a class or structure in C#; an Interface itself does not implement members.
  • Interfaces are contract templates in which the contract members are declared.

Characteristics of an Interface

Interfaces cannot be initialized directly as they do not have a definition for members, they should be implemented by either a class or structure.
Interfaces can contain any of the following type members or a combination of these four member types.
  1. Property
  2. Method
  3. Event
  4. Indexer
An Interface can be declared as either public or internal inside a namespace and can’t have any other access modifiers. An Interface can have any access modifier when declared inside a class or structure.
Members of an Interface are public by default and can’t have other access modifiers.
A class implementing an Interface must implement all the members declared in the Interface and they must be marked as public in the Implicit implementation. In the case of Explicit implementation, the Interface members can't have any access modifiers and they are private by default. If the implementing class is signed as abstractthen the members of the Interface can also be signed as abstract in the class.

Why should we use Interfaces in C#?

Let’s start with a real world scenario to understand the Interface implementation.
Consider an application with a logging module to log application errors; the application should be able to address a customer specific error logging method. On the customer's side, Client A may expect the application to write logs to the file system, Client B may expect to log errors in the database, and Client C may go for the Windows Event log.
To address the above scenario, the application design should support swapping of the logging system with less or no developer effort, and this leads to writing a plug-n-play like module for the application.
We can address this scenario with a flexible and extensible software design using Interfaces. The rest of the article will deal with developing the system with notes on handling Interfaces in C#.

How to implement an Interface

Interface declaration

An Interface needs to be declared before it can be implemented in any class. An Interface can be declared inside a namespace or a class with the keyword interface followed by the Interface name.
Example
namespace LoggingModule.Contract
{
    public interface ILogger
    {
        /// <summary>
        /// Write log information to logging source.
        /// </summary>
        void WriteLog(String Message);
    }
}
In the above code, we have declared an Interface called ILogger with a single method WriteLog inside the namespace LoggingModule.Contract. As the name implies, the WriteLog method will have code for writing log information to the configured logging source.

Interface implementation

A class can implement an Interface by suffixing a colon followed by the Interface name. A class can implement multiple interfaces by separating the Interface names with a comma.
Example
namespace FileSystemLoggingModule
{
    public class FileSystemLogger : ILogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> File system Logger is invoked!");
        }
    }
}
The above code shows the implementation of a single Interface ILogger in the FileSystemLogger class. TheWriteLog method is defined with the same input parameters and return type (void) as declared in ILogger.
In the same way we can create a class for database logging and Windows EventLog logging as shown below. All these three classes have implemented the contract ILogger which is demanding the implementation of theWriteLog method.
namespace DatabaseLoggingModule
{
    public class DatabaseLogger: ILogger
    {
        public void WriteLog(String Message)
        {
            Console.WriteLine(Message + " ==> Database Logger is invoked!");
        }
    }
}

namespace WindowsEventLoggingModule
{
    public class WindowsEventLogger: ILogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Windows event logger is invoked!");
        }
    }
}
Now, let’s see how to use this interface in an application. We have declared an Enum (LoggingType) to expose the available logging types.
The ApplicationLogger class has a LogError method which will check the logging type configuration and load the appropriate logger implementation.
public enum LoggingType
{
    FileSystem = 1,
    Database = 2,
    WindowsEventLog = 3
}
Code for loading logger based on logging type
namespace LearningInterface
{
    public class ApplicationLogger
    {
       public void LogError(String strMessage)
        {
            LoggingType ConfiguredLoggingType = (LoggingType) 
              Convert.ToInt32(ConfigurationManager.AppSettings["LoggingType"]);

            ILogger Logger;

            switch (ConfiguredLoggingType)
            {
                case LoggingType.FileSystem:
                    Logger = new FileSystemLogger();
                    break;
                case LoggingType.Database:
                    Logger = new DatabaseLogger();
                    break;
                case LoggingType.WindowsEventLog:
                    Logger = new WindowsEventLogger();
                    break;
                default:
                    Logger = null;
                    break;
            }

            if (Logger != null)
            {
                Logger.WriteLog(strMessage);
            }

        }
    }
}
The LogError method reads the logging type value in the app settings from web.config. The ILogger object is initialized based on the logging type set in app settings. By initializing ILogger based on configuration settings, we can easily switch the logging type of the application. If we need to change the logging type in future, we don’t need to edit or recompile the application; changing LoggingType key in web.config will switch the application logging process. A new logging type can be added to the application easily in the same way we did for the database, Windows Event loggers.
There are better ways to achieve plug-n-play like software design with Interfaces and IoC. I have chosen the above approach to make it simpler to understand for beginners in C#.

Types of Interface implementation

An Interface implementation can be either Implicit or Explicit. In this article, we have used implicit Interface implementation.

Explicit implementation allows developers to tag the implementation details explicitly to the Interface. Explicitly implemented members are prefixed with the Interface name as shown below.
namespace LearningInterface
{
    public class ExplicitImplementation: ILogger, IErrorLogger
    {
        void ILogger.WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Explicit implementaion of ILogger.WriteLog() invoked.");
        }

        void IErrorLogger.WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Explicit implementaion of IErrorLogger.WriteLog() invoked.");
        }
    }
}
You will notice that, there are two implementations of the WriteLog method with the prefix of the respective Interface names. Explicit implementation helps identify the members more accurately and avoid shadowing/collision of members in multiple Interface implementations.
You can explicitly implement an Interface in Visual Studio as shown below:
Let’s see a scenario where we need to implement an Interface explicitly.
We know that C# does support multiple Interface implementations in a class. Our application has two interfaces:ILogger and IErrorLogger, for different purposes, and have a method called WriteLog() with identical signature declared in those two interfaces. Now we have to implement those two Interfaces in a class.
First, we shall implement these Interfaces implicitly and see the problem with it.
Interfaces can be implemented implicitly in visual studio as shown in below.
Clicking on “Implement interface ‘ILogger’ will generate a skeleton of ILogger members as shown below and can build successfully.
Let’s modify WriteLog() to test it.
namespace LearningInterface
{
    public class ImplicitImplementation: ILogger, IErrorLogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Implicit implementaion of WriteLog() invoked.");
        }
    }
}
The above code shows the implicit implementation of ILogger and IErrorLogger in theImplicitImplementation class. This code will build with no errors as the WriteLog() implementation is compromising both ILogger and IErrorLogger. Doing this way will spoil the purpose of interfaces as we have defined the same behavior for both Interfaces. So, we need to have an option to identify or name Interface members explicitly.
Let’s invoke WriteLog() from ILogger and IErrorLog objects and analyze the output.
Console.WriteLine("Implicit implementaion of an Interface in C#" + Environment.NewLine);

ImplicitImplementation objImplicit = new ImplicitImplementation();

//Create ILogger object
objLogger = (ILogger)objImplicit;

//Create IErrorLogger object
objErrorLogger = (IErrorLogger)objImplicit;

objLogger.WriteLog("Invoking from ILogger");

objErrorLogger.WriteLog("Invoking from IErrorLogger");

Console.ReadLine();
In the above code, we have created an object of the ImplicitImplementaion class and created ILogger andIErrorLogger objects from it. ILogger and IErrorLogger objects are invoking the WriteLog() method.
Output
When you run the code, you will get an output as shown above. Both Interfaces are invoking the same method.
This is not the expected behavior, ILogger and IErrorLogger must implement the WriteLog method differently and we should be able to invoke a specific implementation of the WriteLog method.
Let’s see how we can achieve it with an explicit implementation of ILogger and IErrorLogger.
Console.WriteLine("Explicit implementaion of an Interface in C#" + Environment.NewLine);

ExplicitImplementation objExplicit = new ExplicitImplementation();

//Create ILogger object
objLogger = (ILogger)objExplicit;

//Create IErrorLogger object
objErrorLogger = (IErrorLogger)objExplicit;

objLogger.WriteLog("Invoking from ILogger");

objErrorLogger.WriteLog("Invoking from IErrorLogger");

Console.ReadLine();
We have implemented the WriteLog method for both interfaces with the prefix of the respective Interface names in the ExplicitImplementaion class. An object for the ExplicitImplemenatation class is created and type casted to generate ILogger and IErrorLogger objects.
So, when we invoke Logger.WriteLog()void ILogger.WriteLog(int ErrorCode, string Message)of ExplicitImplementaion should be invoked. In same way, IErrorLogger.WriteLog(int ErrorCode, string Message) should be invoked when ErrorLogger.WriteLog is executed.
Output
As you can see in the output, we are able to identify and invoke specific implementations of WriteLog() forILogger and IErrorLogger.

Difference between explicit and implicit implementations

Implicit implementation
  1. Members are public by default.
  2. Members must be marked as public.
  3. Members can be invoked directly through the object of the implementing class.
  4. Example:
    FileSystemLogger objFileSystemLogger = new FileSystemLogger();
    objFileSystemLogger.WriteLog("");
Explicit implementation
  1. Members are private by default.
  2. Members can't have any access modifiers.
  3. Members can't be accessed directly, an object of the implementing class should be cast to the Interface type to access the members.
  4. Example:
    FileSystemLogger objFileSystemLogger = new FileSystemLogger();
    ILogger objLogger = (ILogger)objFileSystemLogger;
    objLogger.WriteLog("");

Points to consider while designing Interfaces

  1. An Interface should focus on common and related tasks that a module expects. Inclusion of unrelated methods will ruin the purpose of the Interface.
  2. An Interface should not include any method which is specific to a class; if there are specific methods declared in the Interface, it will become hard to implement the same Interface for other classes.
  3. An Interface should not declare too many methods. Too many methods make the implementation of Interfaces harder as the implementing class needs to implement all methods declared by the Interface.
  4. An Interface should be declared when there is need for abstraction by design. Too many abstractions may lead to increased complexity in maintenance and reusability of code.