Re-throwing Exception, Custom exception


This is a very straightforward post that I just want to highlight some important notes about exception

Re-throwing Exception?

We re-throw exception in many cases for example:

  • For logging

We catch and re-throw the original exception

  • For security purpose

Because we don’t want to reveal info to all users, because it may be used to hack the system, so we just logged the original exception and re-throw general exception “The process can’t be done in this time“, so the user that has admin privilege will be able to go to the event log or the place that we used for logging with confidence it’s an admin user.

  • For using business exception

Sometimes we want to use some custom exceptions to reflect the alternative scenarios for our business workflow, for example:

      • InvalidPasswordException
      • InsufficientFundException
      • Etc.

When we re-throw exception in case of logging we use throw without the object because if we use throw ex, this will chance the Stack Trace to say that the exception originated in that place where it’s not.


try
{

}
 catch (Exception)

{

throw;

}

 

When we create our custom exception, it’s better to make it Serializable and to do that fast it’s better to use Exception snippet

ExceptionSnippet

 


using System.Runtime.Serialization;

[Serializable]
 public class MyException : Exception
 {
 public MyException()
 {
 }

public MyException(string message)
 : base(message)
 {
 }

public MyException(string message, Exception inner)
 : base(message, inner)
 {
 }

protected MyException(
 SerializationInfo info, StreamingContext context)
 : base(info, context)
 {
 }
 }

How to effectively debug Expression Tree?



First this is a very small tip and the reason for creating it because it took me time to reach where I can click the button to display the visualizer of the Expression tree?

  • First we have to be in the debug mode
  • Second open add-watch window for the expression

Add Watch

  • Third click on the a magnifying glass that appears, that’s it

Expression

  • Variable names are displayed with a “$” symbol at the beginning.
  • Assigned an automatically generated names for parameters, such as $var1 or $var2.
  • Assigned an automatically generated name for lambda expression, such as #Lambda1 or #Lambda2.

Good links for more more info

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

http://marlongrech.wordpress.com/2008/01/08/working-with-expression-trees-part-1/

DevMagicFake Published on NuGet



Now you can install DevMagicFake from NuGet server

DevMagicFake on NuGet

DevMagicFake on NuGet

To install the package you just open tool-> Library Package Manager->Package Manager Console as the following:

Open Package Console

Open Package Console

Now in the NuGet Package Manager console write the following

PM>Install-Package DevMagicFake -Project MyMVCProject

This will install DevMagicFake Library and add reference to it in your MVC project, this also will add the configuration file needed in the web.config

You can install it by another way, right click on the project you want to install the library to, choose Manage NuGet Packages, the NuGet Management window will appear, just search for DevMagicFake and install it

Open NuGet Package Manager

Open NuGet Package Manager

Install DevMagicFake from NuGet

Install DevMagicFake from NuGet

Extension Methods for IEnumerable of T and Custom Collection



Custom Collection one of the best design pattern I have ever used. It encapsulates items or array of items inside a seperate class which will allow us to  full control these items, but for modern development, it’s rarely to see custom collection in any post or code snippet everywhere, when I deeply search why the community didn’t follow this pattern, I found the community not only follow this pattern, no it’s recommended to not doing it, Microsoft .NET Framework Design Guide

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

http://stackoverflow.com/questions/1544800/custom-collection-vs-generic-collection-for-public-methods

So what is the main reason for that?

The answer is Extension Method, Microsoft extend all the Old collection like (Any Array, List<T>, Queue<T>, Stack<T>, Dictionary<T,T> etc.) with all extension methods exist in the System.LINQ, so no need to create custom collection, we just need to use IEnumerable<T> or IList<T> and then extend them at any time in my project with new extension methods, but be careful this will not break the access of the members, in other words the extension method will not be able to access the private member like in the custom collection does, but in most cases this will be good enough

  • Extension Method for IEnumerable<T>

We can create extension methods that apply to an interface, which allow us to call this method for each class that implement this interface, for example

If we add extension method called CalculateSalary for IEnumerable<Employee> as the following:

public static decimal CalculateSalary(this IEnumerable<Employee> empList)
{
           decimal totalSalary = 0m;
           foreach (var employee in empList)
            {
              totalSalary += employee.Salary;
            }
           return totalSalary;
        }

So now I can create list of Employee and I will find the method exist in this list as the following:

static void Main(string[] args)
{
      IEnumerable<Employee> emplloyees = new List<Employee>
       {
          new Employee { Id = 1, Salary = 49m },
          new Employee { Id = 2, Salary = 33m },
          new Employee { Id = 4, Salary = 66m }
       };

      Console.WriteLine(emplloyees.CalculateSalary());

      Console.ReadLine();
}

Extension Method rules

  • It must be static and exist in any static class
  • It will extend the first parameter which is prefix with this
  • It will pass current instance of the extended class at the run time
  • If you extend an Interface that’s meaning you extend any class implement that interface

Lambda Expression, Func and Action delegates



Finally I decide to post this topic, every time I said it’s not needed because it’s very simple topic, but I always take time to remember all it’s details specially when i get busy with TFS workflow, build automation, deployment automation and all other process automation stuff, when I get back to C# code I take time to remember these small things, so I decide to post it to be remembered quickly

  • Func<>

I will start by talking about Func<> so what is it?

Built-in delegates that take none or one or many parameters and return one result, as we can see we have 16 overloading start from the first one that didn’t take any parameters and return one result and ending with the final one that take 15 parameters and return one result too

Func Delegates

Func Delegates

Remember that always the last parameter is the return parameter

Why these delegates exist? because .NET Framework use them in LINQ and Extension method so Microsoft makes them public so that we as developers can use them instead of creating new delegates with the same signature

  •   Action<>

The same as Func but it doesn’t return value (void)

Action Delegates

Action Delegates

  • Lambda Expression

So let’s see the following example:

public static int MyMethod (Func<int,int> del)
 {
     return del(4);
 }

So we can see that this method takes a parameter as delegate, that’s mean we will pass a method as a parameter with the same signature of the delegate

So we can make method that take one int and return int as the signature of the Func (parameter) as the following method

public static int MethodParameter(int x)
{
   return  x += 5;
}

And then we will path it to our method (MyMethod)

MyMethod(MethodParameter))

But why we create method that we will not use it anymore??? And here the anonymous method will take place, so instead of creating method and pass it to MyMethod we will pass anonymous method with the same signature

So how to write anonymous method with the same signature? it’s very simple, we just write the method and remove the first part until the parameter and write delegate instead of the first part as the following:

Anonymous Method

Anonymous Method

 So it will become as the following: 
delegate(int x) { return x += 5; })

So now we can pass the anonymous method to MyMethod as the following:

MyMethod (delegate(int x) { return x += 5; }));

So now we will convert the anonymous method to lambda expression and pass it to MyMethod but first how we can convert anonymous method to lambda expression? It’s very simple

(delegate(int x) { return x += 5; }  // anonymous method

(x)=> { return x += 5; } // remove delegate and int

x=> { return x += 5; } // remove Parentheses because one variable

x=>  x += 5 // remove return and curly brackets it's one statement like if

So now instead of pass anonymous method to MyMethod we will pass the lambda expression of the anonymous method as the following:

MyMethod (x=> x += 5));

We don’t need to express the logic of our delegate in the lambda expression. We can as easily call a method, like this:

prod => EvaluateProduct(prod)

If we need a lambda expression for a delegate that has multiple parameters, we must wrap the parameters in parentheses, like this:

(prod, count) => prod.Price > 20 && count > 0

And finally, if we need logic in the lambda expression that requires more than one statement, we can do so by using braces ({}) and finishing with a return statement, like this:

(prod, count) => {

//...multiple code statements

return result;
// notice here because multiple parameters we have  Parentheses
// and also because we have many statements we have curly brackets

}


I hope it helps :-)

Yield return, what does it mean?



Yield return, it’s a very strong keyword, all the LINQ to object use it when we use foreach or yield return.

It is used to iterate through a collection returned by a method. you can create methods that return a collection and don’t have to go through declare and maintain it’s state the compiler will do it for you, what does it means?

To understand the different lets see code that doesn’t use yield and code does

Without yield

class Program
 {
   static void Main(string[] args)
   {
     foreach (int i in GetInt())
     {
       Console.WriteLine(i.ToString());
       Console.Read();
     }
   }

   public static IEnumerable<int> GetInt()
   {
      List<int> nums = new List<int>();
      for (int i = 0; i < 5; i++)
      {
         nums.Add(i);
      }
      return nums;
   }
 }

With yield


class Program
 {

   static void Main(string[] args)
   {
      foreach (int i in GetInt())
      {
        Console.WriteLine(i.ToString());
        Console.Read();
      }
   }

 public static IEnumerable<int> GetInt()
 {
   for (int i = 0; i < 5; i++)
   {
     yield return i;
   }
   yield return 20;
   yield return 30;
 }

You can see here the different that you don’t need to declare a variable to hold the return collection from your method you just need to yield return the variable and if you make a break point and execute each method you will notice how this method has different execution path, because without yield the foreach of the GetInt has to be finished first and then populate the collection variable but in other case it will return after each iteration, so it will return what you real need as you need it, so it will continue in the second method where it stop.

In other word it will get iterate to bring the first number and then the caller will return to the first method “Main” and then when the method inside the Main call the second method it will go to iterate and bring the second number and return and so on.

LINQ basics


  1. Obtain the data sources(s)
  2. Create the query
    1. Declare variable var query = the following
    2. From variable Name in obtained data Source //Declaration
    3. Where variable name. Property == or > or < or any operator against any value // criteria and filtering
    4. Orderby variable name. Property, variable name. Property //sorting
    5. Select (variable name or variable name * 10 (any expression) or new { property1= val1 , property2 = val2 } (anonymous type) // projection
  3. Execute the query
    1. ToList() //by calling
    2. ToArraay() //by calling
    3. Foreach and access the query result

Example


 var files = new DirectoryInfo(@"c:\\").GetFiles(); //Obtain the data sources(s)
 var query = from file in files //Create the query //Declaration
 where file.Length > 0 // criteria and filtering
 orderby file.Name, file.Length  //sorting
 select new // projection
 {
 Name = file.Name,
 Length = file.Length,
 CreatedDate = file.CreationTime
 };
 var my = query.ToList(); //Execute the query

 //or

 foreach (var myFileInfo in query) //another Execute of the query
 {
 Console.WriteLine(myFileInfo.Name);

 }