Tuesday, September 16, 2014

Today delivered a Hands-on labs kind of a session titled “Universal Apps for Windows Devices” for Internal Software Development Team at Central Bank Sri Lanka.

Targeted duration for the session was 3 hours, but had to limit the session to 1.5 hours due to unavoidable circumstance. I have managed to cover the topics such as Introduction to Windows Runtime Apps, Apps life cycle etc. Since all the participants are newbies to Windows Runtime Apps, wrote a very simple Windows 8.1 Application. Session concluded with a hope to continue the missed part of the session with another session in the near future. So let’s see how it goes.

Thursday, September 11, 2014

In this wiki let’s see how we can write a custom collection initializer. Before going straight to the topic let’s refresh our brains on Object Initializers and Collection Initializers.

Object Initializers

Let’s say you have the following class named “Employee”.

publicclass Employee

{

publicint Id { get; set; }

publicstring Name { get; set; }

}

“Employee” class has two properties “Id” and “Name”. So this is how we can initialize a object of type “Employee” and set the values for it’s properties in the classical way.

Employee employee = new Employee();

employee.Id = 1;

employee.Name = "Jaliya Udagedara";

So notice here that there are three lines of code, and the more you have properties, the more lines of code you have to write just for setting up values for properties. Now let’s have a look at how we can do the same using the
Object Initializer of the class Employee.

Employee employee = new Employee()

{

Id = 1,

Name = "Jaliya Udagedara"

};

Even though there seems to be many lines of codes here, technically it’s just a one line. Note that even you can remove the parenthesis next to Employee and right the object initializer in the following way. It will still work.

Employee employee = new Employee

{

Id = 1,

Name = "Jaliya Udagedara"

};

Collection Initializers

Collection initializers works in the same way as Object Initializers and it lets you add one or more elements when you initialize a collection class that implements
IEnumerable. The collection class must be implementing
IEnumerable, otherwise you won’t be able to use collection initializer, please take a note of that. You will later understand why the collection has to be implementing
IEnumerable.

Now let’s see how we used to add items to a collection in the classical way.

List<Employee> employees = new List<Employee>();

employees.Add(new Employee() { Id = 1, Name = "Jaliya Udagedara" });

Here I have first created an List of type Employee and added a new Employee. And to add new Employee I have used it’s object initializer. Now let’s see how we can use the collection initializer to do the same.

List<Employee> employees = new List<Employee>()

{

new Employee()

{

Id = 1,

Name = "Jaliya Udagedara"

}

};

So what happens here is by using a collection initializer you don't have to specify multiple calls to the
Add method. Behind the scene when the source is compiling the compiler calls the
Add method of the respective collection. So for that compiler needs the collection class to be implemented
IEnumerable and to have an public method named Add. So here the List<T> is implementing IEnumerable.

So now let’s see how we can define a custom collection class (same is
List<T>) which can be initialized using the collection initializer.

I am modifying the previous “Employee” class by adding a public constructor which takes two values in and set values to it’s properties.

publicclass Employee

{

publicint Id { get; set; }

publicstring Name { get; set; }

public Employee(int id, string name)

{

Id = id;

Name = name;

}

}

Now I have the following Custom collection class named “EmployeeCollection” and it’s implementing
IEnumerable of type Employee. Here I am adding a public method named "Add" which takes
two parameters so as the constructor of the Employee.

publicclass EmployeeCollection : IEnumerable<Employee>

{

privatereadonly List<Employee> employees;

public EmployeeCollection()

{

employees = new List<Employee>();

}

publicvoid Add(int id, string name)

{

employees.Add(new Employee(id, name));

}

public IEnumerator<Employee> GetEnumerator()

{

return employees.GetEnumerator();

}

IEnumerator IEnumerable.GetEnumerator()

{

return GetEnumerator();

}

}

Now let’s see my custom “EmployeeCollection” in action. By calling public Add method I can still add Employees.

EmployeeCollection employees = new EmployeeCollection();

employees.Add(1, "Jaliya Udagedara");

And this is how we can use the collection initializer on my custom “EmployeeCollection”.

Monday, September 8, 2014

Imagine your web application is having some issues and you have configured the application to show custom error messages instead of real exceptions. So one way of knowing what’s happening is, to change the web.config to throw real exceptions instead of custom error messages. And I am sure, your site viewers definitely not going to like it. So is there any other way, that we can use to see what has happened apart from using some logging? There is.

IntelliTrace can be quite useful in such cases and in this post let’s see how we can use IntelliTrace to collect information of an ASP.NET application running on IIS. So without much information let’s dive in to see this in action.

I have created a MVC application and I am having that application running on my local IIS. Currently it is working perfectly well. I can login and navigate around.

ASP.NET Application Running on IIS

Now to introduce a bug, I am going to change one of the columns which is related to login functionality. So in the applications’ database, I am going to change the column “UserName” to “User_Name” in the AspNetUsers table.

Changing Table Columns to Produce a Bug

Now I am trying to login to the site back.

Error

As expected, I am getting an error. The error message is not so informative and If I don’t know a column in the database is changed, I definitely am in trouble, figuring what went wrong here. Now let’s see how I can use IntelliTrace to find out what has happened.

First you need to download and extract IntelliTrace Collector which you can download from here. This exe is being updated every 3 months by Microsoft and it is recommended to use the latest every time. I am creating a folder named “ITraceCollector” in my C: drive and I am placing the downloaded executable there. Next what I need to do is run the executable.

IntelliTraceCollector

You need to agree on the license terms and conditions and browse for an folder to extract the content (here, after the extraction the only file I will be getting is IntelliTraceCollection.cab file). Here I am giving my extraction destination as,

One thing to note is, if you have Visual Studio installed, based on your version of Visual Studio you can find the already extracted content in above mentioned folder (if you are using Visual Studio 2012, the path would be “C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\IntelliTrace\11.0.0”). When the Visual Studio is installing, it will place a IntelliTraceCollection.cab file there, but it is not the latest. So again the recommendation is to use the latest. Since I don’t want the latest IntelliTraceCollection.cab to be in a separate folder, I am just giving the original path as my extraction path.

Once the extraction is done, copy and paste the new IntelliTraceCollection.cab file to “ITraceCollector” folder which I have created before. Next I need to open up the command prompt as Administrator and run the following command to extract the content of IntelliTraceCollection.cab file.

Above what I have done is, I am changing the current directory to “c:\ITraceCollector” and I am issuing a expand command. First parameter (IntelliTraceCollection.cab) is the cab file to be expanded, second parameter (F:*) specifies all files in the cab file should be expanded. Third and the final parameter (c:\ITraceCollector) is the destination.

Once the command got completed, I can see a whole bunch of folders and files created in “C:\ITraceCollector” folder. The next thing I am interested is the default collection plan for ASP.NET applications which can be found in the “c:\ITraceCollector” folder. I need to create full collection plan and I am going modify the existing default collection plan and save as a new plan. For that download and install the “IntelliTrace Collection Plan Configurator v1” from here. Once installed, open up the “IntelliTrace Collection Plan Configurator v1”.

Go to File –> Open.

IntelliTrace Collection Plan Configurator

Select the “collection_plan.ASP.NET.default.xml”

Opening Default ASP.NET Collection Plan

Once the selected collection plan is opened, go to “IntelliTrace Events” tab and select all. This will cause the collection process we are planning to run to collect all the information of all the IntelliTrace events.

Selecting All IntelliTrace Events

Once that is done, let’s go ahead with saving the file and I am giving a new name as “collection_plan_full.xml”.

collection_plan_full.xml

Now the next thing be done is initiate the IntelliTrace collection process. For that let’s open up the PowerShell as Administrator.

First I am importing the PowerShell module for IntelliTrace. You can find it “C:\ITraceCollector” folder.

Now let’s check what are the available IntelliTrace commands by running Get-Help command.

Get IntelliTrace Help

There I have a command named “Start-IntelliTraceCollection”. I am issuing that command.

Starting IntelliTrace Collection

It is asking for name of Application Pool. I am getting the Application Pool by going to IIS, right clicking on my application and Manage Application –> Advanced Settings.

Application Properties

Getting Application Pool Name

I am copying the Application Pool name which is “DefaultAppPool” and pasting it in the PowerShell.

Application PoolName

Then it is asking me for the collection plan. I have created a full collection plan before and I am giving the path of that particular xml file which is “C:\ITraceCollector\collection_plan_full.xml”.

Collection Plan Name

Now it’s asking for the Output path where trace files should be created. For that I am creating a folder named “ITraceLogFiles” in my C: drive and I am giving that path and hitting on enter.

Output Path

I am thrown with an error “The following application pool requires write permissions to the output directory: "NTAUTHORITY\NETWORK SERVICE", "C:\ITraceLogFiles".”. Now let’s give full control to the folder “C:\ITraceLogFiles” for the user “NTAUTHORITY\NETWORK SERVICE”.

Setting Permission to ITraceLogFiles Folder

After doing that, let’s run Start-IntelliTraceCollection command back again and it’s time let’s make it short by issuing the command from one line.

No errors this time and it’s asking me to confirm the action. I am entering “Y”.

Now, IntelliTrace collection process has been started. Now let’s try to log in to my web application back again so those events will be collected by IntelliTrace.

Error

Again, I am getting the error. That’s fine and let’s examine the “C:\ITraceLogFiles”.

Created iTrace Files

I can see a iTrace file created there. Since now I know my actions on the web application has been traced by IntelliTrace, let’s stop the IntelliTrace collection by issuing Stop-IntelliTraceCollection command. Now it is asking for the Application pool and I am giving it as “DefaultAppPool” and like previous, I am confirming the action.

Stop-IntelliTraceCollection

Again you can do this by issuing following command in one line.

Stop-IntelliTraceCollection DefaultAppPool

Since IntelliTrace collection is now stopped, let’s open the iTrace file using Visual Studio. You just have to double click on that file, it will be opened using Visual Studio.

IntelliTrace Events

After scrolling a bit I can see several events logged saying “Invalid column name ‘UserName’”. And when I double clicked on an event, it starts to debug with the IntelliTrace window.

Debug Mode

Since the error is thrown from ASP.NET Identity, I cannot debug the code here. If an error is thrown in code written by me, I should be able to directly navigate to the code.

Friday, September 5, 2014

Yesterday conducted a session at Sri Lanka .NET Forum. In this session I have gone through how we can use Debug/Trace classes for logging and for catching errors. Then I have explained about IntelliTrace and demoed how we can use it within Visual Studio. Concluded the session demoing how we can use IntelliTrace in production to debug errors in a Web Application running on IIS.

Monday, September 1, 2014

NServiceBus is one of the widely used service bus for .NET. I have been spending some quality time learning NServiceBus and I realized there is not much resources for learning NServiceBus. Though there is a documentation, it seems to be still evolving over time and not all is still documented. So thought of writing this post as someone might find it helpful.

In this post let’s see how we can write a application where some application publishes events and another application consumes those.

I will start off with the application by creating a blank solution named “NServiceBusPublishSubscribeSample”.

Adding a blank solution

For this solution, I am adding three class library projects named “NServiceBusPublishSubscribeSample.Publisher”, “NServiceBusPublishSubscribeSample.Subscriber” and “NServiceBusPublishSubscribeSample.Messages”. I am deleting default Class1.cs from all the three projects. Now I am running NServiceBus.Host nuget package on “NServiceBusPublishSubscribeSample.Publisher” and “NServiceBusPublishSubscribeSample.Subscriber” projects using Package Manager Console.

Install on Publisher

Installing NServiceBus.Host on publisher project.

Install on Subscriber

Installing NServiceBus.Host on subscriber project.

Once Install on Package Manager Console completed installing all the required files, you can see in both “NServiceBusPublishSubscribeSample.Publisher” and “NServiceBusPublishSubscribeSample.Subscriber” projects, there is a new class added named “EndpointConfig”.

Now let’s move into Publisher Project. I am modifying the “EndpointConfig” class as follows.

I have changed the AsA_Server into AsA_Publisher. In addition I am implementing IWantCustomInitialization interface on my “EndpointConfig” and it is giving me a method to implement named “Init()”. For now, I will keep it as it is.

Now I am adding a new class there and I am naming it as “MyTask”. I am implementing an interface named IWantToRunWhenBusStartsAndStops on “MyTask”.

publicclass MyTask : IWantToRunWhenBusStartsAndStops

{

public IBus Bus { get; set; }

publicvoid Start()

{

}

publicvoid Stop()

{

}

}

Now here in “Start()”, I am planning on publishing some messages which the subscribed clients can consume. For that between the Publisher and Subscriber, I need to share messages. Those messages, I am going to put in Messages Project. I am adding new class named “MyMessage” inside Messages project.

There I have a single property named “Message” of type string.

publicclass MyMessage

{

publicstring Message { get; set; }

}

Then I am adding references from both Publisher and Subscriber to Messages project.

Now moving back to Publisher project, I am modifying the “Start()” method in “MyTask” as follows.

publicclass MyTask : IWantToRunWhenBusStartsAndStops

{

public IBus Bus { get; set; }

publicvoid Start()

{

Bus.Publish(new MyMessage()

{

Message = "Hello World!"

});

Console.WriteLine("Published a message.");

}

publicvoid Stop()

{

}

}

Now inside my Subscriber project, I am modifying the “EndpointConfig” as I did in Publisher project.

I am keeping AsA_Server as it is and in this class also I am implementing IWantCustomInitialization interface and I am keeping the “Init()” as it is.

Now I am adding a class named “MessageSubscriber”. I am implementing an interface named “IHandleMessages<T>”. In this case it’s “IHandleMessages<MyMessage>”.

publicclass MessageSubscriber : IHandleMessages<MyMessage>

{

publicvoid Handle(MyMessage message)

{

Console.WriteLine(message.Message);

}

}

Now I am all set. Now what I need to do is configuring the end points of publisher and subscriber. For that let’s modify the “Init()” methos in both “EndpointConfig” classes in both Publisher and Subscriber projects.

Here I have configured both end points with Fluent API. Once this is done, there is only one part left to get this up and running. Still my Subscriber doesn’t know where to listen for. For that we need to modify the <UnicastBusConfig /> section in Subscriber projects’ app.config file as follows.