Feeds:
Posts
Comments

Posts Tagged ‘.net’


[tweetmeme source=”aabdulmoniem” only_single=false]

Another new feature in C# 4.0 is covariance and contravariance. Really, I will let you in this post with those two nice videos which explains well what is this new feature. This video is made by Eric Lippert divided into two parts. Enjoy!

How Do I: Use Covariance and Contravariance in VS 2010 Part I?

How Do I: Use Covariance and Contravariance in VS 2010 Part II?

I really do like the new feature because it didn’t break the main theme of C# that is strongly typed language.

Also, I like the semantics behind the in and out keywords when used in this new feature.

Finally, I don’t have to cast each element in IEnumerable sequence coming from LINQ to return a sequence of some related class, it will be done for me at compile time out of the box! Great!

Advertisements

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

The VS 2010 debugger has a some great new capabilities like Intellitrace (historical debugging), the new parallel/multithreaded debugging capabilities, and dump debugging support.

For now we will demonstrate some new tiny usability improvements in VS debugger.

1 – Break Points Labels

Suppose that we have a windows application with one form and two buttons on it. We have also two click event handlers and a constructor. Then we added three break points one in the constructor and one in each click handler.

Open the break points window from Debug -> Windows -> Breakpoints. You will see the following:

As we can see, we can’t distinguish these three break points from each other by just looking into the break points window. VS 2010 comes with a new capability “Breakpoints Labels” which allows you to attach label/labels to each break point. See the following steps:

1) Right-click on any breakpoint

1) Right-click on any break point

2) Add label

2) Add label

3) See the new labels attached to the breakpoints

3) See the new labels attached to the break points

Filtering and Searching by labels:

Enable/Disable break points by label:

This gives you an advantage to disable some break points you don’t want to break while debugging which share some common label (behavior, position … etc).

2 – Import / Export break points

This capability allows you to import/export break points to XML files to share them with another team member or to attach them in a bug work item in TFS for example.

3 – Pinned Data Tips

Using this feature, VS 2010 allows you to better track values while you are in debugging session or even you are not.

I will just enter a debugging session, and just hover over any variable I want to track.

You can pin this value for later tracking, also you can add some comments, and for sure you can un-pin it at any time:

We can also Import / Export these data tips as the breakpoint for later share:

One great feature, is that you have the ability to see what is the last value of a specific variable in the last debugging session even if you are not in a debugging session! WOW! Close the debugging session, and look at the screen shot:

That’s it. I think that VS has added some very great capabilities to its powerful debugger. Happy debugging!

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Old versions of VS like 2008 was really painful when trying to navigate from an interface method to its implementation. Now, as we have seen a lot of improvements in navigability in VS 2010, we have been introduced with a very cool new window called: “Call Hierarchy”.

Only you have to right-click on any name you want to trace its call hierarchy and click on “View Call Hierarchy” like the following screen shot:

VS 2010 will handle the rest. It will open a new dockable window for you titled: “Call Hierarchy”

Lets examine some features of this window:

1 – Calls to and Calls from:

As you can see, you can investigate all the called paths from the chosen method or all the called paths to the chosen method.

2 – Call sites

You can click on any call path from the left side of the window to see all the call sites on the right window plus you can navigate to the chosen call site if you want by double clicking on any call site.

3 – Navigate to the call from or call to paths:

You can also navigate to the call path by clicking any code path from the left window.

4 – Filtering call hierarchy:

You can filter the call hierarchy by solution, project and document as shown in the following screen shot:

Now, let’s see more complex scenarios when trying to navigate for virtual or interface methods.

Suppose that we have a class Employee and Manager both are implementing an interface IHuman and inheriting from a class Person. Let’s see these four types:

Person class:

public class Person
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public string FullName
     {
         get
         {
             return Title + " " + FirstName + " " + LastName;
         }
     }

     public Person()
     {
     }

     public Person(string title, string firstName, string lastName)
     {
          Title = title;
          FirstName = firstName;
          LastName = lastName;
     }

     public virtual void PrintInformation()
     {
          Console.WriteLine(FullName);
     }
}

IHuman interface:

public interface IHuman
{
     void Talk(string talking);
     void Eat(string food);
}

Employee class:

public class Employee : Person, IHuman
{
     public string Salary { get; set; }

     #region IHuman Members

      public void Talk(string talking)
      {
           Console.WriteLine("I am saying: " + talking);
      }

      public void Eat(string food)
      {
           Console.WriteLine("I am eating: " + food);
      }

      #endregion

      public override void PrintInformation()
      {
           base.PrintInformation();
           Console.WriteLine(Salary);
      }
}

And Manager class:

public class Manager : Person, IHuman
{
     public string DepartmentName { get; set; }

     #region IHuman Members

     public void Talk(string talking)
     {
          Console.WriteLine("I am saying: " + talking);
     }

     public void Eat(string food)
     {
         Console.WriteLine("I am eating: " + food);
     }

     #endregion

     public override void PrintInformation()
     {
          base.PrintInformation();
          Console.WriteLine(DepartmentName);
     }
}

As you can see that Employee and Manager classes override the PrintInformation method which is a Person virtual method. Also, they implement the two methods Talk and Eat of IHuman interface.

Now let’s play with the call hierarchy feature from the Person class. Right-click on the PrintInformation method in the Person class and choose the “View Call Hierarchy” menu item. See the next screen shot:

As you can see, we can navigate to all the overrides from this window very easily and forgetting about the hassle of Find or Find All References!

Let’s switch to the IHuman interface and see what is the call hierarchy of the Talk method:

Really, pretty neat!

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Update:
Box selection is one of the old features of the VS but it was only supporting you in VS 2008 with deleting or either copying this text.

ScottGu said:

Box selection is a feature that has been in Visual Studio for awhile (although not many people knew about it).  It allows you to select a rectangular region of text within the code editor by holding down the Alt key while selecting the text region with the mouse.  With VS 2008 you could then copy or delete the selected text.

VS 2010 now enables several more capabilities with box selection including:

  • Text Insertion: Typing with box selection now allows you to insert new text into every selected line.
  • Paste/Replace: You can now paste the contents of one box selection into another and have the content flow correctly.
  • Zero-Length Boxes: You can now make a vertical selection zero characters wide to create a multi-line insert point for new or copied text.

All you have to do is to click on ALT key + left mouse button and then drag. What will you see?

As you can see there is light blue box is drawn as long as you drag. This box represents as a boundary to some text in the code file. You can then do whatever you want with this selection either to copy it for example or even delete it.

Let’s see more appropriate example. What if I have some public variables and I want to make them all private.

The old way to make this, is to go line by line and change public to private but if I have 10 lines, or may be 100, or even 1000?! This is really a consuming task.

Here is the box selection comes to the rescue. See the next screen shots:

Step 1: Select the public keywords (ALT + Left Mouse Button + Drag)

Step 2: Type private and see what will happen?

After completion!

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Older versions of VS like 2003 and 2005 were dedicated to only one framework. This was annoying because you have to use multiple versions of VS to develop multi-target applications which wasn’t very feasible at this time!

VS 2008 had come with a great feature called Multi-Target support which enables developers to develop multi-target applications on the same IDE.  So, I can develop a program under .NET 2.0 and using the same VS to develop another one with .NET 3.5 or even convert the old one to .NET 3.5. Great feature, huh!

The problem was that all these versions will run on the same CLR, they are only different in class libraries! So, VS 2008 was primarily focused on filtering the different assemblies and project templates according the developer’s framework choice but everything else was working on the same CLR like compiling and debugging for example.

This wasn’t perfect because the intellisense of VS 2008 always showing the libraries of .NET 3.5 even if you are using .NET 2.0! This makes the chance that developers using .NET 2.0 adding code snippets which is supported only in .NET 3.5 by accident.

VS 2010 comes to the rescue. Now you can develop many programs under many different frameworks safely because the intellisense has been improved to show only what your framework supports.

Enough talking let’s see some screen shots. Just I will create two different web applications targeting different frameworks. The first one will target .NET 2.0:

And the second one will target .NET 4.0:

Now we have two web applications in our Solution Explorer:

Now let’s examine some differences, as we see DotNet2 project is the startup one so we will just run the page and open the integrated server information of VS 2010 to see the following:

But when we mark DotNet4 project as the startup one and run it you will see a different server information:

As you saw the difference is a clean separation between old CLR and new CLR. Good shot!

Let’s see another difference while working with VS Toolbox. We will just open the default page of the DotNet2 web application and open the VS ToolBox data tab to see what the supported controls are in ASP.NET 2.0:

And for the DotNet4 project, we will a different control list:

As we can see that VS 2010 now filters the tool box to show different controls according to the targeted .NET framework. Amazing!

Another one is, the property grid. Let’s see what is the difference. Drag a button on the default page for both projects and let’s see what the property grid will show. In DotNet2 project:

And for DotNet4 project:

As we can see, VS 2010 filters the properties which are supported in each framework correctly. Nice!

Last one, is the Intellisense which we have talked about firstly. Let’s try to write a statement like (Response.Re) in the two projects and let’s see what is the difference. In DotNet2 project:

And in DotNet4 project:

As we can see, VS 2010 filters the methods and properties which are supported in the targeted framework automatically for you to prevent to from accidentally writing something not appropriate.

A very good addition to this new version VS 2010.

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

In old editions of VS to find all the references of a specific variable on the same file for example you have to do that:

Right Click on the variable -> Click on find all references

Then VS will give you all the references he found within the page or not in a new separate window (Results window).

Now, with the new theme of VS 2010 which is “Keep the developer into focus”, you can accomplish that scenario only by putting your mouse cursor on top of the required variable and let VS 2010 do it for you out of the box ;). See the next image:

References Highlighting

FirstName property is highlighted

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

If we look at the theme of C# 3.0 – 3.5, we will see that functional programming has been introduced by exposing LINQ features.

And if we look into the current release theme, we will see that this year’s theme is dynamic keyword.

Dynamic keyword gives you the ability to create objects dynamically at runtime, gives you the ability to call something you already know that it is existing but at runtime not at compile time, and it gives you the ability to interact with dynamic languages such as python for example.

Let’s get started with this new keyword.

Assume that we have the following Person class:

public class Person
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
         get
         {
             return Title + " " + FirstName + " " + LastName;
         }
     }

    public Person()
    {
    }

    public Person(string title, string firstName, string lastName)
    {
         Title = title;
         FirstName = firstName;
         LastName = lastName;
    }

    public void Print()
    {
         Console.WriteLine(FullName);
    }
}

In the Main method of a console application, if I would like to instantiate a new object from the Person class I would do this:

Person person = new Person();
person.Title = "Mr.";
person.FirstName = "Ahmed";
person.LastName = "Abdul Moniem";
Console.WriteLine(person.FullName);

In the last example, the compiler at compile time knows exactly what is Person is and what its type. So, it will generate error if you tried to access a non-existent property or method in the Person class.

Lets add couple of lines to demonstrate the dynamic type:

Person person = new Person();
person.Title = "Mr.";
person.FirstName = "Ahmed";
person.LastName = "Abdul Moniem";
Console.WriteLine(person.FullName);

dynamic dynamicPerson = person;
dynamicPerson.FirstName = "Mohamed";

Console.WriteLine(dynamicPerson.FullName);

As you can see, I have created a new variable called dynamicPerson and its type is dynamic which telling the compiler that it will be validated at runtime. In last example, I have made dynamicPerson to point to person object then I have changed a property on the dynamicPerson and used it to print the full name on the screen.

The same results between this and the normal object initiation process. So, what is the benefit of dynamic keyword?

Let’s add the following using statement on top of our file like that:

using System.Dynamic;

And in our Main method we will write something like that:

dynamic employee = new ExpandoObject();
employee.FirstName = "Ahmed";
employee.LastName = "Abdul Moniem";
employee.FullName = employee.FirstName + " " + employee.LastName;
Console.WriteLine(employee.FullName);

Here is the magic of dynamic keyword, you can create a new object which doesn’t exist at all at runtime. In the last example we have created a new employee of type ExpandoObject (in System.Dynamic) which supports this dynamic behavior in the language.

While I was coding I realized that an employee must have a first name so I wrote:

employee.FirstName = "Ahmed";

And again I realized that the employee must have a last name, so I wrote:

employee.LastName = "Abdul Moniem";

As you may guess, I also realized that I want to add a new property FullName, so I wrote:

employee.FullName = employee.FirstName + " " + employee.LastName;

Then I print the result, and viola! every thing is working exactly as the first example of Person class in this post despite of that I don’t have any employee classes! This is the magic of dynamic keyword.

Let’s add some sugar on my employee object:

employee.Print = new Action(delegate() { Console.WriteLine(employee.FullName); });
employee.Print();

As you can see, I have added a new method which will run at runtime without any mentioned error, also at compile time everything is working fine as long as I am using this dynamic keyword.

You can also, use the famous lambda expression to create your methods. So, the last example can be changed to be:

employee.Print = new Action(() => Console.WriteLine(employee.FullName));
employee.Print();

Until now, I am just demonstrating some of the capabilities of this new keyword but until now I didn’t reveal its power!

Let’s now consider some real cases. What if I have a type which I want to instantiate an object from it at runtime and then call a method on this object still at runtime. This means that I don’t know that type at compile time. This means I have to use reflection, my old friend.

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
object person = Activator.CreateInstance(t, null);

The method CreateInstance will return a type object not a Person type. Which means I can’t do this:

// Compile time error, no method named Print() in object!
person.Print();

So, what I have to do? I should use Invoke method to call the Print method at runtime. The reflection engine at runtime will know that I have a person object that I can call Print on it, and it will call it on behalf of me.

t.InvokeMember("Print", System.Reflection.BindingFlags.InvokeMethod, null, person, null);

And here is the complete code:

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
object person = Activator.CreateInstance(t, null);
t.InvokeMember("Print", System.Reflection.BindingFlags.InvokeMethod, null, person, null);

Using the dynamic keyword, it becomes more easy and cleaner to develop a scenario like this:

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
dynamic person = Activator.CreateInstance(t, null);
person.Print();

Let’s now delve into a more interesting topic, how you can run a dynamic language like python from C#?

First of all, you will need to install IronPython and reference its assemblies into your project.

Now we will write a simple python script into a file called Math.py for example, and it to your project root and it must have Copy Always value of its Copy to Output Directory property:

def Add(x ,y):
    return x + y

Now we will execute this python script:

var py = Python.CreateRuntime();
dynamic test = py.UseFile("Math.py");
dynamic sum = test.Add(5,10);
Console.WriteLine(sum);

And simply you will see the result 15 printed on the screen! Nice, right?!

Finally, I have just highlighted some of the features of this dynamic keyword and how you can use it in many different scenarios. I hope you all to grasp all the benefits of this new keyword.

Read Full Post »

Older Posts »

%d bloggers like this: