Monday, April 15, 2013

GzipStream To Byte Array

public static string Compress(this string s)
    {
        byte[] bytesToEncode = Encoding.UTF8.GetBytes(s);
        return Convert.ToBase64String(bytesToEncode.Compress());
    }

public static byte[] Compress(this byte[] bytesToEncode)
    {
        using (MemoryStream input = new MemoryStream(bytesToEncode))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress))
            {
                input.CopyTo(zip);
            }
            return output.ToArray();
        }
    }



public static string Explode(this string s)
    {
        byte[] compressedBytes = Convert.FromBase64String(s);
        return Encoding.UTF8.GetString(compressedBytes.Explode());
    }

public static byte[] Explode(this byte[] compressedBytes)
    {
        using (MemoryStream input = new MemoryStream(compressedBytes))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
            {
                zip.CopyTo(output);
            }
            return output.ToArray();
        }
    }

Tuesday, April 9, 2013

Sql Server ConnectionTimeout vs CommandTimeout


ConnectionTimeout a property of Connection class in ADO.NET, is the time you would wait, for connecting to a given database, before flagging a connection failure. Default value is 30 seconds.
new SqlConnection().ConnectionTimeout = 10;
CommandTimeout a property of the Command class in ADO.NET, is the time you would wait, for a command (query, stored procedure, etc.) to return result set, before flagging an execution failure. Default value for CommandTimeout too is 30 seconds.
new SqlConnection().CreateCommand().CommandTimeout = 10;
Unlike ConnectionTimeout which are part of connection string, command timeouts are defined separately (hardcoded or as appSettings). Setting both of them to 0 (zero) would result in indefinite wait period which is generally considered a bad practice. You ideally want to set both of them to in accordance to your performance SLAs. Though at times, while running data heavy background jobs / workflows you may want to set your CommandTimeout to a larger value.