Thursday, June 19, 2008

Passing viewstates of a page to another page

Download the source code

Sometimes we need to pass information of one page to the next page to do this there are different approaches one of them is that you can pass just a querystring then lookup data in your data source. However sometimes there are no data sources so you need to have all states of one page in another page. So you may use Session object to pass this information. However, this may not be the best way because you are using Session object which is shared between different pages for a user. There is another way which is PostBackUrl.(In next posts I will compare State Management in asp.net)

How to pass viewstate by PostBackURL

After Visualstudio 2005 all our buttons has a nice properties called PostBackUrl which can be assigned to a page then state of this page (the page that has button with PostBackUrl) will be passed to Next page.

Take a look at this:

In this example we have a textbox and a dropdownlist and we need to see state of these two controls in next page. Also we have a button that its PostBackUrl is set to a page. When user click on this button the state is passed to next page to access these states you need to use PreviousPage object. Remember if someone tries to access this page by giving this page address into browser or user is redirected from other redirection method Then PreviousPage object is null. So to be in safe side always check this object. Take a look to this code:

if (PreviousPage != null)

{

DropDownList lst = PreviousPage.FindControl("DropDownList1") as DropDownList;

if (lst != null)

LabelDropdown.Text = lst.Text;

TextBox txt = PreviousPage.FindControl("TextBox1") as TextBox;

if (txt != null)

LabelTextbox.Text = txt.Text;

}

As you see in the code we are checking PreviousPage object so we are sure that previous page state is passed to this page it means that redirection method was PostBackUrl.

Also we have another method to make controls type safe which is defining PreviousPageType Directive (in html code) but the issue with this approach is that you can define one page as your previous page. Also if user access to this page with any other of redirection method then an error will be generated. So I highly recommend you use the previous approach and never user PreviousPageType directive.

Let's see the steps:

1- Define a page with a button which its PostBackUrl is filled with a page ( we call it target page)

2- In Target page Use PreviousPage.FindControl to access controls in previous page.

3- Always check PreviousPage object to be sure it is not null

Download the source code

Wednesday, June 18, 2008

Control structures in C#

These structures are as follows:

if (expression)

{

statement1...[n]

}

elseif (expression)

{

statement1...[n]

}

.

.

else

{

statement1...[n]

}

Please pay attention to logical operators && and while using then as a expression in if structure because as we explain earlier they won't check the second operand if the first one fulfill the condition.

while (expression)

{

statement1...[n]

}

do

{

statement1...[n]

} while (expression);

In comparison between while and do while , do while will execute the statement at least once.

To explain for stucture we can express an example to clarify it.

for (int i = 1; i < 10;i++ )

{

Console.WriteLine(i);

}

Another control structure is for each. But before we go through it, we should know what arrays are. That's because for each is used only with a of collection entities, collection of data types.

Structure of foreach is as bellow.

foreach (collectionDataType varName in collectionName)

{

statement1…[n];

}

It means that each item in collection will be assigned to varName then the code in the block will be run for varName.

Array

Arrays are of those kinds of variables that are placed in heap memory.(go to first lesson, memory management)

Array is a collection of specific data type. Let's have an example to understand both for each control structure and arrays.

int[] nums = new int [3];

nums[0] = 10;

nums[1] = 15;

nums[2] = 20;

int sum = 0;

foreach (int n in nums )

{

sum = sum + n ;

}

Console.WriteLine("The summary is :{0}" ,sum);

In above code each item in nums is assigned to n and then the code in the block will be run for each item.

Break and Continue

It's time now to talk about break and continue. Remember that, these two statements are using in loop structures. Like for, while, do while and …. Let's see the usage of them in an example.

If you run the following code snippet you will see that when i =5 the code will stop. It means although i is less that 100 but the rest of code won't execute.

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.WriteLine("Hope!");

break ;

}

Console.WriteLine(i);

}

The result will be as follow

Figure 4

But if you change the code like this:

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.Write Line("Hope!");

continue ;

}

Console.WriteLine(i);

}

Instead of each number that is dividable to 5 the word "Hope" will be printed. The result of running the above code snippet is shown in figure 5

Figure 5

Note: You are not allowed to change the value of the counter in the foreach control structure. This is a read only value. It means you can not change the value of i in the code above.

GoTo:

Probably no other construct in programming history is as maligned as the goto statement. The problem with using goto is use of it in inappropriate places.

The structure of goto is

goto lableName;

lableName:

Statement1…[n];

It is hardly recommended to use goto because it reduces the performance of the application, except in some cases that it will increase the performance. Using goto in nested loops that break can't help you will be very handy.

Switch case

Another control structure is switch with the following structure

 switch (expression)
{  
   case constant-expression:
        statement
        jump-statement
    case constant-expressionN:
        statementN
    [default]
}

In this structure as you can see if you write even one statement you should have a jump-statement that can be break or got otherwise you as a programmer will face an compile time error indicating that you lost a jump-statement. Don't forget to define break in default case. Let's explain the structure in a sample code.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

In this case you won't get a compiler error because of not having break in the first case statement. The reason is you don't write any code for that specific case statement. This means compiler will execute codes till it arrives to a break or goto. If a user enters 10 as the value or 20 he will receive similar out puts.

But what if you want the compiler execute first and second statements that are in case 10 and 20 if user_entered_value is 10 and execute statement in second case if user_entered_value is 20. You simply can modify the code as bellow using goto.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

please pay attention to the out put with different entered_values.

Figure 6- User entered 10

Figure 6- User entered 20

"Thanks To Azadeh for writing this post"

Tuesday, June 17, 2008

Access master page members from a page

download the source code

Sometimes we need define a property or a method in a masterpage and we need access to that property or method in pages that are using that masterpage. To do this we have two choices.

1- Using FindControl (this.Master.FindControl("usercontrolid"))

2- Using this.Master.YourProperty

The first one is not type safe so you could misspelled a property name then you will get null so this approach is error porn. Furthermore, the control should be cast to a valid control. Also you cannot access property by this approach but you can access to controls in masterpage. However, it does not need any other effort.

The second one is type safe, access to masterpage properties is possible and there is no need for casting. However, it needs that the control be defined at least internal and you need define the master type in your page. Then compiler can detect that master page property and it allows you to access to those property through intelisence.

Let's see an example: we have a Label and image in our masterpage and we have some methods in our master page. We need to call these methods from page that is using these masterpage. Also we have a property in master page that we need to have access in our page. Take a look at this:

This is the master page html code:

This master page properties and methods

public Label TitleLable

{

get

{

return LabelTitle;

}

}

public void ShowImage()

{

Image1.Visible = true;

}

public void HideImage()

{

Image1.Visible = false;

}

Then we create a page that is using this masterpage. And this is the html code:

Important: in this code we defined a mastertype directive to notify compiler that we are using these masterpages then if you compile and try to access masterpage methods and properties you can see them.

Take a look to the code behind of the page. As you see we implemented both way. I highly recommend the second way. Remember the first way does not force you to define mastertype in the page. While, second way need the mastertype directive in html code of the page:

protected void ButtonChangeTitle_Click(object sender, EventArgs e)

{

//first way

//Label lbl = Master.FindControl("LabelTitle") as Label;

//lbl.Text = "New Title is Assigned";

//second way

Master.TitleLable.Text = "New Title is Assigned";

}

protected void ButtonHideImage_Click(object sender, EventArgs e)

{

//first way

//Image img = Master.FindControl("Image1") as Image;

//img.Visible = false;

//second way

Master.HideImage();

}

protected void ButtonShowImage_Click(object sender, EventArgs e)

{

//first way

//Image img = Master.FindControl("Image1") as Image;

//img.Visible = true;

//second way

Master.ShowImage();

}

As I said before I highly recommend the second way. Let's review the steps:

1- Create a master page

2- Define some public properties and methods in masterpage

3- Create a page using the master page

4- Define the mastertype directive in page

5- You can access masterpage public properties and method through Master object in the page

Operators in C#

It is important to know that C# and java support the rules of IEEE, means if you have 10.5/0 you won't get an error. It will be infinity or if you have 0.0/0.0 the result will be not a number. But if you have 10/0 then you will got an overflow error.

As you all know there are different kinds of operators. 
 ·         Relational Operators such as ==,!=,>,>=,<,<= which are used between two operands(except !=) and the result is a Boolean.
 ·         Logical operators such as &,,&&, that are used between two Boolean operands and return a boolean. It is good to point that && and  make a short circuit, means if the first operand is false the && operator returns false without checking the other operand. But if the first operand is true  operator will return true without checking the other one.
 ·         Arithmetic operators such as +,-,*,%. No need to describe them more as you are familiar with 
 
Besides the other operators that we don't describe them here, there are some important ones that are basic in C#.

++ Increment operator, incrementing the value by 1 (i++ is the same as i=i+1)

— Decrement operator, decrementing the value by 1 (i— is the same as i=i-1)

+= Increment assignment operator (i+=5 is the same as i=i+5)

-= Decrement assignment operator (i-=5 is the same as i=i-5)

== and != Equality and Inequality operator

% Modulus (remainder) operator. (17%5 equals 2)

Thanks to Azadeh for this post

Sunday, June 8, 2008

Evaluate your code by Code Analysis

We may write lines and lines of code but never check our code to see whether we follow up the best practice for coding. Sometimes, we make big mistakes in our codes it may not appear now but in future when change requests come. It reveals our code was not that much good we thought it was. So how can a programmer be confident about his code? The only way is that you need to review your code but in reality being overloaded we never have this chance. Nevertheless, we need code checking to be automatic and Code Analysis is a tool absolutely free with Visual studio .Net helps us to check our code in terms of security, design, maintainability, reliability and a lot more.

How to configure Code Analysis?

Open your project in visual studio then right click on your project and select properties. Then select code analysis tab. And you need to check "Enable Code Analysis". I highly recommend taking a look at different Rules that you can check. For example if you have different naming convention you can unselect that.

Then all you need in solution explorer right click on your project and select Run Code Analysis. It will show you some warning for your code.

Take a look at this picture

For simple code that I wrote code analysis could find some issues with my code. One of them says for enum value you need to have a zero value which is part of Microsoft best practice.

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"