Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, June 27, 2020

LinkedIn skill assessment

I passed the LinkedIn C# assessment and now have (barely visible) badge on my profile. This is the report I saw after I gave the test:


And now on my profile, in the skills section there is a tick mark next to C# as shown below:


Of course for me there is a tick next to .NET as well since I gave and passed another assessment for that.

I like the idea of assessments but I don't like the fact that it is hardly visible on your profile. I am guessing most people would not even notice it.

Monday, May 28, 2018

Why is the web page taking a long time to load?

Is this a good question to ask during interviews? I do feel like it tests the problem-solving skills of candidates. Can he/she tell me all the possible causes? Can the break the issue down to its components? Can they identify the different items that can cause problems?

Further, if they do say there is something wrong with the server code ( which is normally their top answer) , I can dig deeper into their ideas on improving the efficiency of the code. 

Saturday, March 3, 2018

Type of parameter is not CLS-compliant

So it's just another normal day, I am coding and coding and coding and suddenly this squiggly line shows up!
Oh no! The squiggly line of death you ask?? Not quite it's like a caterpillar and not much more than that really. It's not dreaded, deceitful or deadly. So I am pretty sure I won't die and neither would my laptop.


This squiggly line appeared below a function parameter. On closer inspection, as I hover my mouse over the caterpillar,  a message pops up saying that "Type of parameter 'someVariableName' is not CLS compliant. "
First time I have seen that error. Now if you'll want more details of the error you can find it here
In my specific case, this was caused because 'Unsigned types should not be part of the public interface of the class'. This particular function was being made public and the parameter in question was a enumerator type.
Which means ..... (drum roll)...........
Enums are stored as unsigned integers by default!
No, no they are not. Actually, here is the real reason why I got the compiler warning:
"The method was being publicly exposing from an assembly marked as CLS-Compliant a type that is from an assembly that is not CLS-Compliant.
This post on SO helped


Extreme short hand coding (C#, ASP.NET)

I was adding items to a drop down list on code behind and in my quest to reduce lines of code, I did this:

dropdownListOne.Items.Add(New ListItem("text", "value" ) With {.Selected = True})

This would add a new listitem and select it. You can also achieve this by writing the following lines:

Dim li As New ListItem()
li.Text = "text"
li.Value = "value"
li.Selected = True
dropDownListOne.Items.Add(li)

Woohoo! So I just saved 4 lines of code (could be more if we had more properties of ListItem to set). Not much difference in performance, I suppose. You can achieve the same thing in C# using:

dropDownListOne.Items.Add(New ListItem("text", "value") { Selected = true});

Linq is fun

Recently I used some LINQ in Visual Basic .NET to search through data structures such as Array and Lists.

//check if list contains a particular object with two property values equal to x and y respectively.
objectArray.ToList.Find(Function(objectItem) objectItem.PropertyOne = x AndAlso objectItem.PropertyTwo = y)
//remove specific notification objects from list of notification objects list
objectArray.RemoveAll(Function(objectItem) objectItem.PropertyOne = x)
//creates a new array without a particular item in the original array
objectArray = objectArray.Where(Function(objectItem) objectItem.PropertyOne <> x).ToArray()


Definitely helps with brevity of the code and has a cool syntax. But I am not so sure about performance. I think it still uses loops internally. I will keep updating this as I use more and more LINQ. More to follow...

Precedence and associativity of operators

Recently at a meetup, one of my colleagues asked the following question:  
int a =1; int b=2; c=a+++b;
What is the value of c?
SOLUTION: So for the answer, you need to look at precedence and associativity of operators here ++ has higher priority than + and will be evaluated first. Therefore, the equation is equivalent to
c= (a++)+b;   //(1++)+2=1+2=3
And the value of c is 3.  

Lets take another example. Suppose we add the line
c=a=b;
to the above code. Now what is the value of c?
SOLUTION: Both the operators (=) are of the same precedence. Therefore associativity comes into the picture and the associativity of = is from right to left. Therefoer, the equation is equivalent to,
 c=(a=b);
And the value of c is 2  

TIP: You can memorize the basic structure of the precedence table using the following trick: PUMASRELCA  - each letter is the first letter of each category in the table arranged in order. Let me take you to the animal kingdom: PUMA S(low) R(red) E(lephants) L(loath) C(at) A(udio)    

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);
}

}

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

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:





Tuesday, March 22, 2016

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: