Tuesday, January 29, 2019

Get selected value of a dropdown without ID

As the headline is short, the work is simple. Look at the following code

$('select').on('change', function () {         
            var ttMailActorTo = $('option:selected', this).attr('ttMailActorTo');
            if (isEmail(ttMailActorTo))
                $('#ttMailActorTo').val(ttMailActorTo);
});

It binds the change function to all select on the page and get the special attribute value "ttMailActorTo" and append it to a hidden field "ttMailActorTo".

Simple as that. Enjoy.

Wednesday, August 9, 2017

Custom Duration Reminder in C#

It's a common issue that most software developers sit for long time and forget to move around. So here is a timer created for reminding them with a ugly sound clip. :)
The existing features are;

1. Time is configurable
2. Minimize to System Tray




Download the Setup file here.
https://www.dropbox.com/s/4ew1y6w56yemkhn/TRDReminder.zip?dl=0


Monday, July 24, 2017

SQL Function to Split String into a List

Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e. no INSERT or UPDATE statements allowed).
A Function can be used inline in SQL Statements if it returns a scalar value or can be joined upon if it returns a result set.
This explanation is copied from stackoverflow.com to understand the differences of using SQL Functions.

So let's get to the headline. Yes we sometimes need to pass a list of values and get them split from a given delimiter. Especially we can use such function to join with other queries to do the job easier and faster. Look at the following.

To do so, first we maintain a sequence table that has sequential numbers starting from 1.
 CREATE TABLE tblSequence (  
      [id] [int] NOT NULL  
 ) ON [PRIMARY]  
 GO  

And now let's add some sequential numbers to it. For the moment we assume the max would be 8000.
 Declare @i int  
 Select @i = 1  
 While @i <= 8000  
 Begin  
      insert into tblSequence(id) values (@i)  
      if @@error <> 0 Break  
      Select @i = @i + 1  
 End  
 go  

It's time to use this table and create our function.

 CREATE FUNCTION tblListSplit(@ListId varchar(8000),@d char(1))  
 RETURNS TABLE  
 AS  
 RETURN (  
      SELECT  
           row_number() OVER(ORDER BY id) id,  
           NullIf(rtrim(ltrim(SubString(@d + @ListId + @d, id, CharIndex(@d, @d + @ListId + @d, id) - id))), '') Val  
      FROM tblSequence (NOLOCK)  
      WHERE id <= Len(@d + @ListId + @d)  
      AND     SubString(@d + @ListId + @d, id - 1, 1) = @d  
      AND     CharIndex(@d, @d + @ListId + @d, id) - id > 0  
 )  
 GO  

Now the function is ready to serve us as needed. Let's try it.
 select * from tblListSplit('1,2,3,4,5,6,7,8,9,10',',')  

And the result will be like;
















So, you can see the list is split according to the delimiter we pass and here we used a comma. Try it with all your needs in your procedures.
Happy Coding..!!!



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...!