Thursday, 2 April 2015

How to calculate checksum using fileStream object in dotnet




Calculate checksum using fileStream object in dotnet


using System;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.IO.Abstractions;

namespace Helper.Utility
{

//Class CrcUtil.cs used get filestream using filepath for calculating checksum

    public class CrcUtil
    {
        private readonly IFileSystem _fileSystem;

        public CrcUtil(IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
        }

        public string GetCrcCode(string filePath)
        {
            try
            {
                using (var stream = _fileSystem.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    return GetCrcCode(stream);
                }
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in CrcUtil {0} for file {1}", ex.Message, filePath);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }

        public string GetCrcCode(Stream fileStream)
        {
            try
            {
                return Md5HashGenerator.GenerateKey(fileStream);
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in CrcUtil {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }
    }
//Class Md5HashGenerator.cs used for calculating checksum of passed filestream

    public class Md5HashGenerator
    {
        public static String GenerateKey(Stream sourceObject)
        {
            //Catch unuseful parameter values
            if (sourceObject == null)
            {
                throw new ArgumentNullException("sourceObject");
            }
            //We determine if the passed object is really serializable.
            try
            {
                //Now we begin to do the real work.
                var hashString = ComputeHash(sourceObject);
                return hashString;
            }
            catch (AmbiguousMatchException ame)
            {
                throw new ApplicationException(string.Format("Could not definitly decide if object is serializable. Message:{0}", ame.Message));
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in Md5HashGenerator {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }

        }

        private static string ComputeHash(Stream objectAsBytes)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            try
            {
                var result = md5.ComputeHash(objectAsBytes);
                // Build the final string by converting each byte
                // into hex and appending it to a StringBuilder
                var stringBuilder = new StringBuilder();
                foreach (var data in result)
                {
                    stringBuilder.Append(data.ToString("X2"));
                }

                // And return it
                return stringBuilder.ToString();
            }
            catch (ArgumentNullException)
            {
                //If something occured during serialization, this method is called with an null argument.
                // SsiLogger.Logger.Error("Hash has not been generated.");
                return null;
            }
            catch (Exception ex)
            {
                // SsiLogger.Logger.Error("Exception occured in Md5HashGenerator {0}", ex.Message);
                // SsiLogger.Logger.Debug(ex);
                throw;
            }
        }
    }
}


Friday, 27 February 2015

How to create relative path from absolute path in Web Application using environment variables


Windows Environment variables:
In C#, you could use windows environment variables for configuration.
   
In below example, "Testdata" is the folder which should be configured in windows “Program data” folder.
And exact location of Program data will be determined using C# Environment.ExpandEnvironmentVariables() method.


Setting in Web.Config or App.Config:

<add key="TestFolderPath" value="%Program Data%\Testdata" /> 

//Here "%ProgramData%\Testdata" is absolute path

Reading relative path:
var TestFolderPath= Environment.ExpandEnvironmentVariables(
ConfigurationManager.AppSettings[“TestFolderPath”])

//Output of TestFolderPath=> "C:\ProgramData\Testdata"
//For each machine this path may change based on “Program data” location.



Thursday, 12 February 2015

How to validate https request in WebAPI Application using dotnet


How to validate https request in WebAPI Application using dotnet

Steps:
·         Create request handler
·         Register requester handler


    //Request Handler to be used for Https check: HttpsGuard.cs
    //Supporting class used by Request Handler: IdentityStore.cs

 FileName: HttpsGuard.cs

    public class HttpsGuardDelegatingHandler
    {
        private IIdentityStore _identityStore { getset; }

        public HttpsGuard(IIdentityStore identityStore)
        {
            _identityStore = identityStore;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return ValidateRequest(request, cancellationToken);
        }

        public Task<HttpResponseMessage> ValidateRequest(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!_identityStore.isHTTPSRequest(request))
            {
                var reply = request.CreateErrorResponse(HttpStatusCode.BadRequest, ErrorCodes.InvalidRequestProtocol);
                return Task.FromResult(reply);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }



FileName: IdentityStore.cs

    public class IdentityStore : IIdentityStore
    {
        public bool isHTTPSRequest(HttpRequestMessage request)
        {
            return request.RequestUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
        }
    }


FileName: IIdentityStore.cs

    public interface IIdentityStore
    {       
        bool isHTTPSRequest(HttpRequestMessage request);
    }


FileName: WebApiConfig.cs

    //Register Request Handler in App_Start/WebAPIConfig.cs file
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.Routes.MapHttpRoute("DefaultApi""api/{controller}/{action}/{id}"new { id = RouteParameter.Optional });

            config.MessageHandlers.Add(new HttpsGuard(new IdentityStore())); //Global handler - applicable to all the requests
        }
    }
                                                                                                                           

Friday, 9 January 2015

Types of Certificates required for implementing certificate based communication in dotnet , webapi ,IIS


There are three types of certificates required for implementing certificate based authentication



     Certificate authority (CA) or provider:
·         It will installed in trusted root of both client as well as server


     Server certificate:
·         It should be from same CA as given in point one.
·         It should have public and private key.
·         It will be used on server side.



     Client certificate:
·         It should be from same CA as given in point one.
·         It should have public key.
·         It will be used on client side.



Also, Set Certificate Access Permissions for IIS On server for reading private keys using below steps: 
·         Type MMC in Run, It will open “ConsoleRoot”
·         Go to File menu option and select “Add remove snap in”
·         Select Certificates, click “Add”, select “My Computer” and click  “Finish”. This will open “Services” window.

·         Import Certificate authority certificate in Trusted Root Certification/Certificates using Services.

Tuesday, 20 May 2014

How to check undefined value in Jquery


Checking undefined value in Jquery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.
function A(val){
  if(typeof(val)  === "undefined")
    //do this
  else
   //do this
}


Monday, 12 May 2014

How to calculate browser’s client area using JavaScript, JQuery Function

How to calculate browser’s client area using JavaScript, JQuery Function


Function:
<script type="text/javascript">

function getBrowserHeightWidth(sType) {
        var myWidth = 0, myHeight = 0;
        try {
            if (typeof (window.innerWidth) == 'number') {
                //Non-IE
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                //IE 6+ in 'standards compliant mode'
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
        }
        catch (err) {
        }
        if (sType == 'H' || sType == 'h')
            return myHeight;
        else
            return myWidth;   
              
    }  
</script>

Set Div’s Height using getBrowserHeightWidth() Function
<script type="text/javascript">
$('#divPublishWindow').height(getBrowserHeightWidth('H'));
$('#divPublishWindow').width(getBrowserHeightWidth('w'));
</script>

HTML:
<div id="divPublishWindow">


</div>