Author Archives: Abhishek Sur

About Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

How exception filters can help you investigate runtime errors in C#

Exception filters are not new. Its been there for a long time (at least for than a year) as it is been released with .NET framework 6.0. But I do see developers don’t know the basic advantages of using exception filters and use code inside catch to determine problems. Let us look how exception filters can help you determine the actual exception during your execution.
Continue reading

Workstation GC Vs Background GC

Well, there has been a confusion around the developer community on the differences between the Workstation GC which is by default recommended for standalone machines which targets one single CPU Core and the Background GC which provides multicore execution of Garbage Collections.

In general aspect first let us consider how the Workstation is different from the server.

A Workstation is generally used to provide throughput. There could be a single application running which could use multiple Threads, but the basic idea is to give precedence on the application engine rather than the memory.

On the other hand, Server applications are generally very very long running (for instance ASP.NET Applications) and are job specific, such that when a job needs to be performed, a CPU is assigned to it to perform the task, and once the Task is complete the Thread needs to return back to the Pool. Thus server needs continuous maintenance of its memory usage without hampering the peformance of the application.

Related Read:  LargeObjectHeapCompaction in .NET Garbage Collection

There are three types of GC available currently.

1. Concurrent GC

Concurrent GC maintains a dedicated thread to collect memory footprints. When the GC is performed, all the managed thread may continue to run. For responsive applications, it is recommended to use Concurrent GC as it can still allocate memory while GC is running.

To enable Concurrent GC try :

<gcServer enabled="false"/>

2. Background Workstation GC.

This type of GC is mainly recommended for a client application like Windows Forms or console applications which runs on a single processor. The Workstation GC is a single Thread running on the whole application and collect the whole memory heap at a time concurrently using a single Thread.

To enable workstation gc

<gcServer enabled="false"/>

3. Background Server GC.

This type of GC is ideal for multi-core processor. This kind of GC provides separate managed heap and GC Thread for each processor and can perform more than one GC in parallel. When the GC is performed, all the Threads pointing to the current Core gets suspended. For servers the Background GC is much more recommended.

To enable background GC:

<gcServer enabled=“true"/>

I hope this would help in understanding things better.

Let me know your thoughts.

Inside – String & StringBuilder, which and when ?

Well folks,  even if you think that you know the answer and it is very common, I still think you should read this post to make your concept more clear, because strangely I found there are lot developer who still have some  confusion with the concept even though they read tons of articles in the web about the same topic. This post will give you a bit internal on using String and StringBuilder.

To start with,

Strings are immutable. That means, when you manipulate a string in C#, it creates another string instance in a separate location on heap and points to that location without remembering the previous instance.

Ok, I think you all know this sentence as you might have already came across this and the sentence above is 100% true.
Let’s have a look bit inside

string x = "Daily .NET Tips";
string y = "Daily .NET Tips";

Does it say, x and y will have two different memory locations?

Naah… not at all.

C# does a great job with Strings when dealing with intern. String maintains an intern table which stores all the strings that have been either statically typed as above or used in the program itself. So both x and y variables are initialized with one single address where the string stays.

String Allocation

Now let us consider another example :

string x = "Daily .NET Tips";
string y = "Useful Tips and Tricks for .NET Developer";

string z = x + y;

Now here in the above call, x and y are interned into the string intern table but still z creates a memory because strings are immutable and z will point to another separate location which stores the entire content of Z.

String Concat

Here lies the problem. In case you do like:

string z = x + y + " Follow this site at Twitter and Facebook";

The problem became more acute. As strings are immutable, the above line creates a heap allocation for x + y and stores it and then again it creates another memory for storing x + y + “Follow this site at Twitter and Facebook”.

String Concat Operation

Well, this is wastage of memory you can see. Any string operation, like Replace, Remove, Substring etc, will have this problem.

Lets’s have a look at StringBuilder

StringBuilder is a cure for this. StringBuilder stores a character array without using the inner implementation of C# strings and creates a string instance only when the ToString is called for, thus ensuring that StringBuilder becomes mutable.

That means if you write :

StringBuilder z = new StringBuilder();
z.Append(" Follow this site at Twitter and Facebook");

The object z is maintained in heap as a single array instance of characters which keeps on storing the string into it and any replace or removal of some characters inside the StringBuilder will mean the Array gets manipulated not the actual string.

StringBuilder in Heap and Stack

I hope this post helped you understanding the exact differences.

Do let me know if you still have confusion in this.

Benefit of Using in Dispose for .NET objects (Why and When ?)

Well, while being in touch with a number of developers, I always find people don’t understand the real meaning of disposing objects. Lets clear our basic understanding on why we need to dispose objects in .NET before understanding the usefulness of Using block.

Why Disposing is necessary ? 

We all know, the code that we run on our managed environment are called managed code. All the objects that we create and automatically picked up by an invisible hand from the program itself called Garbage Collector. The GC is capable of detecting all the objects that do not have reference from the program that is running on, thus sweeping the unnecessary memory from the program and return the memory to the program again.

Now you must be thinking, does it sweep only the objects that are Disposed? Aah.. No, not really.

Difference between Managed and Unmanaged Memory. 

In managed world, memory are created in object Heap (a memory separate from Execution memory but exists in the process) and the program have entire idea on the start and end location of the memory it have been using. But while creating a program, we do not really create only managed memory. Consider you are opening a File from your program. There is a request from your program being made to open a File, and load it to Page File such that your program can access the memory and get data. This memory is totally unmanaged, and your program can only request to clear the memory and Garbage Collection cannot collect it without your request.  In case of File open, the memory is cleared when we call File.Close. Thus there is a gap between the Managed and Unmanaged Memory boundaries. The Garbage Collector can only collect the Memory that .NET has allocated and unmanaged memory will remain if you do not explicitly call to remove it.

For instance, File IO, DataBase Connection Open, Network call, etc all calling an external process running in the kernel of the operating system to allocate / deallocate memory. Therefore in such cases, you need an explicit memory deallocation inside your program. You can also consider a PInvoke as an example here, as you are calling an unmanaged memory yourself.

What are your option to Deallocate Unmanaged Memory?

Well, by this, you already know that managed memory does not require anything from the programmer to deallocate. For unmanaged memory, you can create a method that can deallocate the memory (for instance File.Close which is opened inside a class) and call it whenever GC collects. Well, yes. There is an option to define a destructor inside a class which will be called directly from the GC itself and deallocate memory. Let us look how to write a class with destructor.

public class TestClass
    public TestClass()
        //here you can write File.Open
        //here you can write File.Close

Now if you see the above code you can see, we can create an unmanaged memory inside the constructor, and clear the memory in the Destructor of the class so that the unmanaged memory used by the class gets cleared.

But there is a Catch !!!
As you know your TestClass is a managed memory, the object instance of the TestClass would only be cleared by the Garbage Collector. The destructor is called only by the Garbage Collector itself. Now the problem is, when Garbage Collector collects the unmanaged memory, it generally suspends the Execution Engine (not in case of Background GC introduced recently) while collecting, and it cannot call your destructor while in the middle of the Collection. Hence, it maintains a new list of all objects that needs the Destructor to be called. So when your TestClass is found by the GC, it puts the object reference in the Finalizer Queue, and moves ahead. This will make your object to stay longer as the GC collects the object until it executes again, when it starts by calling destructor of all the queued references and then starts collecting managed objects.

Related Read : Using or Using ?

The usefulness of Disposable pattern in Memory Management

Destructor Vs Disposable

The Unmanaged memory is expensive. Take an instance of a Database Connection on a Distributed Database system. If your program have to wait for the destructor to call the Close Connection, there would be lot of unused connection remain in the pool for a long time until the GC executes the destructor. .NET solves the problem by giving a simple workaround to write our Dispose method inside the class and a shorthand using block to call the Dispose method automatically. Let us take an example:

public class TestClass : IDisposable
    public TestClass()
        //here you can write File.Open
        //here you can write File.Close
    public void Dispose()
        //Close the file here

Now in the above code what we did is we defined our own method called Dispose which we would call from Managed Code and the GC.SuppressFinalize will ensure that the Destructor will not be called when a Dispose is already called . Thus ensuring the GC to collect the object rather than putting it to the Finalizer Queue.
Related Read : Using Fixed Keyword in C#

Where Using Block lies in ?

Now, as you can remarkably identify that using a IDisposable is way better than having a Destructor in a class, the C# language gives a syntactic sugar to embrace this functionality and encouraging the use of IDisposable rather the destructor. Now let us think how we could have used the class TestClass.

TestClass tclass = new TestClass(); // The line creates an unmanaged memory instance.
// use the tclass to access the unmanaged memory
tclass.Dispose(); //Clear the unmanaged memory.

We also know that unmanaged memory is not pretty safe to access, we must wrap this inside a Try/Catch/Finally block ensuring the try to try creating the object instance, and Finally will ensure that at any cost the memory gets disposed. We will write like this :

TestClass tclass;
     tclass = new TestClass(); // Here memory gets created
     // We use the object tclass here.
   tclass.Dispose(); // here memory gets cleared

The Finally will ensure that even though the try block encounters an exception, the unmanaged memory gets disposed. To give a shortcut to the above code, .NET provides an Using block. To rewrite the above code with Using block, we write like this :

using(TestClass tclass = new TestClass()) // this is here memory is created
 // We use tclass here..
} // this is where dispose called

Thus you can see, the transformation has made the code so much more readable ensuring the programmer never forget to call Dispose from its code. Thus making the life of the programmer simple.

Things to Remember

  1. We only need to dispose objects with Unmanaged Memory.
  2. Destructor loses GC Generation hence it is better to avoid.
  3. GC.SuppressFinalize will allow the programmer to mark an object that destructor does not needed to be called.
  4. Dispose is a better pattern which allows the programmer to clear unmanaged memory.
  5. Using block is a shortcut of try/finally where in the try, it creates an object of the class and in finally the Dispose gets called.

I hope this post will give you better understanding of the Using block and allow you to write better programs in the long run.

Advanced handling of Photo Capture using PhotoCamera in Windows Phone

Well, as I have already dealt with CameraCaptureTask or PhotoChooserTask before for simple scenarios, it is time to go a little further with dealing with continuous capture or even how to switch between FrontFacing Camera or Primary camera etc. To deal with such scenarios, we use the PhotoCamera class and show the stream from camera directly to a canvas or take picture from it. Let us look into the steps to create an app that can make use of Camera Streams directly.

1. First of all, you need to connect to the Cameara. To connect to the Camera, you need to create an object of PhotoCamera and pass the PhotoCamera Source to a canvas element on the App.

private PhotoCamera Camera { get; set; }

var cameraType = CameraType.FrontFacing;
if (!PhotoCamera.IsCameraTypeSupported(cameraType))
    cameraType = CameraType.Primary;
    MessageBox.Show("Cannot find a camera on this device");
this.Camera = new PhotoCamera(cameraType);

In the above code, the PhotoCamera is initialized. Once initialized, ou can set the Camera photo streams to an element in the screen. To do that, we put a border and directly write the stream using VideoBrush.

<Border x:Name="cameraView" BorderBrush="Black" BorderThickness="5" Grid.Column="0">
           <VideoBrush x:Name="cameraBrush" />

Here the background of the border is filled using a VideoBrush. Now to set the CameraStream to the background of the Border, we simply write as :


Now to capture an image using the PhotoCamera, we call


The above code generates CaptureImageAvailable and CaptureThumbnailAvailable events. When the image is available you can write the data directly from the stream to a disk file.

private void Camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
     Deployment.Current.Dispatcher.BeginInvoke(() =>
         MediaLibrary ml = new MediaLibrary();
         ml.SavePictureToCameraRoll(string.Format("{0:yyyyMMdd-HHmmss}.jpg", DateTime.Now), e.ImageStream);

In the above code, you can see the Image when available after CaptureImage is called, is saved to CameraRoll folder of MediaLibrary. The e.ImageStream will hold the image that is been captured from PhotoCamera object. Using this API, you can capture images continuously and add it to the application and/or disk.

I hope this post will come handy. Will post more about PhotoCamera in subsequent entries. Stay tune.

Working with PhotoChooserTask in Windows Phone

Even though we have CameraCapture Task to deal with camera, there is another Chooser available as well, which can take Picture either from MediaLibrary or directly from Camera. The PhotoChooserTask helps in getting an image from the Picture / Media Library locations. The PhotoChooserTask, just like any other Tasks is listed under namespace Microsoft.Phone.Tasks and is inherited from ChooserBase<PhotoResult>, this will ensure that the Task is invoked as a Chooser and the result will be received by the Completed event when choice is made, just similar to CameraCapture.

var photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += (s, e)=>{
    if(e.TaskResult == TaskResult.OK)
        myImage.Source = new BitmapImage(new Uri(e.OriginalFileName));

The above code will show the photoChooserTask and upon selecting the Photo, it will show the picture on myImage control placed on the XAML.

PhotoChooser also allows you to specify ShowCamera, which can invoke the CameraCaptureTask directly from inside of the PhotoChooserTask and select the Photo Captured from camera.

photoChooserTask.ShowCamera = true;

Other than that, you can also set the maximum PixelHeight and PixelWidth of the image choosen from the PhotoChooser. For instance,

photoChooserTask.PixelHeight = 50;
photoChooserTask.PixelWidth = 50;

I hope this code will help. Thank you for reading.

Working with CameraCaptureTask in Windows Phone

Working with Camera in Windows Phone environment is a common requirement. Almost 25% of the apps in the store uses Camera capture on the app. CameraCaptureTask is a common Task available to the Windows Phone device which can capture camera from an app by launching the basic image capture tool present on the Windows Phone environment and take a picture and give the bytes to you. Here is now you can implement it.

var cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += (s,e) => {
    if (e.TaskResult == TaskResult.OK)
         System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
        myImage.Source = bmp;

The above code creates an object of CameraCaptureTask and invokes its Show method. The Show method will launch the Camera Task on the phone and when user captures the image, it will send the Image bytes to the Completed event. Inside the Completed event, we can have the Image stream available as e.ChosenPhoto. Here we simply displayed the stream in myImage control.

You can take the stream and do whatever you feel. For instance you can save the image in MediaLibrary using the following code.

byte[] ibytes = new byte[(int)e.ChosenPhoto.Length];
e.ChosenPhoto.Read(ibytes , 0, ibytes .Length);
e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
MediaLibrary library = new MediaLibrary();
library.SavePicture("myPhoto.jpg", ibytes );

The above code will save the image as myphoto.jpg to the Picture library. You can also pass the image stream to a WriteableBitmap to modify the content.

 WriteableBitmap writeableBitmap = new WriteableBitmap(200, 200);

I hope this will help you while dealing with Photo based applications in Windows Phone. Thanks for reading.

How to increase Memory usage for an App in Windows Phone

Windows Phone is gradually getting matured day by day. Considering the current situation, the Windows Phone environment gives a restrictive environment where app developers are restricted to do certain things if not specified beforehand. The developer cannot use Library, Camera, Sensors or even memory at sometimes if not defined beforehand.

A Windows Phone App is limited to use 150 MB at max. But sometimes it is well a requirement to have more than this limit at least for high spec devices to run. To solve this problem, you can define a capability on your App to ensure you have high availability of application memory.

To increase the size of memory usage we add the following node to the Manifest file of Windows Phone App:

    &lt;FunctionalCapability Name="ID_FUNCCAP_EXTEND_MEM"/&gt;

It is worth mentioning, the Manifest editor tool is not yet capable to display this capability and it is hidden from the tool, but you can still use it.

There is another Functional Capability which will ensure the large memory is available before running the application and opt out the Low memory phones from running the app. If this is your requirement you can use :

    &lt;Requirements Name="ID_REQ_MEMORY_300"/&gt;

If you use the above capability, the App won’t appear in Windows Phone Store for lower memory phones and it cant be installed in low end devices.

Based on your requirement, you can increase the size boundary from 150 MB to 300 MB or for some devices upto 1GB of application memory usage.

I hope this will help you in real world app development.

Thank you for reading.

Opening Settings Screen using Launch URI in Windows Phone

As we saw in the previous post, that you can programmatically change the Lock screen of the Phone from an app which supports extension of Lock Screen defined in the Metadata file, we can also open various settings screen directly from within the app as well. To open an existing settings applet, you need to first know the URI that belongs to the Settings screen. Once you know that, you can use the following code to Launch a settings

public void OpenSettings(string settingsName)
    var op = await Windows.System.Launcher.LaunchUriAsync(new Uri(settingsName));

In the above code, when “ms-settings-lock:” is passed, it will open the Settings page that belongs to the Lock Screen settings.

When OpenSettings(“ms-settings-lock:”); is called the above screen will open with different settings options to change the Lock screen can be applied.

Similar to Lock Screens, there are also a number of other Launch URI that can help in opening various settings from an App.

1. ms-settings-airplanemode: .
2. ms-settings-bluetooth:
3. ms-settings-cellular:
4. ms-settings-emailandaccounts:
5. ms-settings-location:
6. ms-settings-power:
7. ms-settings-screenrotation:
8. ms-settings-wifi:

If you want to open a Webpage, you can pass a http link directly inside the OpenSettings screen or mailto:emailid link to the LauncUriAsync to open webpage or Email client directly from an app.

I hope this post will come handy.

Thank you for reading.

Updating Lock Screen from Windows Phone App

It is sometimes important for an application to change lock screen of the project. The Lock Screen can be set from an app only if the App supports an Extension to change lock screen. Let us take a look on how to change lock screen from an application.

First of all, Lock screen can be changed by an image from three locations :

1. Images located on app folder.
2. Images located on Internet.
3. Images coming from RSS.

The default lock screen size is 480px X 800px or 960px X 1708px.
Here are the steps to allow a program to change the lock screen.

1. In Solution Explorer right click on WMAppManifest.xml and open it with Text Editor.
2. Add lock screen extension to the application, without which the API to change the lock screen will not work.

      &lt;Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" /&gt;

Now to change the lock screen we need the following code.

private async void LockScreenChange(string filePathOfTheImage, bool isAppResource)
    if (!LockScreenManager.IsProvidedByCurrentApplication)
        await LockScreenManager.RequestAccessAsync();
        var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
        var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);

        var currentImage = LockScreen.GetImageUri();
        MessageBox.Show("Lock screen changed. Click F12 or go to lock screen.");
        MessageBox.Show("Background cant be updated as you clicked no!!");

Here in the code above, we first try to call LockScreenManager.IsProvidedByCurrentApplication. If this API returns true, the application is then capable of changing lock screen. We then go ahead and RequestAccessAsync on the Change background.

Finally we use LockScreen.SetImageUri with an url pointing to an image with specified resolution to change the lock screen of the Windows Phone environment.
The RequestAccessAsync will present you with a messagebox and upon clicking yes on the confirm, it will change the lock screen. The above screenshot is displayed when RequestAccessAsync is called form code.

The types of URL supported are :

ms-appx:/// for resources bundled within the .xap
ms-appdata:///local/ for local images within the root folder.

Hope this tip helps.

Thank you for reading