Sunday, June 8, 2008

Primitive data types in C#

"Special thanks to Azadeh Hasanzadeh who wrote this fantastic post"

The data type variables define the type of data and the format can be stored in it.

In case of data types we can divide programming languages to 3 groups.

  1. Untyped languages: In these languages there is no need to declare the data

type.For example in javascript when you have a=10, it means "a" is an integer because it is assigned to 10 so the data type is predicted by assignment

  1. Typed languages: You should declare the data type.

For example in Pascal, C or VB you should declare the data type of a variable to initiate it .In C:

char c = 2

short s

s=c

In this example as C is a low level language the HEX values of 2 as a character will be placed in s.

  1. Strongly typed languages: In these languages not only you should declare the data type but also you should be aware of data type conversion. C# is in this category.

In C# you will face a compiler error if you try to assign a character in integer type unless you as a programmer accept the responsibility.

Data Types in C#

We can summarize primitive data types as the table below

Data type

Description

Size (bits)

Byte

Unsigned integer

8

Short

Signed integer

16

int

Whole numbers

32

Long

Whole numbers (bigger range)

64

Float

Floating-point numbers

32

double

Double-precision

64

Decimal

Monetary values

96

Bool

True, false

8

char

Single character

16

As I said above C# is a strongly typed language and data type conversion happens under especial circumstances. It means: smaller data types can be converted to bigger but not the opposite. Let's explain it in an example. There are three variables. One is short, the other is an int and the last one is a long.

You simply can convert short to int as int data type accepts a wider range of numbers that includes short data type, but you can't convert long to int. unless you accept the responsibility of loss of data that may happen during the data type conversion. This acceptance is known as Cast. Pay extra attention that in casting you will lost the most valuable bytes of data.

Do you agree to have all we talked about, in an example in .net environment? Here it is:

First of all we will have our examples as a console application which is free from interface.

Let's start together.

  1. From start menu select Microsoft visual studio 2005.
  2. File/New/Project.
  3. Select the options as shown in the figure 1.

Figure 1

Type a Name for your project and browse for its location.

The main window of the .net environment will be shown. In the left pane (solution explorer) you can see "MyfirstProject" as you chose for your project's name. In the source code environment you can also see "MyfirstProject" as the name of the namespace. There is a class named Program. You can change it to whatever you like. The only thing you need to do is select the name of the class from the solution explorer, press F4 or select view/properties windows to see the properties of the class, and then easily change the File Name to your desired name. Pay attention that the class name in source code will be changed. In the "Program" class you are able to see a method called Main which is the main method of the class exactly as it was in C. We will talk about it later.

Imagine we have information of a 30_year_old person whose name is "Matt". The whole days of his age is age*365. Just think that you want to show his Days Of Age in "age" variable. We can declare this information like this:

static void Main(string[] args)

{

int age;

string name;

long daysOfAge;

age = 30;

name = "Matt";

daysOfAge = age*365;

age = daysOfAge;

}

If you click run button ( ) or press F5 you will face an error that its explanation is shown in the bottom of the page. This is exactly the case we talked about before.

Figure 2

You can see that the compiler can't convert long to int. The interesting thing is that it suggests you Casting the data types.(are you missing a cast?)

If you change the above code snippet to

static void Main(string[] args)

{

int age;

string name;

long daysOfAge;

age = 30;

name = "Matt";

daysOfAge = age*365;

age =Convert.ToInt32 (daysOfAge ) ;

}

Then you will say to the compiler that you are aware of possible loss of data. So that compiler won't have any responsibility against this matter.

This is the complete code for our first project. Just type it as it is in figure 3. Don't worry about the syntax you don't know about. We will discuss about them later.

Running a project in .net is with F5 and it start debugging the project, but if you do that you will see that the result is shown so quick that you may not be able to see it. So ctrl+F5 (start without debugging) will give you the chance to see the result.

Figure 3

Note:

There is point about decimal and float data types in C#. In C# every floating numbers are known as double. If you write double d = 10.5; you won't face any error. But if you write float f = 10.5 you will get error. That's because default data type of floating numbers is double and you are trying to cast a double to a float which is a smaller data type and as I explained before changing a data type to a smaller needs to accept the responsibility of loss of data that we called it casting. To avoid this error there are some literals that f is used for casting to float and m is used for casting to decimal data types. It means that you can easily use f as a key word to cast a data type to float which is preferable than using cast. For example

float d = 10.5f;

means you are emphasizing that 10.5 is a float.

Double and float data types round the digit and you can't have precision. So using decimal data type will solve this problem which doesn't round the digit. To convert a digit to decimal you can simply use m literal instead of casting.

decimal d = 10.5m;

This shows that you are using d as a decimal value not a double.

"Special thanks to Azadeh Hasanzadeh who wrote this fantastic post"

Thursday, June 5, 2008

How to export data to CSV file in ASP.NET

Download the source code

First let's see what the CSV file is:

CSV file is a text based file in which data are separated by comma. It can be opened by excel so you can use excel functionality. Each row of data including the title is in separate line. Meanwhile, each row has data separated by comma.

How to create a CSV file?

We need to write data to Response object. Meanwhile the content type should be text/csv also a header type of attachment should be added to response. Afterwards, column names are written to response then to actual data is written (each row should be just in one line).Finally you need to call Response.End to finalize your work.

Important: if any part of data has comma, unfortunately the CSV file will be screwed up. What I did in the code is that I am replacing comma with space so I am sure that the only comma exists in each row is just for separating data rather than being part of data.

public class CSVExporter

{

public static void WriteToCSV(List<Person> personList)

{

string attachment = "attachment; filename=PerosnList.csv";

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.ClearHeaders();

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.AddHeader("content-disposition", attachment);

HttpContext.Current.Response.ContentType = "text/csv";

HttpContext.Current.Response.AddHeader("Pragma", "public");

WriteColumnName();

foreach (Person item in personList)

{

WriteUserInfo(item);

}

HttpContext.Current.Response.End();

}

private static void WriteUserInfo(Person item)

{

StringBuilder strb = new StringBuilder();

AddComma(item.Name, strb);

AddComma(item.Family, strb);

AddComma(item.Age.ToString(), strb);

AddComma(string.Format("{0:C2}", item.Salary), strb);

HttpContext.Current.Response.Write(strb.ToString());

HttpContext.Current.Response.Write(Environment.NewLine);

}

private static void AddComma(string item, StringBuilder strb)

{

strb.Append(item.Replace(',', ' '));

strb.Append(" ,");

}

private static void WriteColumnName()

{

string str = "Name, Family, Age, Salary";

HttpContext.Current.Response.Write(str);

HttpContext.Current.Response.Write(Environment.NewLine);

}

}

Download the source code