Monday, May 7, 2012

Convert to Base64

Base64 encoding used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

Below way of conversion to Base64 using csharp or javascript:
Conversion from/to base64 using csharp:
    static public string EncodeTo64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }

    static public string DecodeFrom64(string encodedData)
    {
      byte[] encodedDataAsBytes
          = System.Convert.FromBase64String(encodedData);
      string returnValue =
         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
      return returnValue;
    }


Conversion from/to base64 using javascript:
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
        Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = Base64._keyStr.indexOf(input.charAt(i++));
        enc2 = Base64._keyStr.indexOf(input.charAt(i++));
        enc3 = Base64._keyStr.indexOf(input.charAt(i++));
        enc4 = Base64._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }
    return string;
}
}

Also there is jquery library for base64:
https://github.com/carlo/jquery-base64

Serialization in Silverlight

When I want to serialize/deserialize class in silverlight 4/5, I found XmlSerializeris not supported.

We can use class DataContractSerializer which is supported by silverlight. Below methods using DataContractSerializer to serialize/deserialize classes:

Serialize method:

        public string Serialize<T>(T data)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(typeof (T)); 
                serializer.WriteObject(memoryStream, data);

                memoryStream.Seek(0, SeekOrigin.Begin);

                var reader = new StreamReader(memoryStream);
                string content = reader.ReadToEnd();
                return content;
            }
        }

Deserialize method: 



        public T Deserialize<T>(string xml)
        {
            using( var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)) )
            {
                var serializer = new DataContractSerializer(typeof (T));
                T theObject = (T)serializer.ReadObject(stream);
                return theObject;
            }
        }

Thursday, April 26, 2012

How can you create Multiple instances of same windows service

Many times you want to create windows service with multiple instances in the same server. We must create windows service with different name for each instance.

You can add parameters for different configuration of windows service when you try to install.

Here is an example of installing windows service:
installutil -i /name=LinkDevSch2 /account=localsystem LinkDev.Timer.Service.exe
Here is an example of uninstalling windows service:
installutil /u /name=LinkDevSch1  LinkDev.Timer.Service.exe

You can use these parameters to modify server name, way of authentication. the ProjectInstaller has 4 methods you can override OnBeforeInstall, OnBeforeunInstall, Install, and Uninstall which enables us to make changes to the service installer at the at run time.

  
     public string GetContextParameter(string key)
     {
            string sValue = "";
            try
            {
                sValue = this.Context.Parameters[key].ToString();
            }
            catch
            {
                sValue = "";
            }
            return sValue;
     }


      protected override void OnBeforeInstall(IDictionary savedState)
      {
          
            base.OnBeforeInstall(savedState);

            bool isUserAccount = false;
          
            // Decode the command line switches
            string name        = GetContextParameter("name");
            serviceInstaller.ServiceName = name;

            // What type of credentials to use to run the service
            // The default is User
            string acct        = GetContextParameter("account");
          
            if (0 == acct.Length) acct = "user";

            // Decode the type of account to use
            switch (acct)
            {
                case "user":
                    processInstaller.Account = System.ServiceProcess.ServiceAccount.User;
                    isUserAccount = true;
                    break;
                case "localservice":
                    processInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
                    break;
                case "localsystem":
                    processInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
                    break;
                case "networkservice":
                    processInstaller.Account = System.ServiceProcess.ServiceAccount.NetworkService;
                    break;
                default:
                    processInstaller.Account = System.ServiceProcess.ServiceAccount.User;
                    isUserAccount = true;
                    break;
            }

            // User name and password
            string username = GetContextParameter("user");
            string password = GetContextParameter("password");

            // Should I use a user account?
            if (isUserAccount)
            {
                // If we need to use a user account, set the user name and password
                processInstaller.Username = username;
                processInstaller.Password = password;
            }
        }


        protected override void OnBeforeUninstall(IDictionary savedState)
        {
            base.OnBeforeUninstall(savedState);

            // Set the service name based on the command line
            serviceInstaller.ServiceName = GetContextParameter("name");
        }

Now you can created NET Windows Service with multiple instance any time you want.

Tuesday, April 24, 2012

Tips Comment ASPNET Controls

Some times ASPNET Developer do mistake by commenting server controls
as html comment like below:
<!--<aspnet:TextBox runat="server" id="txt"/>

-->

This comment will affect only by rendering tags as commented html, but doesn't affect its server side events and validations. which
will cause many problems. It is displaying sensitive information, it is vulnerable to cross-site scripting,  failure in firing some scripts like script validation, unexpected behaviour of scripts, and render unwanted tags(affect the performance).

To ignore any of the above problems use server side:
<%--<aspnet:TextBox runat="server" id="txt"/>

--%>

Sunday, April 22, 2012

Allow WCF multiple Binding on IIS

IIS supports specifying multiple IIS bindings per site. A WCF service hosted under a site allows binding to only one baseAddress per scheme.
I want to host service with multiple binding without custom factories.
http://seesaudi.com, http://seesaudimor.com

I found solution:
Solution in .Net 3.5:
Set the baseAddressPrefix to one of the addresses:


        <system.serviceModel>
        <serviceHostingEnvironment>
        <baseAddressPrefixFilters>
                <add prefix="http://seesaudi.com"/>    
        </baseAddressPrefixFilters>
        </serviceHostingEnvironment>
        </system.serviceModel>

  1. Set the endpoints in your web.config file to be absolute URIs:

  2.    <services>
          <service>
            <endpoint address="http://seesaudi.com/Service1.svc/e1"  Binding="..." Contract="..." />
           <endpoint address="http://seesaudimor.com/Service1.svc/e2"  Binding="..." Contract="..." />
          </service>
       </services>
Solution in .Net 4.0: 
  In order to enable multiple site binding, you need to set multipleSiteBindingEnabled to true in your application.

   <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  

Thursday, April 19, 2012

Silverlight Designer Error

Silverlight Problem in Design Mode:

When Created Control in Silverlight I found error in design mode:


System.Reflection.TargetInvocationException

[Async_ExceptionOccurred]Arguments: Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.50401.0&File=System.dll&Key=Async_ExceptionOccurred


After many invesigation I discovered I used HtmlPage object (Need browser to execute this line of code).
To fix this didn't execute Html object in design mode example:


if (!DesignerProperties.IsInDesignTool)
{
var height = HtmlPage.Document.Body.GetProperty("clientHeight");
var width = HtmlPage.Document.Body.GetProperty("clientWidth");
this.LayoutRoot.Width = double.Parse(width.ToString());
this.LayoutRoot.Height = double.Parse(height.ToString());
}

Sunday, March 25, 2012

System Center Service Manager 2012 Arabic Portal

It is a second time I worked in arabization of SCM Portal. It is easier than previous version because it is built in silver-light and separate UI layer and business layer.

Below video of SCM arabization: