Tag Archives: C#

How to enable sessions in Web API

Web API does not support native HTTP sessions. And it’s the nature of Web API, but there might be times you need HTTP sessions which resembles your bad design. Because a service framework should not support HTTP sessions as it should be a stateless element. So why do we need sessions in Web API ? I think you should not use sessions in Web API in production; eliminate HTTP sessions completely.

So the answer for the question why do we need sessions in Web API is, just to show how you can enable them. Silly though but you can use this in developing some POC and quick functional demos. Never use sessions in Web API because Web API is designed to be stateless.

First we should implement a ControllerHandler which is capable of handling sessions. In order make our ControllerHandler handle sessions we should implement IRequiresSessionState interface as well. Look at the below code.

   1: public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState

   2: {

   3:     public SessionableControllerHandler(RouteData routeData) 

   4:         : base(routeData)

   5:     {

   6:  

   7:     }

   8: }

The next step is to create a RouteHandler as a wrapper to the ControllerHandler we created, this is because when registering routes in the RouteTable we can pass RouteHandler types not ControllerHandler types. Look at the below code for the custom RouteHandler.

   1: public class SessionStateRouteHandler : IRouteHandler

   2: {

   3:     public IHttpHandler GetHttpHandler(RequestContext requestContext)

   4:     {

   5:         return new SessionableControllerHandler(requestContext.RouteData);

   6:     }

   7: }

Then finally we have to register our RouteHandler in the RouteTable

   1: RouteTable.Routes.MapHttpRoute(

   2:     name: "DefaultApi",

   3:     routeTemplate: "api/{controller}/{id}",

   4:     defaults: new { id = RouteParameter.Optional }

   5: ).RouteHandler = new SessionStateRouteHandler();

In order to make our custom route to be used we need to put it on top of other route registrations.

ObjectCache – Caching

In the ASP.NET domain all the state mechanisms can be considered as caching, both in the client side (view states, query strings, cookies) and in the server side (application state, session state and the Cache object itself.) You can define the classes and properties as static to get the effective functionality of caching. In ASP.NET the Cache object is HttpContext.Cache and .NET 4 introduced the ObjectCache to be used in non ASP.NET applications. This post will walk you through about the ObjectCache.    Learn about Windows Azure Caching.

ObjectCache

This is included in the System.Runtime.Caching assembly. MemoryCache is the concrete implementation of this library. The following method provides a quick glance on how ObjectCache can be used.

   1: public static void PutInCache(string key, object value)

   2: {

   3:     

   4:     var cache = MemoryCache.Default;

   5:     var policy = new CacheItemPolicy()

   6:     {

   7:         AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(5)),

   8:         Priority = CacheItemPriority.Default

   9:     };

  10:  

  11:     Console.WriteLine("Cache Size for the application in MB - {0}", cache.CacheMemoryLimit / ( 1024 * 1024) );

  12:     Console.WriteLine("{0}% cache memory is used.", (100 - cache.PhysicalMemoryLimit));

  13:  

  14:     cache.Remove(key);

  15:     

  16:     cache.Add(key, value, policy);

  17:  

  18:     int result = (int) cache.Get(key);

  19:     

  20: }

CacheMemoryLimit property gives the allocated cache memory for the specific instance of your application, where as PhysicalMemoryLimit give the unused space of the cache in percentage. When the cache memory  reaches beyond the CacheMemoryLimit then cache values are removed automatically, we can track this and take actions by registering a callback for the cache item removal.

Cache have 2 types of expiration policies. AbsoluteExpiration is the definite time after which there’s no guarantee for the item to be available in the cache memory, SlidingExpiration is where if there’re no access to the particular cache item within the specified time period there’s no guarantee for that item to be available. These 2 are very common and available in the HttpContext.Cache as well.

Cache has a priority which takes the value of the CachItemPriority enum. This enum has 2 values Default and Not Removable. Default is the default set up, means when you do not mention any value this would be applied. Default ensures the default behavior of the cache. Not Removable is used to instruct the system not to clear the values from the cache even when the system runs low in memory. These values should be cleared explicitly.

Windows server 2008 Core doesn’t support the ObjectCache and some Itanium implementations also do not support ObjectCache. Windows Server 2008 R2 with SP1 and later versions (including Windows 8.1) support ObjectCache.

SharePoint 2013 Item level Auditing

This post provides information about the item level auditing and how the server side object model works.

When you create site collection the auditing is not enabled by default. Each content database has a AuditData table to store the auditing information. You can enable the auditing at the site collection level through Site Settings => Site Collection Audit Settings. You can view the Audit Logs through Site Settings –> Audit Log Reports.

When no auditing is enabled and if you try to see / generate any of the available audit reports you will end up with a screen which says “Something went wrong”.

Now let’s walk through 2 scenarios to get some understanding about the SharePoint 2013 Item level Auditing.

Scenario 1 – No Auditing

image

Now in a clean new environment we will check the Audit status of the SPSite, SPWeb, SPList, SPListItem.

In the example we have a site collection and it has a Document Library names “AuditDocLib” and it has one document.

   1: private static void PerformAuditFeatureCheck()

   2: {

   3:     string url = @"http://singlespserver/";

   4:  

   5:     using(SPSite site = new SPSite(url))

   6:     {

   7:         var siteAuditFlags = site.Audit.AuditFlags;

   8:     

   9:         var topLevel = site.OpenWeb();

  10:         var topLevelAuditFlags = topLevel.Audit.AuditFlags;

  11:         

  12:         var sharedDocLib = topLevel.Lists.TryGetList("AuditDocLib");

  13:         var shareDocLibAuditFlags = sharedDocLib.Audit.AuditFlags;

  14:  

  15:         var doc1 = sharedDocLib.Items.GetItemById(1);

  16:         var doc1AuditFlags = doc1.Audit.AuditFlags;        

  17:  

  18:        }

  19: }

When we run the above code AuditFlags of the SPSite, SPWeb, SPList and SPListItem is None.

 

Scenario 2 – Enabling Audit for specific ListItem

image

Now we’ll enable the auditing for a specific document in the AuditDocLib.

   1: private static void EnableAuditForItem()

   2: {

   3:     string url = @"http://singlespserver/";

   4:  

   5:     using(SPSite site = new SPSite(url))

   6:     {

   7:         var topLevel = site.OpenWeb();

   8:         

   9:         var sharedDocLib = topLevel.Lists.TryGetList("AuditDocLib");

  10:         

  11:         // AuditFlag is None

  12:         var shareDocLibAuditFlags = sharedDocLib.Audit.AuditFlags;

  13:  

  14:         var doc1 = sharedDocLib.Items.GetItemById(1);

  15:         

  16:         // AuditFlag is None

  17:         var doc1AuditFlags = doc1.Audit.AuditFlags;        

  18:  

  19:         //enabling auditing for the item

  20:         doc1.Audit.AuditFlags = SPAuditMaskType.View;

  21:         doc1.Audit.Update();

  22:     }

  23: }

Now doc1 is audit enabled. And in the Audit Log Reports we can get the Audits. Below image shows the screen shot of the audit report after viewing the doc1 for few times. image

Notice that the report also has the log entries for the Library (AuditDocLib). It is obvious that if a person want to view an item in the library more often he/she has to navigate to the corresponding List/Library and view the Item. But we didn’t specify to audit the Library; in the code the AuditMask is set only for the item.

Again we’ll run the PerformAuditFeatureCheck method to check the AuditFlags

 image

You can see that the AuditFlags for the AuditDocLib is still None. This is because AuditFlags were not set for the AuditDocLib explicitly beacuse there’s no <NewAuditMask>4</NewAuditMask> event against the AuditDocLib.

This also hints us a point that just by retrieving the AuditFlags of a List / Library through the object model doesn’t give you the full insight of whether the particular List / Library is being audited. AuditFlags property gives the value of the last explicitly set AuditMask.

C# – implicit & explicit keywords

What are the uses of the implicit and explicit keywords in C#.

implicit is used when we need implicit conversions between types. It works on value types and as well on reference types.

The below code shows the use of implicit keyword. Create a class named Digit as below and note the two static methods with implicit keyword.

   1: class Digit

   2: {

   3:     public double val;

   4:     

   5:     public Digit(double d)

   6:     {

   7:         val = d;

   8:     }

   9:  

  10:     public static implicit operator double(Digit d)

  11:     {

  12:         return d.val;

  13:     }

  14:  

  15:     public static implicit operator Digit(double d)

  16:     {

  17:         return new Digit(d);

  18:     }

  19:  

  20: }

Since the Digit class has both the Digit to double conversion and the double to Digit conversion implicit functions defined, it is safe to do the following.

   1: Digit dig = new Digit(7);

   2:  

   3: //This call invokes the implicit "double" operator 

   4: double num = dig;

   5: //This call invokes the implicit "Digit" operator

   6: Digit dig2 = 12;

Same works on complete reference types as well. Look at the following example.

   1: class Animal

   2: {

   3:     public string  Family { get; set; }

   4:  

   5:     public static implicit operator Dog(Animal animal)

   6:     {

   7:         return new Dog() { Breed = animal.Family };

   8:     }

   9:  

  10:     public static implicit operator Animal(Dog d)

  11:     {

  12:         return new Animal() { Family = d.Breed };

  13:     }

  14: }

  15:  

  16: class Dog

  17: {

  18:     public string Breed { get; set; }

  19: }

These following conversions are possible.

   1: Animal a = new Animal() { Family = "Golden Retriever" };

   2: Dog d1 = a;

   3: a = d1;

 

explicit keyword does the right opposite, where we have to explicitly cast the one type to the other. Say we’ve a set of classed like this.

   1: class WaterCleaner

   2: {

   3:     public string Name;

   4: }

   5:  

   6: class RoboticCleaner

   7: {

   8:     public string Name;

   9:  

  10:     public static explicit operator WaterCleaner(RoboticCleaner r)

  11:     {

  12:         return new WaterCleaner() { Name = r.Name };

  13:     }

  14:  

  15:     public static explicit operator RoboticCleaner(WaterCleaner w)

  16:     {

  17:         return new RoboticCleaner() { Name = w.Name };

  18:     }

  19: }

Then you should do the explicit casting like this.

   1: RoboticCleaner rc = new RoboticCleaner() { Name = "Super Cleaner" };

   2: WaterCleaner wc = (WaterCleaner)rc;

 

If RoboticCleaner has implicit conversion defined then you don’t need the explicit conversion.

Now the question is what if the RoboticCleaner class has both implicit and explicit conversions defined.

Now your RoboticCleaner should be like this.

   1: class RoboticCleaner

   2: {

   3:     public string Name;

   4:  

   5:     public static explicit operator WaterCleaner(RoboticCleaner r)

   6:     {

   7:         return new WaterCleaner() { Name = r.Name };

   8:     }

   9:  

  10:     public static explicit operator RoboticCleaner(WaterCleaner w)

  11:     {

  12:         return new RoboticCleaner() { Name = w.Name };

  13:     }

  14:  

  15:     public static implicit operator WaterCleaner(RoboticCleaner r)

  16:     {

  17:         return new WaterCleaner() { Name = r.Name };

  18:     }

  19: }

Then the compiler gets confused and shows this message. (click on the image to enlarge)

image

HTTP Headers

This is a quick and a small post on reading the HTTP headers in ASP.NET. Code gets the HTTP header key – value pairs and write it to a text file.

   1: protected void Page_Load(object sender, EventArgs e)

   2: {

   3:     var headers = Request.Headers;

   4:     StreamWriter writer = new StreamWriter(Server.MapPath("~/data.txt"));

   5:  

   6:     foreach (var item in headers.AllKeys)

   7:     {

   8:         string data = item + "---" + headers[item];              

   9:         writer.WriteLine(data);

  10:     }

  11:  

  12:     writer.Flush();

  13:     writer.Close();

  14: }

Output text file as follows.

   1: Connection---Keep-Alive

   2: Accept---text/html, application/xhtml+xml, */*

   3: Accept-Encoding---gzip, deflate

   4: Accept-Language---en-US

   5: Host---localhost:24859

   6: User-Agent---Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

AES Cryptography

Contains the code for AES encryption and decryption in C#.

   1: public byte [] EncryptText(string plainData)

   2:         {

   3:             RijndaelManaged rij = new RijndaelManaged();

   4:             

   5:             rij.GenerateKey();

   6:             _key = rij.Key;

   7:  

   8:             rij.GenerateIV();

   9:             _intializationVector = rij.IV;

  10:  

  11:             ICryptoTransform encryptor = rij.CreateEncryptor(_key, _intializationVector);

  12:  

  13:             using (MemoryStream msEncrypt = new MemoryStream())

  14:             {

  15:                 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

  16:                 {

  17:                     using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))

  18:                     {

  19:                         swEncrypt.Write(plainData);

  20:                     }

  21:  

  22:                     return msEncrypt.ToArray();

  23:                 }

  24:             }

  25:  

  26:         }

  27:  

  28:  

  29:         public string  DecryptText(byte [] encrytedData)

  30:         {

  31:             RijndaelManaged rij = new RijndaelManaged();

  32:  

  33:             ICryptoTransform decryptor = rij.CreateDecryptor(_key, _intializationVector);

  34:  

  35:             using (MemoryStream msDecrypt = new MemoryStream(encrytedData))

  36:             {

  37:                 using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

  38:                 {

  39:                     using (StreamReader srDecrypt = new StreamReader(csDecrypt))

  40:                     {

  41:                         return srDecrypt.ReadToEnd();

  42:                     }

  43:                 }

  44:             }

  45:         }

  46:         

  47:     }

UI Updates – Part 2

ASP.NET

ASP.NET UI updates are handles using Ajax. In this example it is described how to use the ASP.NET Ajax for the updates.

In ASP.NET Ajax we can have update panel and make the updates via Ajax calls. Prepare your ASPX markup like below.

   1: <body>

   2:     <form id="form1" runat="server">

   3:         <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

   4:         

   5:         <div>

   6:             <asp:Button ID="BtnPostback" runat="server" Text="PostBack" OnClick="BtnPostback_Click" />

   7:         </div>

   8:  

   9:         <div>

  10:             <asp:UpdateProgress ID="UpdateProgress1" runat="server">

  11:                 <ProgressTemplate>

  12:                     <asp:Label Text="Working..." ID="LblBusyIndicator" runat="server"></asp:Label>

  13:                 </ProgressTemplate>

  14:             </asp:UpdateProgress>

  15:         </div>

  16:  

  17:         <div>

  18:             <asp:UpdatePanel ID="UpdatePanel1" runat="server">

  19:                 <ContentTemplate>

  20:                     <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

  21:                 </ContentTemplate>

  22:                 <Triggers>

  23:                     <asp:AsyncPostBackTrigger ControlID="BtnPostback" />

  24:                 </Triggers>

  25:             </asp:UpdatePanel>

  26:         </div>

  27:  

  28:     </form>

  29: </body>

Code behind..

   1: private void PerformTask()

   2: {

   3:     // job time 4 - 10 seconds

   4:     int time = new Random().Next(4, 11);

   5:     Thread.Sleep(1000 * time);

   6:     Label1.Text = String.Format("Hello from worker - ran for {0} seconds", time);

   7: }

   8:  

   9:  

  10: protected void BtnPostback_Click(object sender, EventArgs e)

  11: {

  12:     PerformTask();

  13: }

 

Silverlight

Silverlight the platform itself is asynchronous. And we can have the same mechanism we used in WPF for the UI updates, but little different.

Read the Silverlight Dispatcher for the Silverlight UI updates

UI Updates – Part 1

Updating the UI is a problem and it is tricky. There are very few simple rules to follow. Let’s see Here we’ll see  some smart ways to perform UI updates on Console applications, Windows Forms, WPF, ASP.NET, Silverlight, Windows Phone and Windows Store apps.

Console Applications

Do they have UI ? No. But we’ll check how different threads perform updates on Console applications. Look at the following code. It has a main thread and another thread (worker thread) perform some time consuming task and updates the UI. Main thread shows a rotating bar till the worker thread completes.

   1: class Program

   2:     {

   3:         static void Main(string[] args)

   4:         {

   5:             Console.WriteLine("Application Start");

   6:             Thread worker = new Thread(PerformTask);

   7:  

   8:             worker.Start();

   9:  

  10:             ShowConsoleWaitAnimation(worker);

  11:  

  12:             Console.WriteLine("Application End");

  13:             Console.ReadKey();

  14:  

  15:         }

  16:  

  17:  

  18:         private static void PerformTask()

  19:         {

  20:             // job time 4 - 10 seconds

  21:             int time = new Random().Next(4,11);

  22:             Thread.Sleep(1000 * time);

  23:             Console.WriteLine("Hello from worker - ran for {0} seconds",time);

  24:         }

  25:  

  26:  

  27:         private static void ShowConsoleWaitAnimation(Thread thread)

  28:         {

  29:             while (thread.IsAlive)

  30:             {

  31:                 Console.Write("Processing - /\r");

  32:                 Thread.Sleep(100);

  33:                 Console.Write("Processing - -\r");

  34:                 Thread.Sleep(100);

  35:                 Console.Write("Processing - \\\r");

  36:                 Thread.Sleep(100);

  37:                 Console.Write("Processing - |\r");

  38:                 Thread.Sleep(100);

  39:             }

  40:         }

  41:     }

 

Windows Forms

Look at the below code. In a simple Windows Forms application, for a button click event, a time consuming task runs in a separate thread and tries to update a Label control.

   1: private void BtnStartWork_Click(object sender, EventArgs e)

   2: {

   3:     Thread worker = new Thread(PerformTask);

   4:     worker.Start();

   5: }

   6:  

   7: private void PerformTask()

   8: {

   9:     // job time 4 - 10 seconds

  10:     int time = new Random().Next(4, 11);

  11:     Thread.Sleep(1000 * time);

  12:     LblStatus.Text = String.Format("Work completed - ran for {0} seconds", time);

  13: } 

 

When you run the above code, you will get this famous Exception. Because the Label control is created in UI thread and our worker thread tries to reach it. Cross thread referencing cannot happen as this is a violation of operating system thread handling policies. ( Do not mistake the cross thread communication and cross thread referencing, cross thread communication can happen among threads)

image

There are plenty of solutions for this problem, but the ready made one is to use BackgroundWorker class. The below code shows how you can use BackgroundWorker class and perform UI updates and also shows a progress bar on the UI. Events are coded inline to reduce the number of methods for this small demo.

   1: public partial class Form1 : Form

   2: {       

   3:        private BackgroundWorker _bgWorker = new BackgroundWorker();

   4:        private string _result = String.Empty;

   5:  

   6:        public Form1()

   7:        {

   8:            InitializeComponent();

   9:        }

  10:  

  11:        private void BtnStartWork_Click(object sender, EventArgs e)

  12:        {

  13:            _bgWorker.WorkerReportsProgress = true;

  14:  

  15:            _bgWorker.DoWork += (s, ev) =>

  16:                {

  17:                    _result = PerformTask();

  18:                };

  19:            

  20:            _bgWorker.ProgressChanged += (s, ev) =>

  21:                {

  22:                    workerProgressBar.Value = ev.ProgressPercentage * 100;

  23:                };

  24:  

  25:            _bgWorker.RunWorkerCompleted += (s, ev) =>

  26:                {

  27:                    LblStatus.Text = _result;

  28:                };

  29:  

  30:            _bgWorker.RunWorkerAsync();

  31:        }

  32:  

  33:  

  34:        private string PerformTask()

  35:        {

  36:            // job time 4 - 10 seconds

  37:            int time = new Random().Next(4, 11);

  38:            int fullTime = time;

  39:  

  40:            while (time >= 0)

  41:            {

  42:                Thread.Sleep(1000);

  43:                _bgWorker.ReportProgress(1 - (time / fullTime));

  44:                time--;

  45:            }

  46:  

  47:            return String.Format("Work completed - ran for {0} seconds", fullTime);

  48:         }

  49:           

  50: } 

 

WPF

In WPF we can use the BackgroundWorker, but also there’s a well refined solution in the WPF is to use the Dispatcher object. WPF model has Dispatcher object common across all the controls. So we can use this to update the UI.

Little modification in the PerformTask() and make it return the result.

   1: private string PerformTask()

   2: {

   3:     // job time 4 - 10 seconds

   4:     int time = new Random().Next(4, 11);

   5:     int fullTime = time;

   6:  

   7:     Thread.Sleep(time);      

   8:  

   9:     return String.Format("Work completed - ran for {0} seconds", fullTime);

  10: } 

Button click event.

   1: private void BtnWork_Click(object sender, RoutedEventArgs e)

   2: {

   3:     Thread thread = new Thread(() =>

   4:         {

   5:             string result = PerformTask();

   6:             Dispatcher.Invoke(() =>

   7:                 {

   8:                     TxtStatus.Text = result;

   9:                 });

  10:         });

  11:     thread.Start();

  12: }

Part 2 – will discuss about UI updates in ASP.NET and Silverlight.