Expert C# 5.0 with the .NET 4.5 Framework - book published on 17th December 2012



Expert C# 5.0 with the .NET 4.5 Framework is a book about getting the best from C#. It’s based on the principle that to write good, high-performance, robust applications you need to understand whats going on deep under the hood.

If you are already experienced with writing managed applications and want to learn more about how to get the best from the  language at an advanced level, then this is the book for you.

Table of Contents

  1. Reintroducing C# - A detailed look at the language we all know
  2. C# objects in Memory
  3. Parameters
  4. Methods
  5. Automatic property declarations
  6. Enum
  7. Delegates
  8. Event
  9. ForEach and Iterator
  10. The String data type
  11. Collections explained
  12. LINQ in C#
  13. Exception Management
  14. Async 
  15. Debugging

If you would like to preview please visit here or to buy here.

Codeproject article - C# Linq in Detail

Another article just published in the Code project about the C# Linq in detail.
To read please visit C# Linq in Detail.

This article has been selected in the article of the month competition, please vote me if you like this article. If you would like to vote me, please visit,

http://www.codeproject.com/script/Surveys/VoteForm.aspx?srvid=1300

http://www.codeproject.com/script/Surveys/VoteForm.aspx?srvid=1295

Thank you.

How does it work in C#?

A new article has been published in the Code Project. The article is in here.

Send ASP.NET formatted errors details via Email.

Exception/Error is common scenario in any application. In ASP.NET, there many ways to handle those errors or exception, for example, when an error or exception occurred in ASP.NET application, system is going to send formatted error message to specified developers or team mentioned in the email list. The difference will be the body of email will contain exactly same formatted error ASP.NET generated to display the error or exception details when occurred. For example,



But when an ASP.NET application goes into life, user should not experience to see the above error page where they should see custom error page which easy to understand. More information about is in here.

So in here, this test application will display default error page when there is an error occurred in the system and send an email formatted like above image. 

To do that need to add void Application_Error(object sender, EventArgs e) method into Global.asax.cs file,  the code block is,


    void Application_Error(object sender, EventArgs e)
        {
            HttpUnhandledException httpUnhandledException = new HttpUnhandledException(Server.GetLastError().Message, Server.GetLastError());
            SendEmailWithErrors(httpUnhandledException.GetHtmlErrorMessage());
        }
So GetHtmlErrorMessage() method of HttpUnhandledException class will do all the formatting stuff.
 
The code block to send email is below,
        private static void SendEmailWithErrors(string result)
        {
            try
            {
                MailMessage Message = new MailMessage();
                Message.To = "To address";
                Message.From = "FROM addressd";
                Message.Subject = "Exception raised";
                Message.BodyFormat = MailFormat.Html;
                Message.Body = result;
                SmtpMail.SmtpServer = "SMTP Sever Address";
                SmtpMail.Send(Message);
            }
            catch (System.Web.HttpException ehttp)
            {
                // Write o the event log.
            }
        }
 
To test it there is button on page which manually trigger an exception, the code for button is as below,
 
        protected void btnError_Click(object sender, EventArgs e)
        {            throw new Exception("This Exception is raised to test");
        }
 
 
So now the system will display default error page when an exception occurred and send email with formatted exception details as below,
 
Default Error page,
 

 
And an email with formatted exception details,
 



Codeproject article about extension methods of IEnumerable in C# in

I posted another article about extension methods of IEnumerable in C# in the Codeproject. It could be found in here

Few extension methods of IEnumerable

Following code shows few extension methods of IEnumerable<string>,
public static class EnumberableExtensions
{
         public static IEnumerable<string> IfMatchWith(this IEnumerable<string> myList, string itemToMatch)
        {
            foreach (var item in myList.Where(item => item == itemToMatch))
                yield return item;
        }
 
        public static IEnumerable<string> IfNotMatchWith(this IEnumerable<string> myList, string itemToMatch)
        {
            foreach (var item in myList.Where(item => item != itemToMatch))
                yield return item;
        }
 
        public static IEnumerable<string> IgnoreNullOrEmptyOrSpace(this IEnumerable<string> myList)
        {
            foreach (var item in myList.Where(item => !string.IsNullOrEmpty(item) && item != " "))
                yield return item;
        }
 
        public static IEnumerable<string> MakeAllUpper(this IEnumerable<string> myList)
        {
            foreach (var item in myList)
                yield return item.ToUpper();
        }
 
        public static IEnumerable<string> MakeAllLower(this IEnumerable<string> myList)
        {
            foreach (var item in myList)
                yield return item.ToLower();
        }
 
        public static IEnumerable<T> MakeAllDefault<T>(this IEnumerable<T> myList)
        {
            foreach (var item in myList)
                yield return default(T);
        }
 
        public static IEnumerable<string> IfMatchWithPattern(this IEnumerable<string> myList, string pattern)
        {
            foreach (var item in myList.Where(item => Regex.IsMatch(item, pattern)))
                yield return item;
        }
 
        public static IEnumerable<string> IfLengthEquals(this IEnumerable<string> myList, int itemLength)
        {
            foreach (var item in myList.Where(item => item.Length == itemLength))
                yield return item;
        }
 
        public static IEnumerable<string> IfLengthInRange(this IEnumerable<string> myList, int startOfRange, int endOfRange)
        {
            foreach (var item in myList.Where(item => item.Length >= startOfRange && item.Length <= endOfRange))
                yield return item;
        }
}

Codeproject article about Template method pattern in C#

I posted another article about Template method pattern and Action in C# in the Codeproject. It could be found in here.

Codeplex - .NET Utility Library project

I just published a project in Codeplex. The project name is DotNetUtility - a .NET Utility Library for C#. The project URL is DotNetUtility - a .NET Utility Library for C#. This is open source and if any one willing to contribute please let me know.

Code project - Caching uses with Proxy pattern in C#

I posted another article about improvement of Proxy Pattern by using Caching technique in C#. It could be found in Caching uses with Proxy pattern in C#.

return new Lazy(() => new T()); /* Lazy initialization of objects in C# */

We should try to initialize objects when we need it otherwise the objects will reside in the memory. Probably it won't matter when the object is not that expensive otherwise it really matters. So if we could use something which give us the opportunity to initialize objects only when we need it or probably Singleton pattern or something like this. In .NET 4.0, there is new feature which will do the job for us. That feature is Lazy<T>, following code block will show the use of it,
static Lazy<T> LazyLoader<T>() where T : new()
{
    return new Lazy<T>(() => new T());
}
 
static Lazy<T> LazyLoader<T>(Func<T> lazyInitialisationBlock) where T : new()
{
    return new Lazy<T>(lazyInitialisationBlock);
}
 
static List<string> InitialisationBlock()
{
    return new List<string> { "One", "Two" };
}
Usage of the above code,
static void Main(string[] args)
{
   Lazy<ClassForLazyLoad> loader = LazyLoader<ClassForLazyLoad>();
   Console.WriteLine("{0}", loader.Value.Name);
   Lazy<List<string>> listLoader = LazyLoader<List<string>>(InitialisationBlock);
   Console.WriteLine("{0}", ReferenceEquals(listLoader, null) ? "Loading hasn't been finished yet" : "Loading has been finished");
   Array.ForEach(listLoader.Value.ToArray(), item => Console.WriteLine(item.ToString()));
}
related classes,
public class ClassForLazyLoad
{
   public string Name { get { return GetType().FullName; } }
}

Codeproject articles - Strategy method or Switch statement in C#

I just published another article in the code project. This article is about Strategy method which can be used to replace the switch statement in C#. That article could be found,

Strategy method or Switch statement in C#

A Generic Strategy Pattern implementation using C#

Strategy Pattern - according to this pattern, there will be an interface, few concrete classes which will implement the interface and there will be selection process of the concrete classes. There is good definition in here.

I created a Generic class for Strategy Pattern. Generic Strategy Pattern class will accept the type of Concrete class and types of the parameters and it will take parameter for the argument of the concrete class.

Usage of the StrategyPattern,
 class Program
 {
   static void Main(string[] args)
   {
     int resultOfInt = StrategyPattern.StrategyAddExecutor<int, IntProgrammingCalculatorImp>(1, 2);
     string resultString = StrategyPattern.StrategyAddExecutor<string, StringProgrammingCalculatorImp>("1AA2AA", "2");
   }
 }
The Generic StrategyPattern class will implement the access of different methods defined in the IProgrammingCalculator interface for instance in here Add and Sub methods. In here T denotes the type of parameter of the methods and S denotes the concrete class type.
 public static class StrategyPattern
 {
    public static T StrategyAddExecutor<T, S>(T firstItem, T secondItem)
        where S : IProgrammingCalculator<T>, new()
   {
        return new S().Add(firstItem, secondItem);
   }
 
   public static T StrategySubExecutor<T, S>(T firstItem, T secondItem)
       where S : IProgrammingCalculator<T>, new()
   {
       return new S().Sub(firstItem, secondItem);
   }
 }
IProgrammingCalculator defines the definition of the calculator. There three different types of calculator IntProgrammingCalculator, LongProgrammingCalculator and StringProgrammingCalculator with its own implementation of the methods defined in the IProgrammingCalculator interface. 
 public interface IProgrammingCalculator<T>
 {
     T Add(T firstItem, T secondItem);
     T Sub(T firstItem, T secondItem);
 }
 
 public class IntProgrammingCalculatorImp : IProgrammingCalculator<int>
 {
     public int Add(int firstItem, int secondItem)
     {
         return firstItem + secondItem;
     }
 
     public int Sub(int firstItem, int secondItem)
     {
         return secondItem - firstItem;
     }
 }
 
 public class LongProgrammingCalculatorImp : IProgrammingCalculator<long>
 {
     public long Add(long firstItem, long secondItem)
     {
         return firstItem + secondItem;
     }
 
     public long Sub(long firstItem, long secondItem)
     {
        return secondItem - firstItem;
     }
 }
 
 public class StringProgrammingCalculatorImp : IProgrammingCalculator<string>
 {
     public string Add(string firstItem, string secondItem)
     {
       return firstItem + secondItem;
     }
 
     public string Sub(string firstItem, string secondItem)
     {
       return firstItem.Replace(secondItem, string.Empty);
     }
 }
There are few good articles in the web for further reading,

dofactory.com
Strategy pattern in the wikipedia

Codeplex, few new extension methods in .NET Extensions Methods Library for C# and VB.NET

I have added few extension methods to the project. For instance, in the BooleanExtensions class I added ToBinaryTypeNumber and CombineWith method in the ArrayExtension class.

Source code is in the Change Set 62750 and 62790.

Improvement of Generic Enum Parser and .NET Extensions Methods Library for C# and VB.NET

I updated the previous code about Generic Enum Parser. That code is I include into the .NET Extensions Methods Library for C# and VB.NET project in the Codeplex. The code is below,

public static TEnum ParseStringToEnum<TEnum>(this string dataToMatch, bool ignorecase = default(bool))
       where TEnum : struct
{
       return dataToMatch.IsItemInEnum<TEnum>()() ? default(TEnum) : (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, default(bool));
}
 
public static Func<bool> IsItemInEnum<TEnum>(this string dataToCheck)
        where TEnum : struct
{
        return () => { return string.IsNullOrEmpty(dataToCheck) || !Enum.IsDefined(typeof(TEnum), dataToCheck); };
}
If anyone wants to download it please visit here. The code is part of the StringExtensions class.

Codeproject articles

I just published few articles in the code project. I wrote about enum parsing, few extension methods of string and ternary operator. Those article could be found,

Codeproject article about Page and Web user control communication.

I just finish writing a tips/tricks article about Asp.Net Page and Web user control communication in Code project. That article is about, if we want to execute a method of Asp.Net page from a event handler of Web user control's control. The article could be found at How to execute Asp.Net Page method from control's event handler of a web user control.

thanks mohammad.

Generic Factory pattern - to switch between Mock and Production environment service

Factory pattern - in my previous article, I explain the factory in detail. One thing came up in my mind about generic factory pattern. This is really handy to have in project. For example if we are working in a environment where service could be tested in Mock or Production environment. And also Mock and Production services using common contracts. So this is a good candidate of Generic Factory. In this article, I will include few sample contracts, production and mock implementation of those contracts, a Service Factory and Test class.
public interface IServiceProxyOne { void ProcessRequest(string data);   }
public interface IServiceProxyTwo { void ProcessRequest(string data);    }
 
public class ServiceProxyOne : IServiceProxyOne
{
  public void ProcessRequest(string data) { /* do something.*/}
}
public class ServiceProxyTwo : IServiceProxyTwo
{
  public void ProcessRequest(string data) { /* do something.*/}
}
 
public class MockServiceProxyOne : IServiceProxyOne
{
  public void ProcessRequest(string data) { /* do something.*/}
}
public class MockServiceProxyTwo : IServiceProxyTwo
{
  public void ProcessRequest(string data) { /* do something.*/}
}
Service Factory implementation code is below,
public static class ServiceFactory
{
     public static IServiceProxyOne CreateServiceProxyOne()
     {
       return GetProxyInstance<IServiceProxyOne, MockServiceProxyOne, ServiceProxyOne>();
     }

     public static IServiceProxyTwo CreateServiceProxyTwo()
     {
       return GetProxyInstance<IServiceProxyTwo, MockServiceProxyTwo, ServiceProxyTwo>();
     }
 
     public static T1 GetProxyInstance<T1, T2, T3>()
            where T2 : T1, new()
            where T3 : T1, new()
     {
       return IsMockEnvironment() ? (T1)new T2() : (T1)new T2();
     }
 
     public static bool IsMockEnvironment() { return !default(bool); }
}
To test the code we can use below,
static void Main(string[] args)
{
    ServiceFactory.CreateServiceProxyOne().ProcessRequest("Service Proxy one test.");
    ServiceFactory.CreateServiceProxyTwo().ProcessRequest("Service Proxy two test.");
} 
thanks mohammad.

 Few C# and Application Design books from Amazon,