Thursday, October 13, 2016

Convert dates to MM/dd/yyyy format


C# function that converts different date formats to MM/dd/yyyy



In my database, there was a date formatting problem. Dates were stored in the following formats M/d/yyyy (eg. 9/9/2009) , M/dd/yyyy (e.g. 9/09/2009), MM/d/yyyy (e.g. 09/9/2009) and MM/dd/yyyy (e.g. 09/09/2009). This was a problem especially since we required the user to enter their date of birth at the time of first login. Therefore, I created the above function to convert all dates to the MM/dd/yyyy format. 

Sunday, August 14, 2016

Coding problems to refresh your brain

Coding problems that I have come across recently:

1. Add two simple mathematical expressions which are of the form Axa + Bxb + ...

2. Print nth number of Fibonacci series using iterative loop.

3. Iterate and print every element of a n-child binary tree

4. Dollar Words:

acalephe
acclimatizable
acclimatizer
acclimatizers
accorage

Using a C# console application, give each letter in each word a numerical value equal to its position in the alphabet.  So "a" is 1 and "z" is 26.  Punctuation and whitespace is 0.  Find words where the sum of the value of the letters is 100 and print each of the “100” words on the console.

5. In the programming language of your choice, write a method that modifies a string using the
following rules:

- Each word in the input string is replaced with the following: the first letter of the word, the count of
distinct letters between the first and last letter, and the last letter of the word. For
example, “Automotive parts" would be replaced by "A6e p3s".
- A "word" is defined as a sequence of alphabetic characters, delimited by any non-alphabetic
characters.
- Any non-alphabetic character in the input string should appear in the output string in its original
relative location

6 a)An array contains 0s and 1s. Write a function to sort all the 0s to the left and the 1s to the right.
b) Check if array is sorted i.e. if all the 0s are to the left and 1s are to the right.

7. Convert date strings in the following formats  'M/d/yyyy' , 'MM/d/yyyy', 'M/dd/yyyy' to 'MM/dd/yyyy'.  This is a real life problem that I had to fix for the dates in my company's database.

Sunday, June 19, 2016

How reference types are passed to functions

I used to have this confusion about what exactly happens when reference types are passed by value to functions till recently. Let me illustrate what I have learnt since then with a few examples:

           static void Main(string[] args)
        {
            string s = "UNITED";
            ChangeString(s);
            Console.WriteLine(s);

            StringBuilder a = new StringBuilder("UNITED");
            ChangeSb(a);
            Console.WriteLine(a);
            Console.Read();
     
       }  
        private static void ChangeString(string s1)
        {
         
            s1 += "STATES";
        }

    private static void ChangeSb(StringBuilder a1)
        {
            a1.Append("STATES");
        }

Output:
UNITED
UNITEDSTATES

Explanation:
So reference types always contain the memory location of the data and not the actual data itself. In the above example s will contain the memory location where 'United' is stored . And then when ChangeString(s) the new variable s is assigned the same memory location that contains 'United'. However when 'States' is appended to it, since string are immutable, a new string is created which contains the memory location of the word 'States'. Therefore, when we output s we still get 'United' since the original variable is untouched. For this example, lets assume the entire word is stored at that memory location because it is not important.



In the case of the StringBuilder a, it again points to the memory location where 'United' is stored. When ChangeSb(a) is called, the new StringBuilder contains the memory location where 'United' is stored.

When "States" is appended to it, the memory location will now contain "United States". A new location is not used since StringBuilders are not immutable.

And another example:

         static void Main(string[] args)
        {
            string s = "UNITED";
            ChangeString(s);
            Console.WriteLine(s);

            StringBuilder a = new StringBuilder("UNITED");
            ChangeSb(a);
            Console.WriteLine(a);
            Console.Read();
      }
     
   
        private static void ChangeString(string s)
        {
             s = "STATES";
       
        }

  private static void ChangeSb(StringBuilder a)
        {
            a = new StringBuilder("STATES");
         
        }


Output:
UNITED
UNITED

Saturday, May 21, 2016

JSON using JavaScriptSerializer in C#

I had to work with JSON recently to integrate the Payeezy gateway to our website. First time I used the dynamic type in C#. Below is the code I used to create the JSON:



 dynamic payload = new
        {
            merchant_ref = "Payeezy Token test",
            transaction_type = "purchase",
            method = "token",
            amount = amt,
            currency_code = "USD",
            token = new
            {
                token_type = "FDToken",
                token_data = new
                {
                    type = cardType,
                    value = transarmorTokenValue,
                    cardholder_name = cardHolder,
                    exp_date = expMonth+expYear
                }
            }
        };
        jsonString = JSONHelper.ToJSON(payload);



In order to parse the response JSON:

StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
responseString = responseStream.ReadToEnd();
 var responseValues = JSONHelper.ToDictionaryStringObject(responseString);
  int bankResponse = Convert.ToInt32(responseValues["bank_resp_code"]);



    
The JSONHelper class:

public static class JSONHelper
{
    public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);
    }


  public Dictionary<string, object> ToDictionaryStringObject(string s)
{
       var json = new JavaScriptSerializer();
       return json.Deserialize<Dictionary<string, object>>(s);
}

}

Thursday, May 19, 2016

2 applications instead of 1

These days whenever you build a complex website such as an insurance/benefits enrollment system you plan for 2 applications instead of 1.

The first application is obvious. It is the system in which your customers would use to enroll into their benefits.

The second application is an administration system for the benefits enrollment system. So that non technical employees can configure the system as per the business requirements and your input is not needed for every small change.

In the self enrollment system we have at our company, I have so far built the following admin features:

1. HTML text-boxes where the user can configure popups to be shown on different pages of the self enrollment system.

2. Make a user admin on the website with special privileges.

3. Delete all future deductions (selected plan amount) of users of a particular group. This feature is useful when the sales team has to give demos of our website.

4. Enable or disable a product on the self enrollment system.

5. Changing whether current deduction (last year's deduction amount) is visible on top of every product screen per group.

I'll keep adding features as our product evolves. 

Saturday, May 14, 2016

Is the field 'tobacco user' redundant?

I work in the insurance industry right now and we have a concept of rate tables which we display the rates that is applicable to a customer as per his demographics such as age and tobacco usage. 

For one particular product we have two rate tables depending on whether the customer is a tobacco user or not. The appropriate rates are shown to customer on the screen depending on his answer to the question about his tobacco usage.



My confusion is how to store the fact whether the customer is a tobacco user or not. I know we should not create redundant columns in a database table  Every time the customer makes a selection and enroll's in a policy his action is recorded in the transactions table. Would it be redundant to create a column in this transactions table that records whether the customer is a tobacco user? Because the rate that the customer selected is recorded and this can be matched to the corresponding rate table to identify whether the user is a tobacco user or not.

But then later, when we have to create reports about customer demographics. In order to identify the tobacco usage status of a customer we would need to execute two queries and if the 'tobacco user' column is present we would need only one.

What is your opinion?

Sunday, May 8, 2016

How to change the width of popup after initialization?


I set the width of the popup as auto when initialized in JQUERY script file which is shared with several pages on my website:


 $("#modal-dialog").dialog({
        autoOpen: false,
        modal: true,
        resizeable: false,
        position: { my: 'top', at: 'top+100' },
        height: 'auto',
        width: 'auto',
        buttons: {
            Close: function () {
                $(this).dialog("close");
            }
        },
        show: {
            effect: "drop",
            duration: 400,
            direction: "up"
        },
        hide: {
            effect: "drop",
            duration: 400,
            direction: "down"
        }
    });


And on a particular page I put the following code in the HTML. I am filling the contents in the server code

  <div id="modal-dialog" title="">
                                <div id="dialogContent" runat="server" clientidmode="Static">
                                    </div>
                                    </div>
    
                          
Now try as I may to resize the width it wouldn't work.

 var dialogW = $(window).width() * 0.7;
                        $("#modal-dialog").css("width", dialogW);
                     
                     
However all I needed to do was add this line and it worked:

  $("#dialogContent").css("width", dialogW);
                   
Which means that you need to re-size the content in order to re-size the popup. This way your popup can be of different widths on different pages.

Monday, April 25, 2016

Why create functions?

Going back to the basics today. I personally worked on several programs where the authors have just wrapped all the code in a single function and it has worked! An example, suppose you are working on an ASP.NET website - just stuff everything into the page life cycle Page Load function!

But I am a firm believer in creating functions to segregate your code since it has the following advantages:


  1. Problem solving: They allow us to conceive of our program as a bunch of sub-steps. (Each sub-step can be its own function. When any program seems too hard, just break the overall program into sub-steps!). [1]
  2. Code reuse: They allow us to reuse code instead of rewriting it. [1] This will also reduce the length of your code file. 
  3. Garbage collection: Functions allow us to keep our variable namespace clean (local variables only "live" as long as the function does). In other words, function_1 can use a variable called i, and function_2 can also use a variable called i and there is no confusion. Each variable i only exists when the computer is executing the given function. [1]
  4. Unit testing: Functions allow us to test small parts of our program in isolation from the rest. [1] This is fantastic for Unit Testing. So is dependency inversion. 
  5. Maintainability: It makes it easy to maintain the code since the length of your file is small. And further, if you make changes to the function the new code is automatically propagated to every where the function is called. On the other hand, if you have not created functions, you would have to change the code everywhere either by searching for it or waiting till your program crashes :).

Image source: Wikipedia


When should you create functions?

  1.  Duplicated code: When the same code repeats in several places. This was and still is a thumb rule. 
  2. Long methods: All other things being equal, a shorter method is easier to read, easier to understand, and easier to troubleshoot. Refactor long methods into smaller methods if you can. [2]
  3. Single responsibility principle: If a method has more than one responsibility it can lead to a violation of SRP. [3]
References: 
1. http://www.cs.utah.edu/~germain/PPS/Topics/functions.html
2. http://blog.codinghorror.com/code-smells/
3. http://programmers.stackexchange.com/questions/275646/is-the-single-responsibility-principle-applicable-to-functions


Sunday, April 17, 2016

Two cases: Show a page only if a condition is met AND Restrict user to a certain page

1. There are multiple ways to this, but possibly the best way in ASP.NET is to have a session variable set.

Then check for value of the session variable in page_init or page_load and direct the user accordingly.




2. Another situation is when the user has to be directed to a certain page in the website. If x occurs, redirect user to a certain page. And then, don't let him out of that page if he doesn't make a selection. Java script has a solution to this:

 window.onbeforeunload = function UnLoadWindow() {
         return 'Please completed the selected.'
     };

But this still gives the user the option to leave:


But Session variable solves this too. And check for this variable in every other page of your website or on the master pages. If the variable exists and has the appropriate value, redirect user back to the page. For e.g. suppose we want to take the user to a completed page once his application for a loan is completed. Now we don't want the user to navigate to any other page in the website, until the officer process his documents. We can set a session variable:

Session["complete"]= True;

And check in all the other pages:

if(Session["complete"].ToString()=="True")
        Response.Redirect("complete.aspx");


Sunday, April 3, 2016

My binary world

I am a coder and so I view this world in binary....

Zeros and Ones. Good and Bad. Heroes and Villains. Black and White.

So how the heck am I supposed to create a green button? :)



Why does a page take a lot of time to load?

Suppose your users complain that the website takes a long time to load once they login. It's problem solving question. Let's break it down into the areas where the problem might be:

1. Server scripts

2. Database

3. Browser

4. Client scripts

5. Actual server

Lets address each area:

1. Server scripts
Server side code has some faults. What if there is an long loop of inefficient code?

2. Database
There might be a lot of concurrent users on the application and which leads to a lot of database reads and writes. There are several ways to find out how much time that it takes to execute a particular query. 

3. Browser.
Our website wasn't loading on IE either since we had not published the P3P policy.

4. Client scripts.
Errors in JavaScript.

5. Server issues.
Less RAM? Too many programs or users running concurrently may be one of the reason why the server takes a long time to respond. Why don't you check if the website loads properly at time of when there are few users accessing the system?

By the way, I came across this great post at Kissmetrics.

Wednesday, March 30, 2016

Code to search CSV files and provide user the option to download them

You have some CSV files stored in a folder on your server and you want to let the user download each separately. You will need a ASP.NET placeholder (ID="Downloads") on your UI.

 private void CheckForDownloadFiles(string filePath)
    {
        DirectoryInfo d = new DirectoryInfo(filePath);  
        FileInfo[] Files = d.GetFiles("*.csv"); //Getting CSV files
        Downloads.Controls.Clear();
        string str = ""; int i = 0;
        foreach (FileInfo file in Files)
        {
            str = str + ", " + file.Name;
            i++;
            CreateLinkButtonAndLabel(file.Name,i, filePath);
        }
    }


private void CreateLinkButtonAndLabel(string fileName, int count, string filePath)
    {

        Downloads.Controls.Add(new LiteralControl("<br />"));
        LinkButton newDownload = new LinkButton();
        newDownload.ID = "DownloadBtn"+count;
        newDownload.CommandArgument = filePath+fileName;
        newDownload.Click += new EventHandler(DownloadCSV);
        newDownload.CssClass += "btn btn-success btn-xs";
        newDownload.Text = "<img src='../Images/icons/csv-file.gif' alt='Download CSV File' /> Download CSV";
        Downloads.Controls.Add(newDownload);
        Label label = new Label();
        label.ID = "DownloadLabel" + count;       
        label.Text = " "+fileName+" ";
        Downloads.Controls.Add(label);
}


protected void DownloadCSV(object sender, EventArgs e)
    {

        LinkButton btn = (LinkButton)sender;
        string fullFilePath = btn.CommandArgument;
        if(fileName.Contains("csv"))
            Response.Redirect(fullFilePath);
  }

This will create a button and display the name of your file next to it:





Sunday, March 27, 2016

Badman vs. Superbad

What a bad movie!

I should have stayed at home and done some coding.

Or just slept.

When will I learn?

Saturday, March 26, 2016

Beneficiaries vs. Dependents


I work in the health insurance domain and believe me it helps to have a little bit of domain knowledge. Every employee who is enrolled in a benefit plan can have dependents and beneficiaries attached to the plans.

Source: http://letsallgetcovered.org/ 



You enter dependents in order to make them eligible for benefits such as medical insurance coverage. 


You enter beneficiaries to identify individuals who are entitled to receive benefits in the event of an employee's death, for example, life insurance or 401(k) beneficiaries.


Currently, in our system we have different pages through which the beneficiaries and dependents are added into the system. Further, there are different tables in which they are stored in the back-end. 


References:

1. https://docs.oracle.com/cd/E26228_01/doc.93/e21932/ww_depend_benefic.htm#WEAHB173


Tuesday, March 22, 2016

Bootstrap makes overflow hidden automatically.

My Div

 <div class="form-group" >

contained a table far too wide. But instead of showing the horizontal scrollbar, the table was just brutally cut off and we couldn't see it.





Simple fix:

 <div class="form-group" style="overflow:scroll" >

Of course, later I decided to use an IFRAME and so it didn't matter anymore!

Iframe's are useful when your code takes a while to load.

I was reading a CSV file and converting it to a HTML table to display it. However, since the file was large, it was taking a while for the code to execute and the page to be rendered. Hence, I shifted the table to an iframe and the code to the corresponding page. Now the rest of the page loads fast, and only the iframe still takes three to four more seconds to load. I can handle this even better if I can show the user an image which signifies that the iframe is loading. But I don't really need that right now. And fyi, StringBuilder helped reduce the execution time by a lot!

Sample code behind the iframe page:

//Note that FileContents is a literal control on the page.


  string folderPath;
    protected void Page_Load(object sender, EventArgs e)
    {
        folderPath = @"../Something/SomeFolder/";

        PrintFile();
    }

    private void PrintFile()
    {
        Directory.CreateDirectory(folderPath);

        DirectoryInfo d = new DirectoryInfo(folderPath);
        FileInfo[] Files = d.GetFiles("*.csv");
        foreach (FileInfo file in Files)
        {
            PrintContents(file.Name);
        }

    }

    private void PrintContents(string name)
    {
        string path = folderPath + name;
        FileContents.Text = "";
        StringBuilder htmlOutput = new StringBuilder();
        using (StreamReader readFile = new StreamReader(path))
        {
            string line;
            string[] row;
            line = readFile.ReadLine();
            string[] rowHeaders = line.Split(',');

            htmlOutput.Append("<table border='1'><tr>");
         
            foreach (string s in rowHeaders)
            {
                htmlOutput.Append("<th>" + s + "</th>");
               
            }
            htmlOutput.Append("</tr>");

            while ((line = readFile.ReadLine()) != null)
            {
                row = line.Split(',');
                if (row.Length > 1)
                {
                   
                    htmlOutput.Append("<tr>");
                    foreach (string s in row)
                    {
                        htmlOutput.Append("<td>" + s + "</td>");
                       
                    }
                    
                    htmlOutput.Append("</tr>");
                }
            }
            htmlOutput.Append("</table>");
           
        }

     


        FileContents.Text = htmlOutput.ToString();

    }


RESULT:


Friday, March 18, 2016


Code using Bootstrap to wrap text around a embedded video:







<div class="widget-content">
<h1 class="page-title">Welcome!</h1>
<div class="separator-2"></div>


<div class="row">
<div class="col-md-12">
                               
                                        <div class="pull-right" style="position:relative;padding-bottom:2%; padding-left:2%">

<div class="embed-responsive embed-responsive-16by9">
                                            <iframe width="420" height="315" src="https://www.youtube.com/embed/R-TBYP0xZCw" frameborder="0" allowfullscreen></iframe>

</div>
                                    </div>

                          
Blah blah blah blah.







</div>
</div>

Codility's got it

New website I came across. Good learning material and fun challenges.