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

Sunday, May 10, 2020

Singleton: Are you doing it right?

"Tell us about a design pattern that you've used."

Probably one of the most asked questions in a programming interview. And the canned answer always happens to be "Singleton". Why? Because that's the easiest design pattern which you cannot go wrong with. Or is it?

If you don't remember what singleton code looks like, I don't blame you because I don't either. But after giving a little bit of thought, you might be able to come up with this:


Well, true it doesn't have all the bells and whistles like thread-safety and whatnot, but it's a good start. To be frank, I hate locks. It makes the code looking out of place. May be it's just me.

But I have to admit, thread syncing is crucial if you are serious about multi-threaded execution. And you might even want to use "double-checked locking" to favor performance. But what if we could get the same without using locks?


Notice that the above code makes use of how static type initialization works. Static type initialization is guaranteed to happen only once per AppDomian hence line 3 will be executed by the runtime only once, no matter how many threads asked for it.

So what's the caveat? Hmm, glad that you asked. Well, apparently you cannot guarantee when this initialization kicks off, so spawning of our singleton instance will not exactly be "lazy". In fact, it would even be initialized without the class being referred at all. Yikes! Can we fix it?

That's why we've slapped a static constructor in line 6. Mind you, you could've written the same code without it and it'll still work. But with that in place, the compiler generates IL code which fires the initializers in a more predictable fashion. Now the initialization would only happen whenever you refer the static class for the first time. But still, it's not ideal. At least in theory.

What if you have other static members in this class? They could get referred elsewhere and your singleton instance would be spawned prematurely. It's a valid case hypothetically. To circumvent this, you could add a nested static class only to hold your singleton instance and return it when needed. But that's overkill in my opinion. I'm pretty content with the above.

Ok, but can't we achieve this lazy behavior with something much more simple? Sure you can. Lazy<T> to the rescue!


This seems to be the most elegant solution of all. It has everything we tried to achieve: performance and laziness in one package. Have you coded your singletons like this? I have to confess that I have not. In fact, I've only used the style shown in the 2nd code snippet. But I'm looking forward to try out the Lazy<T> implementation when I get my next chance. probably you should give it a shot too. Cheers!

PS: One more thing to note before wrapping up. By using locks or static initialization, you are only making your "singleton instance initialization" thread-safe. It doesn't magically make your other instance methods that do the real productive work thread-safe. You'll need to handle those case by case, if they are prone to be problematic in multi-threaded environments. 

Monday, November 19, 2012

C#: Handling the “The remote host closed the connection” exception in WCF REST

In a recent project, I was involved in developing WCF Restful services for mobile clients. There were some services where the clients send files as multi-part POST requests. In some cases the file data parsing on the server fails due to missing form data fields or missing file data but those scenarios ended up throwing exception on the server. It was the most common communication exception 'The remote host closed the connection'.

The WCF method signature looked like this:
public bool SaveImage(Stream stream)

And inside the method, there is absolutely nothing special I am doing when parsing fails. I am returning true when parsing failed and false otherwise. But when it fails, it throws this exception for no reason.
After much of Googling, I found that when client is no longer connected to the service this exception may occur on the server. And the solution was to check Response.IsClientConnected property and act accordingly if its false. When I checked it, to my surprise it was false even when the method itself gets called! That is only when the parsing failed. So my conclusion was that the WCF infrastructure takes care of those requests which are not legit at the very beginning of its pipeline and releases the client to free its connection pool. But I still wonder why it passes the context to the method, if it is not willing to listen for the response.
So to fix this I added this method to my base service class:
protected bool IsClientConnected
{
    get { return HttpContext.Current.Response.IsClientConnected; }
}
In every method which takes in a Stream, I call this method and make sure client is still listening and return the response. So what do I return when client is not connected? Just null. This gets rid of getting the nasty 'remote host' exception and you can save you logs from overflowing with that.
Happy coding!
PS: The downside of using this method is that you have to use HttpContext which forces you to use AspNetCompatibilityRequirementsMode.Required, in your service which will prevent you from self-hosting it. But then again I don think clients would be disconnected in this fashion unless in that case. So I guess it's fair enough :)

Wednesday, February 29, 2012

C#: Exploring OpenSSL.NET

I am currently involved in a project module which involves a bit of cryptography. The basic requirements are:
  • Generating RSA key pair
  • Creating a CSR file
  • Generating a Checksum
  • Encrypting with private key
  • Reading a certificate file
  • Verifying a signature 
So while I was googling for hints, I came across this free library called OpenSSL.NET which looked promising. Find the code below which I use to accomplish the above tasks.

This function generates an RSA key pair and returns a CryptoKey object. The length of the keys are hard-coded to be 2048.
        /// <summary>
        /// Generates a 2048 bit RSA key pair.
        /// </summary>
        /// <returns>The key container</returns>
        public static CryptoKey GenerateRsaKeyPair()
        {
            using(var rsa = new RSA())
            {
                rsa.GenerateKeys(2048, 0x10021, null, null);
                return new CryptoKey(rsa);
            }
        }

The following function takes in a RSA key and creates a CSR file. I have used a DTO to pass in the additional details needed for the CSR generation.
        /// <summary>
        /// Generates a CSR file content according to the details given.
        /// </summary>
        /// <param name="csr">CSR details</param>
        /// /// <param name="key">RSA key</param>
        /// <returns>The CSR file content</returns>
        public static string GenerateCsr(CsrProperties csr, CryptoKey key)
        {
            using (var subject = new X509Name
                              {
                                  Country = csr.CountryName,
                                  Organization = csr.OrganizationName,
                                  OrganizationUnit = csr.OrganizationalUnitName,
                                  SerialNumber = csr.SerialNumber,
                                  Common = csr.CommonName
                              })
            {
                using (var req = new X509Request(0, subject, key))
                {
                    return req.PEM;
                }
            }
        }

For Checksum generation, which is also knowing as generating the hash, I used the following code. The algorithm was SHA256.
        /// <summary>
        /// Generates checksum using SHA256 algorithm.
        /// </summary>
        /// <param name="payLoad">Data to be used for hashing</param>
        /// <returns>The hash</returns>
        public static byte[] GenerateChecksum(byte[] payLoad)
        {
            using (var algo = new SHA256Managed())
            {
                return algo.ComputeHash(payLoad);
            }
        }

To do RSA encryption, I used .NET's native cryptography methods.
        /// <summary>
        /// Encrypts the data using RSA key.
        /// </summary>
        /// <param name="payLoad">Data to be encrypted</param>
        /// <param name="key">RSA key</param>
        /// <returns>The encrypted data</returns>
        public static byte[] Encrypt(byte[] payLoad, CryptoKey key)
        {
            using (var rsa = key.GetRSA())
            {
                return rsa.PrivateEncrypt(payLoad, RSA.Padding.PKCS1);
            }
        }

Well that's about it for now. I will update this with more functions as I move on.
Cheers!

Arduino Line Following Robot: Cracking the shortest/fastest path on a grid with loops

I'm sure you've created a line following robot at some point, if you've been exposed to Arduino (or any other programmable elec...