Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Login failed for user IIS APPPOOL\AppPool4.5 or APPPOOL\ASP.NET

The error ‘Login failed for user 'IIS APPPOOL\AppPool4.5’ usually occurs when you configure a new website in IIS or move an existing website to a newer version of IIS.

A simple solution to the error is to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.5 and grant appropriate permission to the database.

Open SQL Server Management Studio > Right click ‘Security’ > New > Login

iis-apppool-login

Debugging Parallel Code in Visual Studio

.NET 4.0 introduced the Task Parallel Library (TPL) and Parallel LINQ (PLINQ) in an attempt to make parallel programming simpler and making best use of multi-core processors easier.

Recently I was playing around with the Parallel.Foreach and the new Enumerator APIs for the File System in System.IO trying to build a Fast Folder Scanner when I chanced upon the Parallel debugging options in Visual Studio. After fiddling around a little bit, I was able to make sense of the information and it was kind of a ‘brain explode’ moment.

Let me share the things that I figured out.

The Harness Code

- Let’s create a Console Application called FastFolderScanner

- Next we put together the following code to scan folders for a particular type of file and split them out.

Task based WCF Services in .NET 4.5

Task based asynchronous programming is now simplified and streamlined in .NET 4.5 through the use of keywords ‘await’ and ‘async’. These keywords help makes asynchronous code look similar to synchronous coding, making it easier to write and understand Asynchronous code. Those who have used WCF service might have used the Asynchronous contract generation while adding WCF service reference in the Client application. The Asynchronous contracts are required so that client can make an Asynchronous call to WCF service performing time consuming operations.

In Visual Studio 2012 and WCF 4.5, there is a new option available to generate Task based operations so that the code from the client side can be then less complex. In the following example we will see how to implement it.

Sample Application

Step 1: Open VS2012 and create a blank solution, name it as ‘WCF_Task_Based_WCFService’. In this solution add a new WCF Service Application project targeting .NET 4.5 Framework. Name this project as ‘WCF_TaskBasedService’. Rename IService1.cs to IService.cs and Service1.svc to Service.svc.

Free Chart Control for WinForms, WPF and ASP.NET

Nevron has released a Lite edition of Nevron Chart for .NET as Community edition and they are providing licenses for it absolutely free of charge. Some supported charting types and other features of their chart controls are listed over here: https://www.nevron.com/products-dot-net-chart-free-control.aspx

Since the Community edition is part of the Nevron Chart control, it also relies on licenses (free of charge). They are providing 3 types of licenses –
  • Desktop (required for redistribution of your compiled desktop app),
  • Developer (for your development machine) and
  • Server (required for web application deployment)
The Developer and Server licenses are bound to specific machine IDs and they will require these IDs in order to issue your community license.

You can acquire the free license by following these steps:

1. Register a Nevron.com account and activate it

2. Download the Nevron Vision for .NET installation. They are providing 5 separate installations for the different versions of Visual Studio and the .NET Framework

3. Once you install the Vision suite on your development machine, run the Nevron License Key Manager and obtain the machine ID (located in the key manager window title)

4. Send them your development machine ID via email

Nevron will reply back once the account is updated and the corresponding licenses are available.
I think overall if you are a developer who needs a free chart control for your .NET apps, this is as good as it gets. Get your free license here

Celebrating the 1st Anniversary of our Free .NET Magazine with Prizes

Some of you may already know about out Free Digital Magazine for .NET professionals that we publish every alternate month. This magazine contains exclusive .NET articles covering some of the latest .NET Technologies and interviews with .NET Experts like Eric Lippert, John Skeet etc.

We recently released the 1st Anniversary Edition of the DNC .NET Magazine and to celebrate this achievement with our readers, our awesome sponsors have put up plenty of prizes to win.

image

Model Binding in ASP.NET 4.5

In this article, we will explore a new feature introduced in ASP.NET 4.5 called Model Binding which displays data on our WebForms using the SelectMethod attribute of a data bound control. We will also see how to filter data using Value Provider Attribute Eg: [QueryString].

A couple of days ago, I had written an article on “Strong Typed Data Controls in ASP.NET 4.5” which demonstrated a new way of binding data to the data controls in ASP.NET 4.5. We will be using the same example in our demonstration. If you have not seen that article, I suggest you to go through it first.

Let’s start talking about Model Binding in ASP.NET 4.5. In earlier versions of ASP.NET web forms, we used different data sources to perform Insert, Select, Update and Delete operations. We especially used the Object Data Source to implement our own logic during these operations.

In ASP.NET 4.5 web forms, we can use Model Binding for our data bound controls. Now we can specify Insert, Select, Update and Delete methods directly in our data bound controls which can call the logic of the same from the code file of our web form or from other classes.

Perform CRUD Operations using OData Services in .NET

In this article, we will see how to perform CRUD Operations using OData Services in .NET applications.

OData (Open Data Protocol) is a web protocol for performing CRUD operations which is built upon web technologies like HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to the data to various applications, services and stores.

We can use WCF Data Service to expose OData. For this demonstration, we will create a table with the Name Customers under database “CallCenter” in SQL Server 2008 R2. The table script is given below –

CREATE TABLE Customers
(
    CustomerID INT PRIMARY KEY,
    ContactName VARCHAR(50),
    Address VARCHAR(50),
    City VARCHAR(50),
    ContactNo VARCHAR(50)
)


Now let’s start by creating a WCF Data Service which will expose our CallCenter database entities using ADO.NET Entity Data Model. To create a WCF Data Service, let’s open Visual Studio 2012 and create a New Web Site. Choose “WCF Service” and name it as “ODataService_CRUDOperations”.

A Free .NET Magazine for Developers and Architects

A couple of months ago, on DotNetCurry.com, we started the 'DNC Magazine',  a FREE, bimonthly (once every 2 months) digital publication bringing you the latest from the .NET world presented by Microsoft MVP's and industry veterans.

We are three editions old and so far, we have covered topics like C# 5, ASP.NET, MVC, SharePoint, Azure, TDD, Visual Studio, VS ALM, Entity Framework, HTML5, jQuery,  Knockout.js, RavenDB, Roslyn, SignalR, WCF 4.5, WinRT and Windows 8 Application Development amongst others. Not to mention, an exclusive interview with a .NET/Technology expert in every issue like Ayende Rahien, Jon Skeet and Jon Galloway.

Here’s a screenshot of the magazine

image

Feel free to subscribe to this magazine and if you have any suggestions or feedback about the magazine, please drop us a mail or leave a comment.

Click here to subscribe to this free digital magazine

ReadOnlyDictionary in .NET 4.5

Yes! For people doing custom implementation to create a Read Only Dictionary, there is now a .NET BCL implementation of the same in .NET 4.5.

For the Uninitiated the question is - Why do you need a ReadOnlyDictionary in the first place?

A ReadOnlyDictionary is a useful data container when you are sending data across layers of an application and you want to ensure the data is not modified across the layer.

A good use case for this is Configuration information that is critical for functioning of an application. We may want multiple layers of the application to have access to the configuration information (and a dictionary is a very good way to pass configuration around) but no one should be able to update the configuration directly without going through the required checks and balances. In the following sample, we will look a small such sample.

A Read-only Configuration

Step 1: Create a new Console Application in Visual Studio 2012 CP. Name the Solution ‘ReadOnlyCollectionSample’.

Step 2: Add two Window Class Library projects, ConfigurationLibrary and ConfigurationConsumer.

Step 3: In the ConfigurationLibrary project, add a Class called ConfigurationContainer

solution-structure

Step 4: Setting up the ConfigurationContainer

- In the ConfigurationContainer, add a field _mutableConfiguration for type Dictionary<string, string>. This is where we will load our configuration.

- In the constructor, initialize the _mutableConfiguration dictionary and add some key value pairs to it.

- Add a property called Configuration with the type ReadOnlyDictionary<string, string> with a getter only. The Getter will return a new instance of ReadOnlyDictionary<string, string>. The Read Only Dictionary is initiated using the _mutableConfiguration.

- Add a public method AddToConfiguration(key, value). This method will add/update a configuration key/value pairs from outside.

- Add a method ConfigurationAllowed that returns a Boolean. This contains the logic that decides if a particular configuration parameter can be updated or not and update it accordingly. Essentially we have restricted users from updated the Configuration and we will be controlling the update via this method.

- The final class looks as follows:

configuration-container

Step 5: Setting up the ConfigurationConsumer

- Rename the Class1 to ConfigurationConsumer

- Declare a field of type IReadOnlyDictionary<string, string> called _config.

- In the Constructor initialize the _config field by using the Configuration property of an instance of ConfigurationContainer

- Add a method DoSomething() that checks if a “key” called configuration exists and prints a message with the value if it does. If the “key” does not exist it prints a different message.

- Add another method called BeNaughtyWithConfiguration(). Try to cast the _config read-only dictionary into an ordinary IDictionary. Now add a key to the IDictionary instance. The full listing is as follows

configuration-consumer

Step 6: Using the Configuration in ReadOnlyCollectionSample

- In the Program.cs’ main method instantiate the ConfigurationConsumer and call the DoSomething() method

- Add a Console.ReadLine() to wait for user input before executing the next line.

- Call the BeNaughtyWithConfiguration() method

- The Final code is as follows

program-main-method

Running the Sample

Build and run the sample. The output on the console will be something as follows:

console-output-1

As we see, the value from the Read only dictionary was extracted successfully.

Next we hit enter and the code tries to execute the BeNaughtyWithConfiguration method. Wham! We get the following exception:

not-supported-exception

As we can see, our ReadOnly configurations are safe from type conversion into updatable counterparts.

If you add a watch for the convertToReadWrite.IsReadOnly property, you will find it to be ‘True’.

watch-isreadonly-true

A Note about Dictionary of Mutable Objects

In our above sample, the Dictionary was that of primitive type ‘string’ that is itself immutable. However if you had a read only dictionary of type say ConfigElement, where ConfigElement is defined as follows:

config-element

The ReadOnlyDictionary in this case would not be able to prevent changes to the ConfigElement instance. So if someone retrieved the ConfigElement from the readonly dictionary and updated the Value property, the property would get change in the instance that’s in the Dictionary.

updating-mutable-objects

This code will give us the following output

updated-mutable-objects

As we can see the element got updated in the Dictionary.

Conclusion

To conclude, the new ReadOnlyDictionary<T,T> generic type in .NET 4.5 fulfills a long standing feature request for the BCL. It will be very useful for scenarios where read only Dictionaries need to be exposed. One such case is shown above.

The final code (including use of the ConfigElement type) is available here. Repo at: https://github.com/devcurry/ReadOnlyCollectionSample

Note: We have tested the code on the following combinations
1. VS 2012 RC + Windows 7
2. Win8 CP with VS11 Beta to run the code sample. It is going to work on Win8 RP + VS 2012 RC as well.

Zip Archives Become a First class citizen in .NET 4.5

Compression in the .NET framework has been supported via different libraries in the past (via Open File Conventions) but the support for .zip archives hasn’t quite been complete. With .NET 4.5 we get a dedicated zip compression library that allows us to manipulate zip libraries fully.

Introduction

Up until now, compression in .NET was supported only to the extent of supporting Open File Convention and centered on need to adhere to the convention. As a result the archives created we never fully compliant with the zip archive specs. Introducing the System.IO.Compression.ZipArchive type that now covers all our archive compression and decompression needs. In this post we will see the available features and how we can use them to create various types of archiving solutions.

Features of System.IO.Compression.ZipArchive Type

Single step extraction of existing zip libraries
A zip archive can be deflated in a single step as follows

ZipFile.ExtractToDirectory(@”D:\devcurry.zip”, @”D:\devcurry\”);

This above code extracts the dnc.zip file into the D:\dnc folder.
Single step compression of entire folder
A zip archive can be created from a folder in a single step

ZipFile.CreateFromDirectory(@”D:\devcurry”, @”D:\devcurry.zip”);

This compresses the entire contents of devcurry folder into devcurry.zip
Selected compression of a list of files
Single step compression is fine but often we need to be able to create an archive of a set of files in a particular folder. For example, if you blog often with code samples you need your source code packaged without the bin and obj folders as well as exclude the *.user and *.suo files to prevent user cache information from being distributed. The zip library in .NET 4.5 allows us to create a zip archive of selected files as well.

As we will see in the example below it is a very easy to use and powerful library.
Streaming Access to compressed files
Large zip libraries become a limitation in some archiving tools because attempt to open a big file chokes on lack of system memory and crashes. The Zip library in .NET 4.5 provides streaming access to the compressed files and hence the archive need not be loaded into memory before an operation. For example

using (ZipArchive zipArchive = 
  ZipFile.Open(@"C:\Archive.zip", ZipArchiveMode.Read))
{
  foreach (ZipArchiveEntry entry in zipArchive.Entries)
  {
    using (Stream stream = entry.Open())
    {
      //Do something with the stream
    }
  }     
}

A typical use for this could be while building a web server where you could zip and unzip data on the fly. Another use could be collecting data from Internet streams like Twitter or Github statuses and compressing them directly into an archived file.

Example: Compress a Visual Studio Solution file without binaries and personalization information

Visual Studio 2010 has a nice extension called SolZip. What it does is, it adds right click menu to Visual Studio and on right-clicking the Solution in Solution Explorer is creates a zip file without the bin/obj folders. It also excludes the personalization info in the .user and the .suo file. If you bundle these files along with your project and give it to someone they may just end up with conflicts or folder reference issues.
Coming back to the topic, while doing my previous article on CallerInfoAttributes I was in Visual Studio 2012 and went looking for SolZip. I couldn’t find it. Now while writing this article I realized I could create a command line version of it and demonstrate the power of the Zip library in .NET 4.5

Step 1: Create a new Console Application Project in VS 2012

Step 2: Add Reference to the System.IO.Compression and System.IO.FileSystem

add-reference-to-system-io-compression

Step 3: Setup defaults.

We setup the default parameters for the zip file to exclude the files we don’t want by specifying the extensions and/or the folder names that need to be excluded. Note the folders start with a ‘\’.

initial-setup

CreateArchive is the function that actually does the Archiving and returns number of files archived. Once returned we show the number of files returned and wait for the users to hit enter, when we quit the app.

By default if no parameters are specified, this utility will try to zip the contents of it’s current folder while excluding the files with ‘.user’ or ‘.suo’ extension or files in the either of the bin, obj or packages folders.

Step 4a: Filtering and archiving the files

The CreateArchive method takes in the root folder name from where the archiving is supposed to start, the list of extensions and folders that should be excluded and the name of the final archive.

The Excluded method takes the current file in the list of all files being enumerated, and check if it is in a folder that’s excluded or if it has an extension that’s excluded.

create-exclude-method-signatures

Step 4b: The CreateArchive method

The CreateArchive method takes the source folder path and the provided archive name and checks if the archive already exists. If it does it asks the user if it should be overwritten. If user selects y, then the file is overwritten else the process is aborted.

After confirmation, Directory.EnumerateFiles(…) enumerator opens an enumeration over all files in the source folder including sub-folders. The enumerator returns each file’s relative-path. Once it is determined by the Excluded method that the file has not been excluded we add it to the archive.

create-method

Syntax for opening the Archive and adding the file is highlighted. Couple of notes

The CreateEntryFromFile(…, …) method takes two parameters, first one is the source file path, the second one is the path starting from the folder where the archive is located. For example, Let’s assume we have the following structure.

add-file-parameter

We want all contents of the highlighted ‘SolutionZip’ folder in an archive called ‘Archive.zip’. Now as we loop through all the files and come to the AssemblyInfo.cs in the (highlighted) Properties folder. To add this file to the zip value of

file = .\SolutionZip\Properties\AssemblyInfo.cs
addFile = SolutionZip\Properties\AssemblyInfo.cs

Point to note is the value for addFile HAS to start at the folder in which the zip file is, without that the zip file is unable to show the sub-folder structure in Explorer (even though the zip file is valid).

Step 4c: The Excluded method

- The excluded method first creates a collection of folders in the exception list.

- Next it checks if the file’s extension is in the exceptions list. If present it returns true meaning the current file is excluded.

- If it doesn’t find the extension in the excluded list it goes ahead and loops through the folderNames and check if the current file is in the excluded folder or any of it’s subfolders. If yes, it returns true to exclude the file, else returns false.

exclude-method

That’s it, we have a handy little utility to zip up our solution files without any personalization information. Syntax for it is

C:\> SolutionZip.exe mySolution\ solutionName.zip

Conclusion

With .NET Framework 4.5 we have a powerful and robust Zip archiving utility that can be used in our applications so we don’t need to rely on any third party zip providers.

You can Fork the code on Github or Download the source code here

Using Caller Info Attributes in C# 5.0 to Improve Logging

The problem of passing current method details haunted my team and me when we were asked to add logging to every available business layer method in a two year old project, that had no logging and empty try { } catch { } blocks. We eventually worked around it by using a mix of reflection and string literals to get the current method name. But in my guts I hated the fact that I had to use reflection to do logging. This was 5 years ago using C# 2.0.

Come VS 2012 and C# 5, we will have access to three attributes that do specifically the task that we had hacked around then. These attributes are

  • CallerFilePathAttribute
  • CallerLineNumberAttribute
  • CallerMemberNameAttribute

These can be used in any logging method to retrieve the calling method and log it. In this post, we will see how we can use Log4Net’s rolling file Appender* and the Caller Info Attributes to log errors in an application

Note: Appenders for log4Net are like Providers and serve as an extension point for Log4Net. The RollingFileAppender logs errors to a file and rolls over to a new file if the current file passes certain criteria like a date based roll over or size of file based roll over. You also have SQL Appenders and Xml Appenders and host of log outputs possible using Log4Net.

Starting off with a Console Application

Create a new Console Application in Visual Studio 2012 (aka VS 11)

main

We will simply log key-strokes as input at the Console window and depending on type of keys pressed throw exceptions with different methods. We end the execution when users press the Escape key. The code for this is in the LoopInfintely() method shown below.

loop-infinitely-method

To show that the Caller Info Attributes work at the method level we are logging Errors from a method called LogError as shown below

log-error-method

Logger class above is a Singleton wrapper around Log4Net. Before we look at the code for it, let us see the steps to install and configure Log4Net.

Setting up Log4Net

If there was ever anything to complain about Log4Net it was setting up a basic workable Appender in one go. Thanks to Nuget and the Community that has been rectified. Install Log4Net using the following command in the Package Manager Console

PM> install-package log4net

Next install a Rolling File Appender configuration using the following package

PM> log4net.samples.rollingfileappender

The above inserts the following configuration section in the App.config

log4net-config-declaration

The configuration section is as follows

log4net-config

With this as a default, Rolling File Appender has been setup that rolls over daily. We have updated the file location and the converstionPattern as highlighted above. The conversion Pattern ensures the fields are Pipe ( | ) separated, making them easy to import into excel and monitor.

With Log4Net in place let’s implement our Wrapper class Logger

Implementing the Log wrapper – Logger

The Log wrapper is a singleton class that creates one instance of the Log4Net logger and exposes methods for logging different levels of messages. For example it has methods Error, Warning and Debug to log corresponding levels in Log4Net.

It is initialized as follows

initialize-log4net-viewer

The GetLogger factory method initialized the LogManager.

The log4net.Config.XmlConfigurator.Configure() uses the configuration defined in the App.config

The Initialize method is called the first time _log is used. We have a guard clause to check if _log has been initialized. If not, the Initialize() method is called.

Using the Caller Info Attributes and Logging

So far we have a sample application that waits for key-strokes at the console and throws exception with different messages depending on what type of key is hit. Numeric keys result in Debug level logs, Function keys result in Warning level errors and all others result in Error level logs.

Now we look at the wrapper functions in our Logger class and see how we are obtaining trace information. As seen below we have three attribute decorated optional parameters called memberName, sourceFilePath and sourceLineNumber. These are decorated with the Caller* attributes. We can now very easily use these input params in our logs as shown below. The beauty of the implementation is ONLY your logger wants this information so it is specified only in the logger not in every method call to the logger. This by my standards is Magic!

logging-code

Digging Deeper Into Caller Info Attributes

Actually there is not much of magic here, if you notice the three pieces of information they are static once the code is compiled. So the compiler simply replaces the optional parameters with the static values of MethodName, FilePath and SourceLineNumber in the method call at runtime. Basically the compiler is writing a bit of code/text for us at compile time.

Looking at the Logs

I had initially specified the log format to be pipe ( | ) separated. So we can open the file in Excel and specify custom separator as ( | ). Part of the log looks as follows

log-messages

As we can see in Column D we have the details of the Method (where the error occurred), the File in which it occurred and the line number at which the error occurred. The Debug and Warn logs were from the LoopInfinitely whereas Error logs are from the LogError method. In column E we have the exception message and as we can see we have thrown messages based on type of keys typed.

Conclusion

The caller info attributes have primarily been added to aid runtime debugging and error handling. This is a very robust low-level language support.

As seen above it greatly helps writing better trace routines for runtime issue debugging. Also they are simply optional parameters, so you can at any point override the default values and pass in custom values in the parameters.

The Caller Info values are emitted as actual strings into IL at compile time and are not affected by obfuscation.

Another use for the CallerMemberName attribute is implementation of the INotifyPropertyChange interface. Without the CallerMemberName we would need to pass in the property name as a mandatory parameter.

Fork this on Github or Download the entire source code

Reference

http://msdn.microsoft.com/en-us/library/hh534540%28v=vs.110%29.aspx

Task-Based Asynchronous Pattern in .NET 4.5 – Part 1

In a previous article we saw an overview of the new IDE and Framework features of the current .NET Framework beta v4.5. Among other things .NET 4.5 has an improved support for Asynchronous programming through a new Task based model. In this article, we will take a look at the new async and await key words introduced in the C# language.

Asynchronous programming has always been considered a niche and has always been delegated as a ‘good-to-have’ in v2 of something that you were working with. Moreover lack of Async APIs meant you had to wrap async functionality first before you could use them in your code. Basically a lot of plumbing was potentially required to get off the ground with Async programming.

So the synchronous API for reading into a byte buffer would traditionally look as follows:

public class MyReader
  
{

  
    public int Read(byte [] buffer, int offset, int count);

  
}

The pre-TPL API would look something like the following and you would have to setup the callback method yourself and track the End[Operation].

public class MyReader
  
{

  
    public IAsyncResult BeginRead(

  
        byte [] buffer, int offset, int count, 

  
        AsyncCallback callback, object state);

  
    public int EndRead(IAsyncResult asyncResult);

  
}

Instead of the call-back model, one could use the Event based model and write it up as follows

public class MyReader
  
{

  
    public void ReadAsync(byte [] buffer, int offset, int count);

  
    public event ReadCompletedEventHandler ReadCompleted;

  
}

public delegate void ReadCompletedEventHandler(
  
    object sender, ReadCompletedEventArgs eventArgs);

public class ReadCompletedEventArgs : AsyncCompletedEventArgs
  
{

  
    public int Result { get; }

  
}

But with the introduction of Task Parallel Library (TPL), asynchronous programming became easier. To make the above, we would simply need the following code

public class MyReader
  
{

  
    public Task<int> ReadAsync(byte [] buffer, int offset, int count);

  
}

  
Now the above method signature shows how an Async method would be implemented. It returns a Task<T> where T is of type required for the return and the method itself by convention has the word Async appended to it.
Apart from the lesser plumbing required, the framework added a huge collection of Async methods by default. So going forward in this article, we will look at how to consume Async methods provided in the framework.

Consuming an Async call and the ‘async’/‘await’ keywords

As mentioned above the latest .NET framework provides a lot of Async counterparts of older Synchronous method calls. Specifically anything that could potentially take more than 100ms now has an Async counterpart. So how do we use these async methods?
In .NET 4.5 we use the async and await keywords while consuming Asynchronous APIs. So to consume the above ReadAsync we would write code as follows

get-data-async

The method signature when marked with async keyword tell the compiler of our intent to use Async method and that we wish to ‘await’ returning from these Async methods. So the compiler expects one more await keywords in the method. If none are provided, compiler will generate a warning.
Under the hood, the compiler generates a delegate for code after the await key word is used and moves execution to the end of the method such that the method returns immediately. Thereafter the delegate is called once the async method is complete.

Things to look out for

All looks pretty neat, where is the catch?
Well there are quite a few when leveraging the Async framework.
Synchronization Context
Though thread synchronization has now been hidden away from you, does not mean it’s not happening. For example an async read operation that is initiated from the UI thread will have a SynchronizationContext stashed away and every thread completion will result in a hop back to the initiation thread. This is a good idea most of the time because for end users the hop back means ability to show progress on the UI or work on the UI thread. However if this call is initiated from UI thread and passed on to a library whose sole purpose it to read the data asynchronously, the overhead for hopping back and forth between the execution thread and the UI thread is very high and big performance killer. To avoid this Sync context can be skipped using the following syntax

…
  
{

  
    …

  
    int bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false));

  
    …

  
}

What ConfigureAwait(false) does is, it tells the framework not to hop back into the initialization thread and continue if possible.
Avoiding Deadlocks
Incorrect use of the ‘Wait’ call instead of the synchronous ‘Await’ call may cause deadlocks because issuing a Wait on the initialization thread blocks the UI thread, and when ReadAsync tries to synchronize it can’t so it waits resulting in an unending wait. This situation can be avoided if we configure TPL to avoid synchronization context using the ConfigureAwait(false).
How Garbage Collection is affected
Use of the async keywords results in creation of an on-the-fly state machine structs that stashes away the local variables. Thus these local variables are ‘lifted’ up from the ‘stack’ allocation and moved into the heap. Hence even through they look like local variables they definitely stay around for longer.
Moreover .NET’s GC is generational and sometimes multiple sync points might push the allocated ‘locals’ into an older generation thus keep them around even longer before they are eventually collected.
Asynchronicity and Performance
Asynchronous operations are more about scaling and responsiveness rather than raw performance. Almost all asynchronous operations suffer a performance for a single operation due to the overheads introduced. Hence do not treat Performance as the criteria for doing async operations. True performance gain is an aggregate of how better your async implementation uses resource better.
Client vs. Server Async operations
Just as performance is not the reason to do Async, it may not be a good fit for server side operations either. On the client side, asynchrony is all about getting the UI thread freed up for user-interaction as soon as possible by pushing compute intensive tasks off it. But on Server side, operations deal with processing a request and responding to it as quickly as possible. There is no UI thread per se. Every thread is a worker thread and any thread blocked is an operation in wait. For example in ASP.NET the thread pool is revered resource. Unnecessary thread spinning by indiscriminately using threads increase CPU resource requirements and reduce server scaling. Remember in case of servers the most important thing to do is to avoid context switches. Choose an async operation wisely for example when you have I/O intensive operations, using async with correctly configured awaits will actually help the operation.

Going forward

This was a quick introduction to the basic features of the Task-Based Asynchronous Pattern in the upcoming framework release. We will explore more features of this implementation in a follow up article.

Real Developers never start a Project without Source Control, Period! Mercurial on BitBucket

Real developers never start a project without source control, period! So, today I am going to walk you through the steps to use www.bitbucket.org’s Mercurial (Hg) repository.

Disclaimer: BitBucket has not sponsored this article, you can use any available online Mercurial repository

BitBucket offers both Mercurial and Git repositories. I started off with Hg because at the time they had better tooling for Windows. But Git tooling has fast come up to speed and is now on par. I also chose BitBucket over the more popular GitHub because it doesn’t allow free private repositories. You have to pay for private repositories. BitBucket allows private repositories, even for commercial purposes. 

Please read the EULA carefully. For me I needed a place to keep my blogging source code that I make available for free, so I don’t have a commercial interest.

- To start off, go to www.bitbucket.org and setup a free account.

- Next go to http://tortoisehg.bitbucket.org/ and download Tortoise for Hg. If you have used tortoise for SVN earlier, this will be very familiar to you. If not, no worries, we’ll walk through the steps to learn the basics.

- Install Tortoise, since it’s a shell extension you may need to restart the machine. Go ahead and restart.

- Hg is a distributed source control, meaning you have a complete repository locally and any changes you make and ‘check in’ or ‘commit’ goes into the local repository. This is advantageous in multiple ways
  • You can keep checking in your code without affecting others or the build (that should be from a build server’s repository).
  • In your local repository, you can revert and diff code for your changes or changes pulled down from server.
  • You can start a local repository first and then push it to the server once you are ready.
  • You can do a repository pull from the server to create your ‘clone’ and continue committing locally till you are ready to push changes to server.
Method 1: Creating a Local Repository and pushing it to server

Let’s say you are travelling in an airplane without access to Internet and you come up with a brilliant idea that you have to prototype, then and there. You can get started with source control right away.

Create your solution in VS, mine is called HgVersioning. Open Windows explorer and navigate to the folder. Right click on it and select TortoiseHg -> Create Repository Here

create-local-repository

The following dialog, will popup. Select ‘Create’. Click Ok for the confirmation dialog

local-repository-path

repository-created-successfully

Notice the folder will now have a (?) attached to it indicating it’s being watched for changes and that it has uncommitted changes.

new-hg-folder

Committing code locally

Right click on the folder and select ‘Hg Commit’. This will bring up a dialog similar to the one below

commit-initial

Right click on one of the file in obj folder and select Ignore. The following dialog will pop-up.

ignore-filter-obj-files

Change the selection highlighted from Blob (default) to Regexp. Basically we are telling Tortoise Hg to ignore obj folders because these keep changing with every build. Repeat the same for the bin folder

Now select the .suo file and add it to ignore list. Only this time keep the ignore type to Blob. Repeat for .hgignore file.

With all the non-required files ignored, your check in list should like the following

first-local-commit

Don’t forget to put comments because even though it’s a local commit when you push it to server all your comments will be pushed to server. Hit Commit. The code is now in your local repository.

You can continue to make changes and commit to local repository

Pushing code to server

Now let’s assume your first cut of prototype is done and checked in on your laptop. Your plane lands, you get to a place with Internet. So for safety you want the code off your machine into some place more ‘reliable’. Let’s see how to push the code to BitBucket.

Log in to BitBucket. To create a new Repository click on the big green + sign.

bitbucket-create-new-repository

Fill in the Name, Description, Repository Type and Public/Private status. Keep the name same as local.

bitbucket-repo-creation-1

Click ‘Create Repository’ to finish the repository creation process. You should see a success screen as follows.

bitbucket-repo-created-1

You can push code in two ways.

1. From the command line.

Navigate to the folder where your project is and type in
Hg push https://[youraccountname]@bitbucket.org/sumitmaitra/hgversioning
<Once you hit return, it will ask for your password>
Password: [Provide your BitBucket Password]

2. From the UI.

Right click on your Project folder and select ‘Hg Workbench’

invoke-hg-workbench

The workbench looks as follows, select the ‘Refresh’ button as selected below

add-remote-repository-url

Initially the “Remote Repository:” will be empty. Change the Url Type from ‘local’ to ‘https’.

Put in the User ID and url of remote repository, Finally provide the path to the repository.  The final URL should look something like below

provide-url-params-for-remote-repository

Now click on the ‘Push outgoing changes to selected URL’ button (highlighted above).

push-to-remote-confirmation

Click Yes to Confirm

password-confirmation

Provide your BitBucket account password and wait for the push to complete. A banner on top will indicate the push is complete.

push-to-remote-successful

There your code is now secure in a cloud hosted source control server and you don’t need to worry if your laptop crashes what will you do. Next we’ll see the second method of creating the project on BitBucket first and pulling it down

Method 2: Creating the project on Server first and committing the code back

Create a new project in BitBucket as shown earlier. Copy only the url part from the instruction on how to clone the repository

Open Windows Explorer, go to the folder where you want to download the project, right click, TortoiseHg->Clone

provide-remote-repository-url

Paste the URL in the Source, and hit Clone. Provide the password as prompted and done. New source controlled folder is ready

remote-repository-cloned-locally

Create your project and ‘Commit’ as earlier. Only difference is when you Push to server the URL will be ready for you so you don’t have to add it explicitly.

That concludes this article on how to get started on BitBucket using Hg.

Don’t let your code be without source control anymore!

Most Popular .NET, jQuery and Web Development articles in 2011

With 2012 fast approaching and 2011 drawing to an end, we've put together our list of the Most Popular .NET articles on DevCurry.com this year. The year 2011 featured articles on DevCurry covering many technologies like jQuery, HTML 5, ASP.NET, MVC, Silverlight, WPF, .NET, VS 2010, Entity Framework and Sharepoint, just to name a few.

I would like to thank each one of you who has visited my blog or contributed to it by submitting a Guest post, Subscribing to RSS Feed, by joining me on Twitter or the Facebook page or promoting the articles and giving regular feedbacks via rating, comments or Emails. Many thanks to those too who purchased my jQuery ASP.NET eBook.

Here are some articles that were liked the most by readers like you. Have a very Happy New Year 2012!

.NET Articles


jQuery & JavaScript Articles


HTML 5 & CSS Articles

SQL Server for .NET Programmers

As a programmer who has been developing data oriented .NET applications on SQL Server for over a decade now, I have become a strong believer of the fact that a programmer’s knowledge is incomplete, without having knowledge of the database and network he/she is interacting with. In my opinion, T-SQL and SQL Server Administration knowledge to some degree of depth, helps to design and develop your applications well and assists while communicating with the DBAs and admins in your organization.

I have published two link lists that I feel would help a .NET programmer to increase his/her knowledge of the SQL Server database.



Hope you find them useful!

Parallel Running Task Window in Visual Studio 2010

Visual Studio 2010 has provided lots of facilities for developers writing applications targeting various .NET versions. The .NET 4.0 Framework has introduced task parallel library using which you can write code which makes use of the available cores on the deployment machine.

Now as a developer, if you are working on multiple asynchronous operations, you can make use of  the Task class. I have already explained the mechanism of coding using task parallel library over here.

Now if you want to view the visual schedule of the parallel tasks and see each object in the thread, Visual 2010 has provided us this capability using Debug > Windows > Parallel Task window.

Let’s consider the following console application:

task parallel library example

Step 1: To view the ‘Parallel Task’ window, put a BREAKPOINT on the ‘taskDepartments’ declaration code as shown below:

parallel window breakpoint

Step 2: Run the application and click on Debug > Windows > Parallel Tasks. You will see the Parallel Task Window as circled below:

parallel task window

Step 3: Now step through the code, and you will find the Task entries in the Parallel Tasks Window as shown below:

parallel task window

The above image of the Parallel Tasks window shows that two Tasks are running. Currently the control is on the ‘taskDepartments’ task object, so the Location provides the operation being handled by the current running task.

parallel task window

Similarly, in the above image, we can see that the task ‘taskEmployees’ is running and handling ‘ReadAllEmployees’ operation.

In both the images, the ‘Thread Assigned’ represents the thread on which the Tasks are running.

Conclusion: With the use of Visual Studio 2010 and Task Parallel Framework in .NET 4.0, it is easy for the developer to work on parallel programming and monitor it.