Monday, June 19, 2017

Device based Software Licensing in C#

There are many ways that a software can be protected and mostly by introducing a licensing key. It could probably be the oldest way. So let's make it work on our application too.

This time we generate a key based on PC configuration. As the matching key we can use our own encryption to send back the valid key.

It's simple, look at below.
 static void Main(string[] args)  
     {  
       StringBuilder sbKey =new StringBuilder();  
       ManagementClass mc = new ManagementClass("win32_processor");  
       ManagementObjectCollection moc = mc.GetInstances();  
       foreach (ManagementObject mo in moc)  
       {  
         sbKey.Append(mo.Properties["processorID"].Value.ToString());  
       }  
       Environment.GetLogicalDrives().ToList().FirstOrDefault();  
       string hddrive = Environment.GetLogicalDrives().ToList().FirstOrDefault() ?? "";  
       ManagementObject hddkey = new ManagementObject(@"win32_logicaldisk.deviceid=""" + hddrive[0] + @":""");  
       hddkey.Get();  
       sbKey.Append(hddkey["VolumeSerialNumber"].ToString());  
       string keyEncrypted = Encryption.Encrypt(sbKey.ToString());  
       Console.WriteLine("****************** Licensing Key Generator ******************");  
       Console.WriteLine();  
       Console.WriteLine(" Key : " + sbKey.ToString());  
       Console.WriteLine();  
       Console.WriteLine(" Encrypted Key : " + keyEncrypted);  
       Console.ReadLine();  
     }  

The output looks like;



For encryption & decryption, you can refer the older post here.

You can add and remove any values and make it hard to crack. This also can introduce to station based licensing because each license will apply only to one computer.

Happy coding...

Working with XML and LocalStorage in JavaScript & JQuery

We talked about XML in our previous post about how to generate and keep in LocalStorage for client side access.
Lets look at how we can deal with it from the browser using JavaScript and JQuery.
 $(document).ready(function(){  
   var swXmlDocumentAttrib = localStorage.getItem("swXmlDocumentAttrib");  
   var swXmlDocumentAttribJS = $.parseXML(swXmlDocumentAttrib);  
   $(swXmlDocumentAttribJS)      
        .find('AttributeItem')      
        .each(function(index, element){  
         var field = $(element)        
         var idConfigAttribute = field.find('idConfigAttribute').text()  
         var lbConfigAttribute = field.find('lbConfigAttribute').text()  
   });// end of swXmlDocumentAttribJS loop   
 });// end of document ready  

The LocalStorage is ready once the document is loaded.

localStorage.getItem
This will retrieve the stored item with the given key.

$.parseXML
Here we used JQuery to make it east to parse string to XML

AttributeItem
This is the item name

each(function(index, element)
Each item has it's elements with index. This is a loop that iterates until it finishes the document reach the end of items.

var idConfigAttribute = field.find('idConfigAttribute').text()
This get's the each element with matching key.

Like so, we can iterate through the XML and process it as needed. If further clarification is needed, post it via comments. I am happy to write back.

Happy coding...

Sunday, June 18, 2017

Creating XmlDocument in C# & Store in LocalStorage in JS

Mostly we work with data in code behind when developing web applications. Sometimes we do postbacks and reload pages. Sometimes we use AJAX and do partial page updates. Sometimes we don't like both of those but need to keep so much data in client side to access easily even if the network is disconnected.
Today we will see how we overcome this by creating XML document and store it in LocalStorage so that it can be accessed by client side scripts.

1. Create your own XML Document in Code Behind.
 XmlDocument xmlDocumentAttrib = new XmlDocument();  
       XmlDeclaration xmlDeclarationAttrib = xmlDocumentAttrib.CreateXmlDeclaration("1.0", "UTF-8", null);  
       XmlElement rootAttrib = xmlDocumentAttrib.DocumentElement;  
       xmlDocumentAttrib.InsertBefore(xmlDeclarationAttrib, rootAttrib);  
       XmlElement ConfigAttributeList = xmlDocumentAttrib.CreateElement(string.Empty, "ConfigAttributeList", string.Empty);  
       xmlDocumentAttrib.AppendChild(ConfigAttributeList);  
       foreach (var pa in this._Product.ConfigAttributeList)  
       {  
         if (attributeNotInList.Where(x => x.idConfigAttribute == pa.idConfigAttribute).FirstOrDefault() != null)  
           continue;  
         XmlElement AttributeItem = xmlDocumentAttrib.CreateElement(string.Empty, "AttributeItem", string.Empty);  
         ConfigAttributeList.AppendChild(AttributeItem);  
         XmlElement idConfig = xmlDocumentAttrib.CreateElement(string.Empty, "idConfigAttribute", string.Empty);  
         XmlElement lbConfig = xmlDocumentAttrib.CreateElement(string.Empty, "lbConfigAttribute", string.Empty);  
         XmlText idConfigAttributeText = xmlDocumentAttrib.CreateTextNode(pa.idConfigAttribute.ToString());  
         XmlText lbConfigAttributeText = xmlDocumentAttrib.CreateTextNode(pa.lbConfigAttribute);  
         idConfig.AppendChild(idConfigAttributeText);  
         lbConfig.AppendChild(lbConfigAttributeText);  
         AttributeItem.AppendChild(idConfig);  
         AttributeItem.AppendChild(lbConfig);  
 }  

this._Product
This is an object that holds the list of properties.
this._Product.ConfigAttributeList
This contains list of attributes that each one has it's ID and Name.

This peace of code will generate an XML document like below;


2. Now we need to append this to a string.
We use StringWriter and XmlWriter for this.
 var swXmlDocumentAttrib = new StringWriter();  
 using (var xmlTextWriter = XmlWriter.Create(swXmlDocumentAttrib))  
       {  
         xmlDocumentAttrib.WriteTo(xmlTextWriter);  
         xmlTextWriter.Flush();  
         swXmlDocumentAttrib.GetStringBuilder().ToString();  
       }  

The swXmlDocumentAttrib is containing the xml document created above.

3. Inject this to the client side using code behind.
 StringBuilder sbLocalStorage = new StringBuilder();  
 sbLocalStorage.Append("<script>");  
 sbLocalStorage.Append("if (typeof(Storage) !== \"undefined\") {");  
 sbLocalStorage.Append("localStorage.setItem('swXmlDocumentAttrib', '" + swXmlDocumentAttrib + "');");  
 sbLocalStorage.Append("} else { alert('does not support local storage'); }");  
 sbLocalStorage.Append("</script>");  
 Page.ClientScript.RegisterStartupScript(this.GetType(), "productLocalStorage", sbLocalStorage.ToString());  

This will alert if the browser doesn't support for LocalStorage.

localStorage.setItem
The setItem add the string value to the LocalStorage of the browser.

Page.ClientScript.RegisterStartupScript
RegisterStartupScript will register the script in HTML page.

In your client side scripting you can get this stored xml using getItem.

We will discuss further details of how we can deal with such XML from client side in upcoming posts.

Happy Coding...!

Tuesday, June 13, 2017

Working with JavaScript with C# - Single Quote Issue Fixed

Hi Guys,

After some busy days, Here I come again with a small problem I had and of course with the solution too.

Sometimes we have to build JavaScript within our code to inject it to the page. A declared variable for a string in JavaScript can't have a single quote because it gives an error at the end when we need it. This mostly happens with multilingual websites such as in french they use single quote a lot.

Look at the below c# method that can replace the single quote with JS friendly string.


In the same class we can use this as ;


It's simple. Next let's see how we use this to build a XML from C# and store it in JS Local Storage.

Happy coding...