Posts

Showing posts from 2013

CruiseControl.NET: Trigger Project From its URL

Recently we had a requirement to trigger CCNet projects from a Nant file. I thought since Nant and CruiseControl work so well together it would be a piece of cake. But no, Nant doesn’t have anything to trigger projects.

The CCTray connects to CCNet server using Remoting, in days when WCF looks old there are still applications using Remoting :-). I could, in Nant, write C# code and use the library provided by CruiseControl and do exactly what CCTray does to trigger a project. Well, it’s possible, but there was still something missing.If I go to a project’s web dashboard and click on the ‘Force Build’ button – then what happens? I thought that since the dashboard is in asp.net, it might well make a Remoting call on the server-side. But to investigate I fired up Fiddler and this is what I saw:POST http://your-ccnet-server/ccnet/server/local/project/your-ccnet-project/ViewProjectReport.aspx HTTP/1.1
Host: your-ccnet-server
Connection: keep-alive
Content-Length: 16
Cache-Control: max-age=0
Accep…

TPL: Parent-Child Tasks and Captured Variables

What do you think will be the return value of the Task named “parentTask”?voidMain()
{
Console.WriteLine ("Main start.");
//captured variable
int i = 100;

Task<int> parentTask = new Task<int>(()=>
{
Console.WriteLine ("In parent start");

Task childTask1 = Task.Factory.StartNew(() => {
Thread.Sleep(1000);
Interlocked.Increment(ref i);
Console.WriteLine ("In child 1:" + i);
}, TaskCreationOptions.AttachedToParent);

Task childTask2 = Task.Factory.StartNew(() => {
Thread.Sleep(2000);
Interlocked.Increment(ref i);
Console.WriteLine ("In child 2:" + i);
}, TaskCreationOptions.AttachedToParent );

Console.WriteLine ("In parent end");
return i;
});

parentTask.Start();

Console.WriteLine ("Calling Result.");
//next statement will wait on the task
Console.WriteLine (parentTask.Result);

Console.WriteLine ("Main end.");
}

If a parent-child task hierarchy is set by using TaskCreationOptions.At…

.NET Thread Pool

Image
Contents

1. What’s a thread pool and why do we need it?
2. Is it per AppDomain or process?
3. What are the characteristics of a thread in the thread pool?
4. How is thread pool used by the .NET framework?
5. How can we use the thread pool?
6. QueueUserWorkItem
7. Threads are background or foreground?
8. Task Parallel Library
9. When to avoid using thread pool?
10. How many threads are available in the pool?
11. Exceptions
12. Resources

What’s a thread pool and why do we need it?
A thread pool is a store of threads. This store is created at application startup. The thread pool allows developers to focus on tasks or work items and not bother with managing threads actively. It relieves them from instantiating a new thread, starting it over and managing it. Thread pool is also used a lot internally by the framework. For e.g. the asynchronous method calls (BeginInvoke) use a thread from pool, without we knowing or worrying about it at all.
Also creating new threads is expensive, so why not reuse them? …

Difference between delegate() { } and delegate { }

Many times we use delegates such as Action<T> or Func<T, TResult> and we do not want to pass in any argument. For instance, let’s take the Click event’s delegate EventHandler.

The EventHandler delegate expects two arguments – sender and event args, but there are instances when we do not use these parameters in the method. Now when we are writing anonymous method we need to specify these arguments. Code: button1.Click +=
delegate(object sender, EventArgs args)
{
MessageBox.Show("Got Clicked!");
};

But, we also have another option. Code:

button1.Click +=
delegate
{
MessageBox.Show("Got Clicked!");
};

And it works! So we do not use () after the keyword delegate, and it runs perfectly.

But do note, if we are using lambda this option is not available.

button1.Click += () => //ERROR
{
MessageBox.Show("Got Clicked!&qu…

Productivity: Two command-prompt time savers

Image
Recently while watching pluralsight.com videos I noticed that the authors use a console window which allowed them to select and copy text using mouse. And they also had auto-completion for files/directories. As a developer, we work a lot with console applications now and then and having these two features should be a huge time saver.

1> Text selection, copy and paste

Normally we have to click Edit –> Mark –>  Select text –> Press Enter, but there is a quicker way!

- Right-click the title bar and click Properties.



- In the Options tab, look for “Quick Edit Mode” and enable it.
With this setting, we can use left-button mouse to select text and then right-button click or ENTER to copy it. And to paste something, we can click right-button.





2> Auto-completion for files/directories:
For the auto-completion we need to modify the registry. The steps are:
- Open regedit.exe
- Look for HKEY_CURRENT_USER\Software\Microsoft\Command Processor
- Change the value of CompletionChar to 9.







On my co…

C#: object, var and dynamic

Image
One of the interesting concept introduced in C# 4 was the “dynamic” keyword. Let’s see how it is different from the “var” or our old friend “object”.

1. System.Object has been with us since the birth of .NET framework. It is the base class of almost everything. It means we can write:

1: object ostring ="Hello"; 2: object oint =555; 3: oint ="Hello int"; //point to a string 4: ostring =-100;//point to an int
Usage: It is used when the type could be anything. For example a method using object parameter to accept any type and then casting it to appropriate type or use reflection to call operations; or a collection which can hold any type. However with the advent of generics ‘object’ is used less often when creating collections. The primary goal of object class is to be a base class and offer low-level services, which include methods which are common to almost every type in .NET framework or created by users. Methods like ToString(), Equals(), GetHa…

WCF: Duplex Contracts

Image
WCF supports three types of message exchange patterns:

1. Request-Reply
This is the default mode. A point to note is that even if the return type of a service operation is “void” a response would still be sent back to the client.

2. One-way
In one-way operations, the service after queuing up the call doesn’t send anything back to the client. Few details:
- we need to apply “IsOneWay=true” on the operation we want to behave like a one-way
- method type return must be void
- for any exceptions in the service operation, client doesn’t receive any feedback (faults are not returned back).
- the client after making the call returns back immediately to continue execution even if the service operation is still in progress.

3. Duplex
Duplex allows two-way communication. The client makes a call to the service, and then later the service can make a separate call to the client (this call is different from the reply sent back to client for the first call). The call the service makes to the client has its o…

Introducing OData

Image
Last weekend I introduced myself to OData. Here are the findings :-)

Contents:

1. Scenarios
2. Approaches
3. OData
4. Using LINQPad to access NetFlix
5. Examples from the Real World (ecosystem)
6. Resources
7. Developing OData Services(WCF Data Service, ASP.NET Web API)
8. Accessing OData Services (.NET client, jQuery)
9. Limitations
10. And GData?

First let’s start with the scenarios or the domain where OData can be relevant.

Scenarios:

- Let’s say you are a company which runs buses. You are looking for ways to share the information about buses such as arrival time, frequency, operating hours, capacity, service closures etc. You want other web sites and smart phone applications to be able to access this data. How would you do it?
- Say you are working for an online video streaming company like NetFlix and you want to expose your data about movie titles, availability, reviews etc. You want to share this information over the web so that e-commerce web sites like Amazon can create a catalog of your pr…

SQL Server 2012: IIF

Image
SQL Server 2012 introduces the “IIF” function, it’s a shorthand for the CASE expression. I am sure C# developers would love it!

An example: here we are fetching the columns in the table (HumanResources.Employee) using sys.columns and sys.types

> Using CASE

USE AdventureWorks2012
GOSELECT col.[Name],
CASE col.[is_nullable] WHEN 1 THEN 'Yes' ELSE 'No' END AS [IsNullable],
CASE col.[is_identity] WHEN 1 THEN 'Yes' ELSE 'No' END AS [IsIdentity],
types.[name] as [DataType],
col.[max_length] AS [MaxLength]
FROM sys.columns col
INNER JOIN sys.types types ON
col.[user_type_id] = types.[user_type_id]
WHERE col.[object_id] = object_id('HumanResources.Employee')
ORDER BY col.[NAME]
GO

> Using IIF
SELECT col.[Name],
IIF(col.[is_nullable] = 1, 'Yes', 'No') AS [IsNullable],
IIF(col.[is_identity] = 1, 'Yes', 'No') AS [IsIdentity]
,
types.[name] as [DataType],
col.[max_length] AS [MaxLength]
FROM sys.columns col
INNER JOIN sys.types types …

WPF / MVVM Resource Collection

PowerShell: Files and Directories

Image
Many times we feel the need to get the list of files in a directory with all the file details. A picture (screenshot) is worth a thousand words (pixels) but at times it is not the best thing.

(1) Get the file list

Command: cd “C:\Program Files\Adobe\Reader 10.0\Reader”
Command: DIR


This will give us the list, nothing unusual.

(2) Send the list to a text file

Command: DIR > C:\FileList.txt

The file “FileList.txt” will contain the same text that was shown on console

(3) Get only the files or only directory list

The list contains both the directories and files, how do we get only the files? (we can’t do this in a explorer)

Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where{$_.Attributes -ne "Directory"}


The output of DIR is sent to where{}, the “$_” is the current item, Attributes is a property, “-ne” means “not equal to”. Each item in the output of DIR is checked for having the “Directory” attribute. Fantastic!

To get only the directories – we change “-ne” to ‘-eq”
Co…

Windows PowerShell - Get new GUID

Image
Recently I took a brief tour of PowerShell, it’s the Microsoft’s task automation framework. It would suit you more if you consider your keyboard as your friend :). At the moment, I do not know whether I think it is useful or not. I think the more I get to know the various commands, the more I will use and appreciate it.

I am writing this post, so that I can record the PowerShell commands that I begin to use. Here’s is the first one:

Get a new GUID: Currently I use Visual Studio 2005 to get a new GUID value. Now opening up VS just to do that is really an overkill.
In PowerShell we can get it by:


[guid] is a type adapter (you can say alias) to the full class name – System.Guid. NewGuid() is a static method on that class.

If we don’t remember the adapter but if we do know the full class name, we can use –> $guid = [System.Guid]::NewGuid()