Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

C# (Csharp) Switch Case Statement with Example

A C# switch case statement defines multiple groups of statements, and then executes one of these statement; depending on the value of a constant or test expression.

Let us understand this concept with an example.

string siteName = "DevCurry";
switch (siteName) {
    case "DotNetCurry":
    Console.WriteLine("This website is DotNetCurry.com");
    break;

    case "DevCurry":
    Console.WriteLine("This website is DevCurry.com");
    break;

    default:
    Console.WriteLine("Default Website");
}

As you can see, we start by defining a constant at the top:

C# : Cannot implement an interface member because it is not public

If you've written a class that has implemented an interface, you've probably encountered a requirement where a method you are implementing, must be public. The error thrown is usually “Cannot implement an interface member because it is not public”.

If an interface member method is implemented in your class without an access modifier, it is by default private.

But methods have to be either public so that they can be called through the interface, or they need to be explicit. Let us assume your interface is implemented as follows:

public interface ITest 
{
bool IsTest();
}

To change the visibility, you can either change the interface from public to internal.

Random ASP.NET, MVC & C# Tips in 100 Chars

I had a lot of fun last Friday! The South Asia Microsoft MVP group had organized a Techweet Friday where Microsoft MVP’s would tweet tips about different Microsoft Technologies in 100 chars or less.

I tweeted too and here are some ASP.NET, ASP.NET MVC and C# tips for my non-twitter friends

C# Tips

Once you assign a value to a BigInteger variable, it becomes immutable (cannot change)

'var' is not really a C# keyword. You can name variables & parameters as “var” and your compiler won't complain

Enum does not mean Enumerator. Enum is a custom data type whereas Enumerator is a class implementing IEnumerable

Did you know that enum types cannot be written generically. Only classes, interfaces & delegates can be

You should design all custom attributes as sealed .GetValues(typeof(SomeEnum))){ }

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”.

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.

.NET Programming for Absolute Beginners [Free Video Series]

Channel 9 has just launched an absolute beginner programming series to help people learn to program. This FREE training series is created for programmers who have no experience with C# or VB.NET

The series of 49 episodes (24 episodes for C# and 25 for VB.NET) walks you through fundamentals, getting the .NET tools, writing C# and VB.NET code, debugging features, customizations and much more to learn concepts applicable to video games, mobile environments, and client applications

You can access the series as well as read descriptions for each episode in the link given below:



Similarly you may also want to look at the Free Learning Resources section to access .NET training videos, articles, podcasts, ebooks and much more.

Which .NET Attributes are my Assemblies Using?

An attribute describes a characteristic of some elements (classes, methods, fields) of a .NET program. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways. In this post, we will learn how to list all the .NET Attributes that are used by the loaded assemblies in your program.

Use the following code:

image

The above code gets the assemblies that have been loaded into the execution context of the current application domain. We then retrieve the public types in this assembly and select all the attributes. A sample result is as shown below:

.NET attributes

Note: The results may not be the same on each machine. This is because we are referring to GetExportedTypes() which returns type visible ‘outside’ the assembly. So if you add new references to the project or by change the access modifiers of the types, you can get different results.

C#: Find Previous Month's First and Last Day

Here’s a simple query that gives you the first and last day of the previous month.

static void Main(string[] args)
{
var yr = DateTime.Today.Year;
var mth = DateTime.Today.Month;
var firstDay = new DateTime(yr, mth, 1).AddMonths(-1);
var lastDay = new DateTime(yr, mth, 1).AddDays(-1);
Console.WriteLine("First day Previous Month: {0}", firstDay);
Console.WriteLine("Last day Previous Month: {0}", lastDay);
Console.ReadLine();
}

C# Previous Month Dates
You can also use the following method to get the last day of any month. Assuming you want the last day of the current month

var lastDayMonth = DateTime.DaysInMonth(dt.Year, dt.Month);

If you want to do the same in SQL Server, check my post SQL Server: First Day of Previous Month and Find First and Last Day Of Each Month

LINQ: Calculate Average File Size in C#

Let us see a simple code using LINQ and C# that calculates the average FileSize of the files kept in a folder.

First import the following namespaces:

using System.Linq;
using System.IO;


Then write the following code:

class Program
{
 static void Main(string[] args)
 {
  string[] dirfiles = Directory.GetFiles("c:\\software\\");            
  var avg = dirfiles.Select(file =>  
                  new FileInfo(file).Length).Average();
  avg = Math.Round(avg/1000000, 1);
  Console.WriteLine("The Average file size is {0} MB",
   avg);
  Console.ReadLine();
 }
}

The code shown above uses the Average Extension method to compute the average of a sequence of' numeric values. The values in this case is the length of the files in the folder “c:/software”. The result is rounded off to one decimal place using Math.Round

OUTPUT
 LINQ Average File Size

WCF 4.0 REST POX Service with Help Page

Representational State Transfer (REST) support was included in WCF 3.5. In WCF 4.0, this feature has been enhanced with Help page support. This facility was added as WCF REST allows direct call to OperationContracts, using HTTP protocol by the client application. Now the problem is if the WCF service has several OperationContracts, then how does the client application know and distinguish between the urls for method calls? WCF 4.0 REST Help page enhancements provides this feature so that when the WCF service is published on the Web Server, the client application can decide which method to call using the help page and can also view the expected response message generated.

Step 1: Open VS2010 and create a WCF Service application, name it as ‘WCF_REST_POX_Service_Help’. Rename IService1.cs to IService.cs and Service1.svc to Service.svc. In the IService.Svc, add ServiceContract , OperationContract and DataContract, as shown below:

wcf-rest-service

Step 2: In the web.config file, define the EndPointBehavior and define the HelpEnabled attribute for the <webHttp> as below:

wcf-rest-pox-service-help

Step 3: Right-Click on Service.Svc and select ‘View In Browser’, the following message will be displayed:

Service.svc

Click on the Service help Page and you will see the following

WCF Service Help Page

Click on the First Url and you can see an example of the response XML body. Very useful!

WCF Response Body

List<T>.ConvertAll<>() with Lambda Expression

List<T> has many useful methods for dealing with sequences and collections. One such method is the ConvertAll<>() method. All those who have used the List<T>.ConvertAll<>() are aware how useful this method is to convert the current List<T> elements to another type, and return a list of converted elements. However, an instance of a conversion delegate must be passed to this method, which knows how to convert each instance from the source type to the destination type.

For eg: Convert a List<int> to List<string>

ConvertAll with Delegate

However combined with a Lamda Expression, this method can be used to write terse code.

Here’s an example. Let us say we want to rewrite the same code shown above which converts a List<int> to List<string> in the shortest possible way

ConvertAll with Lambda

Add a breakpoint, debug the code and you will see that ConvertAll<>() converted the List<int> to List<string>.

ConvertAll with Lambda

Note: Since ConvertAll() creates a new collection, sometimes this may be inefficient.

Remove all Lower Case Letters using C#

I came across a discussion where the OP wanted to use only the first letter of a word in a string. The first letter of each word was capitalized, so his requirement was to abbreviate the sentence by removing all lower case letters in a string.

For example: ‘We Love DevCurry.com’ would become ‘WLDC’

Here’s how this can be achieved with a Regular expression. Use the following code:

using System;
using System.Text.RegularExpressions;

namespace WordCapital
{
class Program
{
static void Main(string[] args)
{
string fulltext = "We Love DevCurry.com";
Console.WriteLine("Full Text: {0}", fulltext);
Regex rgx = new Regex("[^A-Z]");
Console.WriteLine("Abbreviated Text : {0}", 
rgx.Replace(fulltext, ""));
Console.ReadLine();
}
}
}

In the code above, we are using Regex to match all characters that are not capitalized and then replace it with an empty string.

OUTPUT

image

.NET - Start Asynchronous Parallel Task and Cancel Them Too

I was having a good discussion with a couple of friends about the support of parallel tasks in .NET. If you too are interested in the same, I have written a couple of articles that can give you an overview of the support for parallelism and concurrency in .NET applications.

Parallel Tasks in .NET 4.0 -   The Parallel class found in the System.Threading.Tasks namespace “provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements”. In this article, we will use the Invoke method of the Parallel class to call multiple methods, possibly in parallel.

Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value - In one of the previous articles Parallel Tasks in .NET 4.0, we explored a set of new API’s called the "Task Parallel Library (TPL)" which simplifies the process of adding parallelism and concurrency to applications. We used the System.Threading.Tasks.Parallel.Invoke() to call methods that did not return a value. However for methods that return a value, you would need to use the Task(TResult) class which represents an asynchronous operation that can return a value. We will explore how to use this class in this article

Cancelling Tasks in .NET 4.0 - In one of the previous articles Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value, we used the Task(TResult) class which represents an asynchronous operation that can return a value. In this article, we will see how to cancel a task/operation.

Parallel.For Method in .NET 4.0 vs the C# For Loop - In this article, we will explore the static method Parallel.For. A lot of developers ask me about the difference between the C# for loop statement and the Parallel.For. We will see the difference with an example

On a side note, there are many ways to call a method asynchronously using .NET Delegates. Here are two articles that give you an overview of the same

Call a Method Asynchronously using Delegate BeginInvoke and EndInvoke Pattern - In this article, we will explore multiple ways to call a method asynchronously using Delegates. You can call methods asynchronously in four different ways using the BeginInvoke() and EndInvoke() methods of the Delegate class

Call a Method Asynchronously in .NET using Polling Pattern and Callback Pattern - In my previous article, we explored multiple ways to call a method asynchronously using Delegates. In this article, we will see how to call a method asynchronously using the Delegate Polling pattern and the Callback Pattern.

Loop Multiple Arrays in C# – Short way

Let us see a trick to loop multiple arrays in C#. Consider the following program:

static void Main(string[] args)
{
var arr1 = new[] { 5, 3, 4, 2, 6, 7 };
var arr2 = new[] { 4, 9, 3, 1, 9, 4 };
var arr3 = new[] { 2, 1, 8, 7, 4, 9 };

foreach (int num in arr1)
Print(num);

foreach (int num1 in arr2)
Print(num1);

foreach (int num2 in arr3)
Print(num2);

}

static void Print(int i)
{
Console.WriteLine(i);
}
}

As you can see, we are using three loops to print the contents of the array. Using the LINQ Concat operator, we can shorten the code by reducing three loops into just one, as shown below

If you liked this tip, check some more LINQ Tips

Use Anonymous Method with a Delegate in C#

A colleague of mine asked me a question - ‘How can we use an Anonymous method with a Delegate and when should we do it”.

By using anonymous methods, you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. You can use it to run code snippets that would otherwise require a named method or use it as a quick event-handler with no name.

Here’s the code that shows how to do it. Comments have been placed inline to understand the code

namespace ConsoleApplication2
{
// Define a Delegate
delegate int AddThenMultiply(int i, int j);

class Class1
{
static void Main(string[] args)
{
// Instatiate delegate type using anonymous method
AddThenMultiply atm = delegate(int i, int j)
{
return (i + j) * 2;
};

// Anonymous delegate call
int result = atm(2, 3);
Console.WriteLine("Result is: " + result);
Console.ReadLine();
}

}
}

OUTPUT

Anonymous Method Delegate Call

Determine if your Laptop is Running on battery using C# or VB.NET

Here’s some code to programmatically find out if your laptop is currently running on battery power. I have created a Windows Form application and added the following code on a button click event which uses the SystemInformation.PowerStatus property

C#

private void btnPower_Click(object sender, EventArgs e)
{
PowerLineStatus status = SystemInformation.PowerStatus.PowerLineStatus;
if (status == PowerLineStatus.Offline)
MessageBox.Show("Running on Battery");
else
MessageBox.Show("Running on Power");


}

VB.NET (Converted Code)

Private Sub btnPower_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim st As PowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus
If st = PowerLineStatus.Offline Then
MessageBox.Show("Running on Battery")
Else
MessageBox.Show("Running on Power")
End If

End Sub

image

Check Database connection using C# or VB.NET

As a programmer, one of the most common tasks in your application is to connect to the database. Here’s a very simple way to check your database connection before you start any task or use this as a service to check the connection and pause tasks if the connection breaks.

C#

private static bool DBConnectionStatus()
{
try
{
using (SqlConnection sqlConn =
new SqlConnection("YourConnectionString"))
{
sqlConn.Open();
return (sqlConn.State == ConnectionState.Open);
}
}
catch (SqlException)
{
return false;
}
catch (Exception)
{
return false;
}
}

VB.NET (Converted Code)

Private Function DBConnectionStatus() As Boolean
Try
Using
sqlConn As New SqlConnection("YourConnectionString")
sqlConn.Open()
Return (sqlConn.State = ConnectionState.Open)
End Using
Catch
e1 As SqlException
Return False
Catch
e2 As Exception
Return False
End Try
End Function

The code above opens a connection to the database and returns a boolean depending on the database status.