Thursday, November 25, 2010

[ASP.Net] - Create Your First ASP.Net

1. Introduction


In this article, we will create our first ASP.Net application using the C# language. This is a Step by Step with an explanation in the middle when it required.

2. Creating the Web Project


1) From the start menu open the Visual studio 2005
2) Click on File|New Web Site
3) From the opened dialog chose ASP.Net web site



4) Set the Location as File System.
5) Set language as Visual C#



6) Set a folder path of your choice for your web site by selecting a Folder using the Browse button. Then click OK.



The Visual Studio 2005 creates the web project and it is ready. Here, we selected File System as the location. So we are not going to deploy it in the IIS. The IIS stands for Internet Information Server. IIS is a web server, which processes the user input, and replies back web page content. Since we had selected file system, the application will be created on your local system and cannot be accessed from the network (Local Intranet or World wide web). But, still you can test it on your local application.

Now you are left at the defalt.aspx page by VS 2005. This is the default page every site displays when a site name is invoked just by giving the Name. Just try C-Sharpcorner.com on your browser and watch what page it displays by default.



3. Adding controls to your Page


Now we will add a Hyper Link control and button to the default web page. The link control is not visible when the page is displayed. To make it visible the user should click the button Get Link.

1) First click the Design button in the bottom pane of default.aspx. This is shown in the Previous picture. Note that this is how you will switch between design and source.
2) Once you are in the design mode, first select a button control and drag and drop it to the Design area.
3) Next do the same for Hyper link control.

The design area now looks like below:


4) Click the button
5) Select the menu item View|Properties window
6) From the displayed property window on the Right side pane, set the following properties shown in bold for the Selected button control



7) Click the Hyperlink control and set the properties as shown below:


8) Now Click the Save all Icon from the Toolbar.

4. Adding the event handler


Now we will add the event handler for the button click event. And the handler will take care of setting the visible property for the Hyperlink control to true. When you double click the button Visual studio 2005 will bring you to a C# file called Default.aspx.cs. This file is called code behind file. Code behind – because it takes care writing the logic behind the page Default.aspx. Some people also call it as supporting file. Supporting file for what? Supporting file for the Default.aspx server side script file.

1) Double click the button control
2) Visual studio will bring you to the code behind page. Write the following line of code:

//001: Set the visibilty of the Hyper link to true
HyperLink1.Visible = true;

5. Running Your First web application


1) Click on the Run Icon



2) The following message box displays. Click ok for the Message box.



3) Visual studio invokes the Inbuilt Web server (Like IIS) and displays the Web page designed by you. Click the Show Link button. This will show the Web URL.


6. How Do I open the Attached Project


1) Download the attached zip file
2) Extract it to a folder
3) Open visual studio 2005
4) Click the menu item File|Open|Web site
5) Select the Extracted Folder

Note: The Attached solution is created in visual studio 2005


Source Code : Download


[C#] - Implement Fade Out on Form Close


Introduction


In this article, I will explain how to display the form that goes fully transparent before the form gets closed. Follow the below-specified steps and I will give some explanation when a step requires it.

Set up the Form


  1. Create a New Visual C# project using VS2005 IDE. The project Type is Windows Application.
  2. Add a Label control to your form.
  3. Add a timer component to the form. The component appears below the form in the grey area (Look at the screenshot).
  4. If you need, you can set the Label’s Background and foreground colours.
  5. Set the Form’s Background colour.

The finished form looks like below:




The Timer Component


The timer is found in the Component portion of your toolbox. Once you drag and drop it to the form it will appear as shown in the above picture. Timer component raised an event called Tick. This Tick event is raised periodically for certain time interval. This time, the interval is set by the property interval

There are different types of timer available in dot net framework and I will discuss that in a different article. Here we used time as a component.

Form Load Event Handler


The Dot Net Framework invokes this handler when the form is loading and before get it displayed. Continue the steps to implement the Form Load event handler.

6) Double click the form.
7) It will automatically bring you to the code editor inside the Form Load event. The load event is the default event for the form. 
8) In the load event handler, assign the text for the Label control. Note the usage of Environment.Newline to place a newline in the string. The code written in this handler is shown below:

//Fade001: Set the Label Text
label1.Text = "The Fade Effect is given to" +
    Environment.NewLine + " this Form by Setting the"+
    "Opacity Property";


Tick event Handler for the timer and Opacity property of form


We already saw about the Timer and the Tick event for it. When a tick event is raised by the Timer component, the code in the Tick event handler is get invoked. So, here we will set the Opacity property of the by decrementing it.

The Opacity property is used to control the Transparency of the form. This property is specified in terms of percentage. When the Opacity property is at 0%, the form is fully transparent. So it is clear that the default value for this property is 100%.

Now continue with the steps to decrement this percentage from 100% to 1% in the handler that runs periodically saying thanks to Timer component. The effect is that the form goes from Solid to fully transparent.

9) Double click the Timer1 component.
10) This will bring you to the Timer’s Tick event handler.
11) Inside this handler Place the below code:

//Fade002: Check the Opacity property, When Opacity is 1%
// Close the form and stop the timer.
if (this.Opacity > 0.01)
    this.Opacity = this.Opacity - 0.01f;
else
    this.Close();

Form Closing Event Handler


The "FormClosing event" occurs before the form gets closed. The event itself says that I am not yet done (Not closed, On the way of closing). So this is the correct place for us to say “Hey do not close it now. I will tell you when you should close”. What do we want to achieve? We like to Fade-out the form when the user clicks the close button.

When a user clicks the close button, first, FormClosing event is fired and then the "FormClosed event" is fired. We will check the Opacity property in the FormClosing event, and when it is not transparent enough we will Cancel the event using the "FormClosingEventArgs" passed as the parameter by the FrameWork. And at the same time the Enable the timer component by setting the Enable property to true. Setting the enable property to true makes the timer start raising the Tick event periodically (Based on the Interval property). Also, note that we specified the interval as 50. The unit is in milliseconds. That means, the Tick event is raised 20 times in a second. The simple calculation yields in around 5 seconds the form goes fully transparent and gets closed. Now continue with the steps:
12) As FormClosing is not a default event, go to the form designer and select the form
13) Open the Property window and Click the event button



14) In the left hand side event listing, double click the event name FormClosing
15) This will bring you to the handler for the Form Closing
16) Write the below specified code. The explanation for the code is given before these Steps.

//Fade003: Cancel Form close action when the opacity is
// more than 1%.
if (this.Opacity > 0.01f)
{
    e.Cancel = true;
    timer1.Interval = 50;
    timer1.Enabled = true;
}
else
{
     timer1.Enabled = false;
}



That is all we have done it. Now run the application and click the close button. Watch it. Below is the Screenshot was taken when the form is at Semi-Transparent.


Note: The attached code is in VS2005. Say yes to the conversion dialog when you have the latest version

Source Code : Download

Sunday, November 21, 2010

SQL 2005 - Table relationships - One-To-One, One-To-Many, Many-To-Many

Introduction

The relationship between the tables are very important for the modern database systems like Oracle, SQL Server etc., The relationship between tables are performed by linking a column in one table with a column in another table. When we do so there are four different type of relationship will arise. The relationships are listed below:

1) One to One Relationship2) Many to One relationship3) One to Many relationship4) Many to Many relationship

We will explore each relationship here.

One to Many & Many to One Relationship


In One-to-many relationships, a single column value in one table will have one or more dependent column value in another table. Look at the below Picture:
One-to-Many
Fig 1. One to Many


Here, there are two tables. One is Customer table, which has all the customers. The other table is Order table, which has all the orders uniquely identified by the OrderID. The CustID column in the Order table is showing which customer placed the order. In this case, there will be multiple values for the same CustID in the Order table. If customer X has placed 4 Orders, then there are 4 CustID (X) in the Order table, and there is only one corresponding CustID X in the customer table.

So if you look at the relationship from left to right (Customer to Order), it is a One-To-Many relationship. If you look at the relationship from right to left  (i.e.) Order to Customer, then it is a Many-to-One relationship. Simply, Customer->Order is a One-to-Many relationship & Order->Customer is a Many-to-One relationship.

Modelling the relation


In a relational database system, you can model this with a foreign key and unique Key. In our Example, CustID in the Customer table is Primary or Unique Key. CustID in the Order table is a foreign key that refers the column CustID in the Customer table. Note that if you modelled the One-to-Many relationship between two tables, then many-to-one relationship automatically exists. The professional way of symbolic representation is placing a ¥ on the left side point and 1 in the right side point (In our diagram).  

Many to Many Relationship


Hope you have an idea of what I am going to say here as you already read the previous section. The question is how do we model it in the relational database system. For a perfect Many-to-Many relationship, a third table is required. The third table acts as a bridge between the two connecting tables that want to establish a Many-to-Many relationship. The bridge table stores the common information between the Many to Many relationship tables. Have a look at the below picture:


Many-To-Many
Fig 2. Many-to-Many
In the above example, Transaction table acts as a bridge table. It has information common to both product and customer. The Transaction table has two One-to-Many relationships. One is between Transaction & Customer and the other one is between Product & Transaction. For a given Customer Id row in the Customer table, there exist multiple customer id rows in the transaction table. Similarly, One product id in the Product table has multiple entries in the transaction table. Together the result gives answers to:
1) A customer who purchased multiple products. 
2) A product, which is purchased by Multiple customers.

So how do “Many-to-Many” relationship exists between Product and Transaction tables?

1) First, let us look at the Linkage shown in the picture from left to right. A single customer id XYZ is mapped to multiple repeated customer ids (XYZ) in the Transaction table. All this transaction table’s repeated XYZ customer ids have different Product Ids P1, P2,P3...Pn. All these products in the transaction table will have a unique row in the Product table. So the whole result is “A single customer XYZ purchased Many Products

2) Let us have a look at the diagram from Right to Left. A single product ABC in the product table has repeated entries in the Transaction table. All these same products (ABC) has different customer ids C1,C2,C3…Cn. These a corresponding unique row for each Customer like c1,c2 etc., in the Customer Table. The whole result is “A single product ABC is purchased by Many Customer

Hence, the relationship between Product and Customer is Many -to-Many via the intermediate bridge Transaction. Simple, there are many products purchased by many customers and they together forms the concept of Products Transaction by customers.

Modelling the Relation


1) ProdId and CustId in the transaction table together forms a Primary key. That is; both the Prodid and CustId column uniquely identify a row in product and customer tables respectively. Prodid refers the Product id in the Product table using a foreign key. CusId refers the customer id in the Customers table using another foreign key. So ProdId and CustId together forms a Primary key in Transaction table and as an individual, they act as a foreign key for a table to the left or right.
2) ProdId in the Product table is a Primary Key.
3) CustId in the Customer table is a Primary Key.

One to One Relationship


One to one relationship can exist between two tables. I hope you already guessed it. You are right if your guess is “The second table column that refers the first table column is a primary key as well as foreign key”. Consider the below-specified Picture:


One to One
Fig 3. One-to-One

It looks like an inheritance for Front-end developers. OK. That holds true for our example also. The member id in the CAshCornerMembers table is a Primary key. Two tables VIPMember, as well as MVPMember, refers this primary key column in the table CAshCornerMembers. Both MemberId fields in the tables VIPMember and MVPMember are primary keys and at the same time, they point to the MemberId field of the other table CAshCornerMembers using the Foreign key. So in this example, there exist two One-to-One relations.

How is it One-To-One?


The answer is simple! The columns involved in the Mappings are Unique in the table they present. Also, note that a member can be a VIP member as well as MVP like our Mahesh Chand. In that case, both the table has his MemberId (Once) and refers the Single entry in the table CAshCornerMembers.

Friday, November 19, 2010

SQL 2005 - What is "Data Normalization"?

Normalization


"Normalization" is a well-known standard that helps efficient storage and retrieval of data from the relational database systems. There is three important normalization are available. They are:

  1. First Normal Form
  2. Second Normal Form
  3. Third Normal Form

This article talks about these three normal forms with examples. Let us start with "Database Table Normalization".

First Normal Form


The "First normal form" or First "database normalization rules"  says, “The information stored in the form of database table should be well split into columns. When you split make sure same information is not split into multiple columns”.

Consider the Table Below which stores the C# Corner members for Example:

Normal Table
Fig 1.  Normal Table


Let us say there are 4000 such members in the table. If you want to retrieve the data in the descending order based on the last name then you need to perform string manipulation on the stored data. Also, it is not always guaranteed that the information you split is fully qualified as the last name as you may perform string manipulation based on the space. The first statement in the Normalization (First Normal form) specifies this. "Data should be well split into column". Why do I put “well split” into underline? Because we all know that data should be split into the column. Definitely, no one will design the above table like below:


Wrong way of storing data
Fig 2. Storing everything in single column (Worst Way)

Below is the Well split table:


Well Split Columns
Fig 3. Well Split Columns

Well, but the First normal form says “When splitting, do not split same information into multiple columns”. It may confuse that I split the same information, that is the column 'Name' into multiple columns. OK. Do not look at the initial column before the split that is; the member name. Look at the final result and apply the rule:
“Do not split same information into multiple columns”
First Name and Last Name are different, so it is not the same information. Each column is well categorised. So why the First Norm says “Do not split same information into multiple columns”?

To explain that look at the below table (Order):


Sameinfo in multiple columns
Fig 4. Sample information spawning into multiple columns

The table stores the order in the Orderid column and the customer who placed the order is placed in custid column. But, if you have a look at the columns for products (Product1, Product2, Product3) in the table, it is stored as a separate column. The same information is repeated in multiple columns like product1, product2 etc., to show the products in each order. The number of products that belongs to the Order is not constant as it varies. So Data Manipulation should accommodate the 'change in data' like inserting a row or Modifying a row in such a way that schema should not change.

The correct design is shown below:


Correct design
Fig 5. Correct design

Second Normal Form


The Second Normal form says, “Entire columns in the table should functionally depend on a single key that uniquely identifies the row also should adhere to the first normal form”. Note that, here the key may be a combination of more than one column.


Second Normal form
Fig 6. Second Norm

In the above table say Orders, Customerid and OrderPrice are depending on the single key column Orderid. The CustomerName field is not related to OrderId and should go on a Customer table. If we remove the Customer Name fields from this field the table is in Second normal form.

Third Normal Form


The third normal form says, “Any columns in the table should not depend on column which is not a key column that uniquely identifies the row. Also, first it should be in second normal form”.

It means if a table has some columns that depend on some other column that is not a primary key column then the table is not in third normal form. Let us consider the below example:


Third normal form
Fig 7. Third Normal Form

In the above example, the TotalPrice column is dependent on UnitPrice and NoOfItems. Hence, this column should be removed from the database. The program that processes this table should calculate the TotalPrice or a view could be created to have the calculated column such as TotalPrice. Whatever can be a solution, for the above table should be in the third normal form the TotalPrice column should be removed from the table.

[C#] - Custom Events


Introduction to Events


An event is kind of ‘Something Happened’. Some examples are the button got pressed; a checkmark from the check box is removed. We all know that we call this kind of action as Events happening to those controls.

So let us consider a form that has a button in it. And we all know that a button can be clicked. The user does the action of clicking a button and we do not know when that action will happen. In this situation, if we consider the application wants to know when the button got clicked and wants to say “Hi! There”. So what you think now. Somebody should say the button is clicked and somebody should respond back to the event in our case saying just a “Hi”.

I can hear you are saying Not a big deal. Double click the button, the Development environment will bring me to a function, and write the code there that says Hi”. Well. If the Team Lead (Yes, the same guy who always bugs you) asks you “Hey! We have a class called Product Stock and it maintains the stock in hand in an integer variable. Can you expose an event say LowStock so that the interested one will get a notification when the stock in hand goes below five?

What is the answer?  “Yes”? OK, then you already know the Events very well. It is your choice whether you want to refresh it here or not.
If your answer is “Hey. I know how to handle the UI events. I have not created my own event”, then this article is for you. Let us start.

Publish and Subscribe


If we go back to the button click on the form that says “Hi there”, there are some piece of information we need to know.

  1. The button is placed on the form. The form is the container that holds the button, which is a UI Component.
  2. The Button class in dot net exposes an event called Click. So button class publishes the event click.
  3. The Form class wants to know when the button got clicked. So it subscribes for the published event Click.
  4. When the Button is clicked, Subscriber for the event Click on the button is notified. And there is handler code that says Hi when the notification is received.

So the publish is nothing but exposing the event and subscribe is kind of getting the notification on the supplied function. Delegate and event are tightly coupled. We will see how when we are going through an example and at the same time you can answer the question for your team lead.

The Example


In this example, we have two classes. One is the ProductStock class, which maintains the current stock of the product. The other class is Counter used by the billing counter computers in the retail shop. Let us say A customer comes to billing a counter, informs the product he wants to purchase, pays the bill and goes to the stored room to receive the product. Each billing counter receives a notification when the product stock goes low.

Consider the below picture before we move on:




1) The ProductStock class publishes the event LowStock
2) Purchase, Counter etc classes subscribe to the Published event LowStock.
3) ProductStock sends a notification to the entire subscriber when to ProductStock goes low.

In our Example, we are not going to Implement Purchase and Someother class.

The ProductStock Class


1) The ProductStock has two member variables. One to know the product name and another one is keeping track of the current stock. The current stock is get reduced by the sales counter when a sale of the product is performed.

//001_1: Member Variable.
public string ProductName;
private int StockInHand;

2) The class declares a multicast delegate OnStockLow that takes an Event source object and EventArgs object. The event source is ProductStock as it is going to raise the notification (Event). EventArgs is usually a class derived from it EventArgs that can be used to pack the information related to the event. To keep this example simple I have not derived any object from EventArgs. Below is the declaration of Multicast delegate:

//001_2: Multicast delegate type that gets coupled with the event.public delegate void OnStockLow(object sender, EventArgs e);

3) Next, the event StockLow is declared. Note how the Delegate is coupled with the Event. It implies that notification handler function should return void and receive the object as a first parameter and EventArgs as the second parameter. As it is a multicast delegate you can use delegate chain of above said functions. OK, Now the Product stock published the Event. Below is the declaration of the event:

//001_3: Published event (StockLow), that takes responsibility for sending notification to the subscriber through the above
//Specified multicast delegate
public event OnStockLow StockLow;

Note the syntax:
public event <delegate type name> <event_name>.

4) The constructor of the ProductStock class initialized the members 

ProductName and StockInHand. Below is the code:
//001_4: Constructor that Initializes the Stock
public ProductStock(string Name, int OpeningStock)
{
  ProductName = Name;
  StockInHand = OpeningStock;
}

5) The Counter objects call the ReduceStock function when a sale is performed. This function reduces the current stock and notifies the subscriber of the LowStock event when the current stock goes less than five. Below is the function implementation:

//001_5: This function reduces the stock based on the sales on the billing counters. When the stock in hand is lower than
//                                            5, it raises the event StockLow event.
public void ReduceStock(int SalesDone)
{
            StockInHand = StockInHand - SalesDone;
            if (StockInHand < 5 )
            {
                        EventArgs arg = new EventArgs();
                        StockLow(this, arg);
            }
}

Note that in the above function call to StockLow(this,arg) is known as raising the event or sending a notification.
We are done with the ProductStock class.

The Counter Class


1) The counter class declares the member variable for the counter name and the constructor initializes the Name. The Sales function takes the ProductStock and number of product sold. It makes a call to the ReduceStock after the sales. Below is the Implementation code:

//002: This class for Sales Counter that performs the Sales on different counters and makes the billing. This class
//                                Subscribe to the Published event and Receives notification through Multicast delegate.
public class Counter
{
            //002_1: Class member
            private string CounterName;

            //002_2: Constructor for Counter
            public Counter(string Name)
            {
                        CounterName = Name;
            }

            //002_2: Function that records the sales performed on the counter
            public void Sales(ProductStock prod, int howmuch)
            {
                        Console.WriteLine("{0} Sold {1} numbers", prod.ProductName, howmuch);
                        prod.ReduceStock(howmuch);
            }

2) The counter class implements the notification handler for StockLow. Note that the arguments and the void return type. Because the rule is expected by the delegate OnLowStock coupled with the event. Below is the handler:

//002_3: Function that acts as event handler for LowStock to receive the notification
public void LowStockHandler(object Sender, EventArgs e)
{
            Console.WriteLine("Anouncement on {0}: Stock of Product {1} gone Low",
                        CounterName , ((ProductStock) Sender).ProductName );
}

Client Code


Let us see how the client code works. Before that a small refresh on what we did. The ProductStock class exposes an event StockLow and that event is coupled to OnStockLow delegate. ReduceStock function raises the StockLow event when the product stock goes below five. The counter class implements the notification handler LowStockHandler to receive the notification. Where is the piece of code that links the LowStockHandler to the StockLow event? We will link that in the client code.

1) First the client creates the two billing counter objects. Below is the code for billing counter:

//Client 001: Create Billing Counters
Counter billing_counter1 = new Counter("Sindhu");
Counter billing_counter2 = new Counter("Ganga");

2) Next three ProductStock objects are created. These products will be sold through two counters. Below is code:

//Client 002: Create the Product Stocks
ProductStock prod1 = new ProductStock("Godrej Fridge", 7 );
ProductStock prod2 = new ProductStock("Sony CD Player", 6);
ProductStock prod3 = new ProductStock("Sony DVD", 800);

3) Next, we subscribe to the event LowStock published by the ProductStock class by creating the Delegate that points to the Notification handler function implemented in the Counter class. Below is the code:

//Client 003: Couple the Event with the Handler through the Delegate.
prod1.StockLow += new ProductStock.OnStockLow(billing_counter1.LowStockHandler);
prod2.StockLow += new ProductStock.OnStockLow(billing_counter1.LowStockHandler);
prod1.StockLow += new ProductStock.OnStockLow(billing_counter2.LowStockHandler);
prod2.StockLow += new ProductStock.OnStockLow(billing_counter2.LowStockHandler);  

4) Everything setup. So let as start selling the products and see the notification we stock goes below 5. I recommend you to put a breakpoint on the below piece of code and examine how the Events work. Below is the price code:

//Client 004: Now Let us Start serving the customers on the Queue on each counter
billing_counter1.Sales(prod1, 1);
billing_counter2.Sales(prod1, 2);
billing_counter2.Sales(prod3, 70);
billing_counter2.Sales(prod2, 1);
billing_counter1.Sales(prod2, 3);
billing_counter1.Sales(prod3, 5);

Output is shown below



Note: The Attached Solution is created in Dot Net 2003 for backward compatibility. If you have the latest version Say “Yes” to the conversion dialog.

Source Code: Download
Like this site? Tell it to your Firend :)