I decide to create a category of links



I decide to create a category of links, I will post links that I like, or that have a good knowledge, etc. and I will put my comments, criticizing  or the situation information with it to be memorize and retrieval anytime latter and may help others

 

Copy comments from base in Resharper



I used to use a very slickly feature of Resharper which is copy comments from base (class or interface), anyone knows me will know that I am very strict to code guidance and rules using style copy and other code standard tools, we have very restricted rules about documentation, so this really helped me very well but….?!

 

The problem that the action context of this action sometimes didn’t appear, until this moment I didn’t know why? of course I Google everywhere but nothing helpful except that info that Resharper 6.0 doesn’t support the style cop plugin till now, which was very sad news for me anyway, here what I do to fix the problem, of course it fixed at the end but I didn’t know why??

 

  • I disable the Style copy for Resharper plugin
  • I remove the old comments
  • I remove the inheritance and bring it again

And now its working with style copy an without style cop, Just click on the method name and the context action will appear and include the copy comments from base

Copy comments from base without style cop plugin

Copy comments from base without style cop plugin

 

 

Copy comments from base with style cop plugin on

Copy comments from base with style cop plugin on

 

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/

Unobtrusive JavaScript and Ajax in MVC 3



In the previous release of the ASP.NET MVC which is (MVC 2) I didn’t like the Ajax usage, like Ajax action link and Ajax begin form and I make a rule for the previous project for all my team memebers, that it is prohibited to use any of them, Why??

Because they generate inline JavaScript which is the same way as the web form does, this one of the reason that makes me hit the web form approach.

So why I use them isnted of I can makes a clean JQuery code to follow JavaScript Unobtrusive JavaScript which means that we should keep our JavaScript code separated in. js file, as the CSS it must be separated from the html, the JavaScript also must be separated from html

But in MVC 3 I surprised that all Ajax action not generate inline scripts and use JQuery and custom html attributes, we just reference unobtrusive-ajax.js file and of course the JQuery library, which I can consider it (unobtrusive) as a JQuery plugin, so now I really consider using Ajax helper method in  my next proejct

  • See Ajax Begin Form in MVC 2
<form onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event),
{ insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: '#myDiv' });"
onclick="Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));"
method="post" action="/Home/Save">

<input type="text" name="Name">
    <input type="submit" value="Save">

</form>
  • See the Ajax Begin from in MVC 3
<form method="post" id="form0" data-ajax-update="#myDiv" data-ajax-mode="after" data-ajax-method="POST" data-ajax="true" action="/Home/Save">

<input type="text" name="Name">
<input type="submit" value="Save">

</form>

This really show us how Microsoft not only imporove the MVC itself  but also how they try to follow and lead the web community again as before :-)

Thanks Microsoft Keep Improving

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 :-)

Solve the MVC 3 Shortcut conflict with MVC 2 on Visual Studio 2010



When we install MVC 3 on Visual Studio 2010, the shortcut for MVC 3 didn’t work and this because all shortcut are associated with MVC 2, we can solve this issue by many ways,

We can open–>Tool–>Option–>Enviroment–>Keyboard

Start search for the following items, and we will found each one has 2 items, so we will associate shortcut to the item that didn’t has:

  • ProjectandSolutionContextMenus.Project.Add.Controller Ctrl+M, Ctrl+C
  • ProjectandSolutionContextMenus.Project.Add.Area     Ctrl+M, Ctrl+A
  • EditorContextMenus.CodeWindow.AddView     Ctrl+M, Ctrl+V
  • OtherContextMenus.ASPXcontext.GoToController    Ctrl+M, Ctrl+G
  • Project.AddClass     SHIFT+ALT+C

We can also make another solution by removing MVC 2 Tool from Add Remove Program but this will make any existing MVC 2 application not be able to work, if you remove it by mistake you can install this tool again from VS2010 DVD, the tool name is VS2010ToolsMVC2.msi and can be fond  under WCU\ASPNETMVC

Remove MVC 2

Create a shortcut in Visual Studio to add interface video



When I try to find a shortcut to add interface to my project, I didn’t find, this was very weird to me because I thought sure I can’t find it but it’s there, but when I deeply search I find there is not, so I decide to post an article on how to do it?

See the video

The code for the Add interface Module as the following:

Public Module AddInterfaceModule

    Sub AddInterface()
        Dim interfaceName As String = Microsoft.VisualBasic.Interaction.InputBox("Name", "Add Interface")
        If Not interfaceName.ToLower.EndsWith(".cs") Then
            interfaceName &= ".cs"
        End If

        DTE.ItemOperations.AddNewItem("Visual C#\Code\Interface", interfaceName)
    End Sub
End Module</pre>