C# Web Application Learning Tips

On October 30, 2014, in Other Online Technology, by James Liu

I am working on C# for several weeks. Before this project, I don’t have any experience with C# language. Though I have many years PHP language experience, it still a big challenge for me to work on Microsoft platform with C sharp language. To help me remember some C# basic usages. I set up this post to write down all problems I have met and give out the solutions.

How to Get Current URL?

Here is the way to get current url string in C#.

//following code will get /example.html?id=1234 from url:
String currurl = HttpContext.Current.Request.RawUrl;

How to Get Parameters From URL String?

This could be the most basic usage in C# web application programming. There are several case to get parameters from URL. If you know the key name of url parameters (this is the most of cases), You can use following code to get the value.

//following code will get id parameter from url:
string idstr = Request["id"];

There is another way to get the parameters. Check more information about Request.Url.Query.

//following example code will get id and action from url:
string querystring = Request.Url.Query; //value is ?id=1234&action=add
NameValueCollection qscollection = HttpUtility.ParseQueryString(querystring);

string idstr = qscollection.GetValues("id").First();
string action = qscollection.GetValues("action").First();

If you don’t know the key name, you have to get the whole url and parse all key-value pairs from it.

string queryString = Request.Url.Query;
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();
      queryParameters.Add(key, val);

How to Read Uploaded File by Form POST

Uploading and processing files is another basic task for most web application. In C#, here is the way to handle files uploaded by HTML Form Post. Following C# example source code will show you how to get the file from HTML Form Post and read it line by line.

//myfile is the name of the input html tag
HttpPostedFileBase myfile = Request.Files["myfile"];
if (myfile != null)
    var streamReader = new StreamReader(myfile.InputStream);
    var lines = new List<string>();
    while (streamReader.Peek() >= 0)
        string line = streamReader.ReadLine();

How to Check String is Null or Empty in C#

In most of the cases, we need to test the parameters when we get them from url or post form. At the beginning, I am using following code to test:

string idstr = Request["id"];
if (idstr != null && idstr.Trim() != "")
	//do something

Actually, there is another better way to test in c#:

string idstr = Request["id"];
if (!string.IsNullOrWhiteSpace(idstr))
	//do something

Difference Between DateTime in C# And DateTime in SQL Server

In one of my project, I try to save a time stamp in SQL Server and generate a hash code by it for future validation. In the validation process, I will get the time stamp from SQL Server and generate a new hash code, compare it with the old one. Now problem is that, sometimes the hash code doesn’t match.

C# DateTime Definition
Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file.

SQL Server DateTime Definition (Transact-SQL)
Defines a date that is combined with a time of day with fractional seconds that is based on a 24-hour clock. The official document recommends us to use time, date, datetime2 and datetimeoffset data types in the new work.

The different between these two types is DateTime values in SQL are rounded to increments of .000, .003, or .007 seconds. For example, 01/01/14 23:59:59.999 in SQL server will become 2014-01-02 00:00:00.000; 01/01/14 23:59:59.995 in SQL server will become 2014-01-01 23:59:59.997;

Therefore, to solve this problem, either we need to use datetime2 or we need to trim the nano second part with following code:

DateTime mydate = DateTime.Now;
mydate = new DateTime(mydate.Year, mydate.Month, mydate.Day, mydate.Hour, mydate.Minute, mydate.Second);
//then, save in database
Tagged with:  

Leave a Reply

Free WordPress Theme

WordPress Themes