Tuesday, February 26, 2019

Http TLS Support for Legacy framework

   Recently i faced issue to make http call to WebAPI which is supporting latest TLS12 or TLS11. But our client project framework uses .net 4.0 so it not support by default. To resolve this issue added below code (constructor of API or global level)


 //Setting supported security protocol

   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)((SslProtocols)0x00000C00) | (SecurityProtocolType)((SslProtocols)0x00000300);



Here 

(SecurityProtocolType)((SslProtocols)0x00000C00) is equivalent to Tls12
(SecurityProtocolType)((SslProtocols)0x00000300) is equivalent to Tls11



Ref: https://support.microsoft.com/en-us/help/3154520/support-for-tls-system-default-versions-included-in-the-net-framework 

Monday, December 24, 2018

Retrieve MimeType by its extension

In file IO, we need to set content/type while downloading it and this should be dynamically set by file's extension. Here is code we can use to do the same

Create static class to store all available mime-type, here am showing few only, we can add more.


public static class MimeTypesHelper
        {
            public const string
            Doc = "application/msword",
            Docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            Xls = "application/vnd.ms-excel",
            Xlt = "application/vnd.ms-excel",
            Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Ppt = "application/vnd.ms-powerpoint",
            Pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            Pdf = "application/pdf",
            Zip = "application/zip";


            //get matched mime type by extension, so property name should be equals to file extension
            public static string GetMimeTypeByExtension(string extension)
            {
                //remove period in extension
                extension = extension?.Replace(".", "");
                //match mimetype by property
                string matchedMimeType = typeof(MimeTypes).GetField(extension, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)?.GetValue(null)?.ToString();

                //if there is no match default to octet stream
                if (string.IsNullOrEmpty(matchedMimeType))
                {
                    matchedMimeType = "application/octet-stream";
                }

                return matchedMimeType;
            }
        }


Call this method to retrieve your file mimetype

 Response.ContentType = MimeTypesHelper.GetMimeTypeByExtension(".pdf");   //this will return "application/pdf"