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

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

Tuesday, May 30, 2017

Helping Hand for Flood Relief 2017

Helping Hand for Flood Relief 2017

Dear Friends,
It's time to get together and provide a helping hand to our flood affected brothers and sisters. 
We have planned to collect goods & money for this donation drive. You could contribute by supplying  
  • Baby products (milk powder, soap, diapers etc....), 
  • Clothes (New ones or used ones in very good condition), 
  • Sanitary napkins, 
  • Women's Underwear, 
  • Medicine (OTC) and dry rations 
(Items are ordered in the priority).

We are trying to find a transportation channel and we expect your cooperation on that too. 
Otherwise we'll hand over the goods to Rathmalana Air Force Camp or one of the donation programs arranged by radio channels.

Our collection center is at "Level 10, Access Towers, Union Place, Colombo 02

If it's hard for you to visit? us, 
you may transfer your donations to a bank account 
so that we purchases the above items from a wholesale agent in Fort. 
(Please request bank details.) 

We do share the updates and maintain 100% transparency of your donations.


Let's give them a hand.
The best way to find yourself is to lose yourself in the service of others. Mahatma Gandhi

Tuesday, January 17, 2017

Saving Bulk Records in SQL Server

Database operations are costly. Especially if we deal with big number of data. Sometimes even timeout may happen in your application.

There is a better way we can handle this from code level which we can use SqlBulkCopy class to insert bulk data into SQL Server Tables.

You can read more about SqlBulkCopy class here.

The "WriteToServer" method can be used with a DataTable filled with all your data from the application.

Lets get to work;
 DataTable dtFiles = new DataTable();  
 string _conStringRead = string.Empty;  
 string _strPathToScan = string.Empty;  
 _strPathToScan = ConfigurationManager.AppSettings["folderPath"]; // reading folderpath  
 _conStringRead = ConfigurationManager.ConnectionStrings["Read"].ConnectionString; //reading connection string from App.Config file  
 dtFiles.Columns.Add("lbFileName"); // Adding Column to DataTable  
 foreach (var file in Directory.EnumerateFiles(_strPathToScan, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName).ToList()) // Get files in folder  
           { //append them to DataTable  
             var toInsert = dtFiles.NewRow();  
             toInsert["lbFileName"] = file;  
             dtFiles.Rows.Add(toInsert);  
           }  
 using (SqlConnection sqlConRead = new SqlConnection(_conStringRead))  
           {//Bulk Insert  
              sqlConRead.Open();  
             var bulkCopy = new SqlBulkCopy(sqlConRead);  
             bulkCopy.DestinationTableName = "Your Table Name";  
             bulkCopy.ColumnMappings.Add("lbFileName", "lbFileName");  
             bulkCopy.WriteToServer(dtFiles);  
           }  

So the App.Config file looks like below;

 <connectionStrings>  
   <add name="Read" connectionString="Data Source=xxxx;Initial Catalog=DB;Persist Security Info=True;User ID=development;Password=development; Current Language=French;" providerName="System.Data.SqlClient"/>    
 </connectionStrings>  
 <appSettings>    
   <add key="folderPath" value="X:\FolderPath\"/>    
 </appSettings>  

Here I insert the list of files in the folder to a given table by matching it's columns with the DataTable columns at once. This is a great solution for dealing with large amount of data.

Try and you will enjoy this.

Happy Coding...