http://aspnet-simple-samples.blogspot.in/
Save cookie sample
When a user visits your website, you can use cookies to store user login (storing a password is unsecure!) or user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier.
This sample shows how to save cookie and how to retrive it when you visit site another time.
protected void Page_Load(object sender, EventArgs e) { if (Request.Cookies["MyCookie"] != null) txtSavedCookie.Text = "Cookie is: " + Request.Cookies["MyCookie"].Value; else txtSavedCookie.Text = "No cookies!"; } protected void btnSaveCookie_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("MyCookie", txtCookieValue.Text); Response.AppendCookie(cookie); txtResult.Text = "Cookie saved!! Close this site and open it again - you will see saved cookie value at the top of this page!"; }
All our simple samples available as Microsoft Visual Studio 2008 website projects.
You can DOWNLOAD this Save cookie sample project from Rapidshare.
DateTime sample
If you want to display current date or time on the website you can use DateTime.Now property.
This sample shows how to display it using 5 different formats.
protected void Page_Load(object sender, EventArgs e) { Label1.Text = DateTime.Now.DayOfWeek.ToString();//return the current day of week Label2.Text = DateTime.Now.ToLongDateString(); //return the "long date" Label3.Text = DateTime.Now.ToShortDateString(); //return the "short date" Label4.Text = DateTime.Now.ToLongTimeString(); //return the "long time" Label5.Text = DateTime.Now.ToShortTimeString(); //return the "short time" }
All our simple samples available as Microsoft Visual Studio 2008 website projects.
You can DOWNLOAD this DateTime sample project from Rapidshare.
ПЯТНИЦА, 8 ЯНВАРЯ 2010 Г.
String trim sample
If you need to trim string and remove extra spaces from the middle of the string
you can use this simple sample:
string s = TextBox1.Text; s = s.Trim(); // trim left and right spaces while (s.IndexOf(" ") != -1) // it is 2 spaces in the quotes!! { s = s.Remove(s.IndexOf(" "), 1); // remove extra spaces in the middle of the string } Label1.Text = s;
It will take any input string from the TextBox1, i.e. like this:
"___aaa_______bbb_________ccc_ddd__eee_",
where "_" is a space symbol, and trim it to the:
"aaa_bbb_ccc_ddd_eee".
All our simple samples available as Microsoft Visual Studio 2008 website projects.
You can DOWNLOAD this String trim sample project from Rapidshare.
ПОНЕДЕЛЬНИК, 4 ЯНВАРЯ 2010 Г.
File upload sample
In ASP.NET websites you can upload file on server using the FileUpload web UI control.
(You can drag and drop the control from the Toolbox on the Web page in Design mode.)
The user specifies the file to upload by selecting the file by clicking the Browse button, and then locating it in the Choose File dialog box.
The FileUpload control does not automatically save a file to the server after the user selects the file to upload. You must provide a button that the user clicks to upload the file, in our sample it will be "Upload" button. Here is a code of the Upload button handler from our sample:
if (FileUpload1.HasFile) // check whether the selected file { string path = @"C:\Received Files\"; // This specifies the path to the destination path += FileUpload1.FileName; // add the file name to the path FileUpload1.PostedFile.SaveAs(path); // ... and save Label1.Text = FileUpload1.PostedFile.ContentLength.ToString() + " Bytes saved"; } else { Label1.Text = "You have not selected a file to upload"; }
All our simple samples available as Microsoft Visual Studio 2008 website projects.
You can DOWNLOAD this File upload sample project from Rapidshare.
ASP.NET Basic Controls
http://www.dotnetcodecentral.com/Technology/asp-net
How to search for any control on a web page and get value out of it
Following is the screenshot:
Following is the markup:
01.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
02.
03.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04.
<
html
xmlns
=
"http://www.w3.org/1999/xhtml"
>
05.
<
head
runat
=
"server"
>
06.
<
title
></
title
>
07.
</
head
>
08.
<
body
>
09.
<
form
id
=
"form1"
runat
=
"server"
>
10.
<
div
>
11.
<
table
>
12.
<
tr
>
13.
<
td
>
14.
<
asp:Label
ID
=
"Label1"
runat
=
"server"
Text
=
"Enter Value:"
></
asp:Label
>
15.
</
td
>
16.
<
td
>
17.
<
asp:TextBox
ID
=
"TextBox1"
runat
=
"server"
></
asp:TextBox
>
18.
</
td
>
19.
</
tr
>
20.
<
tr
>
21.
<
td
>
22.
<
asp:Label
ID
=
"Label2"
runat
=
"server"
Text
=
"Select Value:"
></
asp:Label
>
23.
</
td
>
24.
<
td
>
25.
<
asp:DropDownList
ID
=
"DropDownList1"
runat
=
"server"
>
26.
<
asp:ListItem
Value
=
"01"
>first</
asp:ListItem
>
27.
<
asp:ListItem
Value
=
"02"
>second</
asp:ListItem
>
28.
<
asp:ListItem
Value
=
"03"
>third</
asp:ListItem
>
29.
</
asp:DropDownList
>
30.
</
td
>
31.
</
tr
>
32.
<
tr
>
33.
<
td
valign
=
"top"
>
34.
<
asp:Label
ID
=
"Label3"
runat
=
"server"
Text
=
"Select Value:"
></
asp:Label
>
35.
</
td
>
36.
<
td
>
37.
<
asp:RadioButtonList
ID
=
"RadioButtonList1"
runat
=
"server"
>
38.
<
asp:ListItem
Value
=
"1"
>Sunday</
asp:ListItem
>
39.
<
asp:ListItem
Value
=
"2"
>Monday</
asp:ListItem
>
40.
<
asp:ListItem
Value
=
"3"
>Tuesday</
asp:ListItem
>
41.
</
asp:RadioButtonList
>
42.
</
td
>
43.
</
tr
>
44.
</
table
>
45.
<
hr
/>
46.
<
table
>
47.
<
tr
>
48.
<
td
>
49.
<
asp:Label
ID
=
"Label4"
runat
=
"server"
Text
=
"Enter control name to get value :"
></
asp:Label
>
50.
</
td
>
51.
<
td
>
52.
<
asp:TextBox
ID
=
"txtControlName"
runat
=
"server"
></
asp:TextBox
>
53.
</
td
>
54.
<
td
>
55.
<
asp:Button
ID
=
"btnShow"
runat
=
"server"
Text
=
"Show Value"
56.
onclick
=
"btnShow_Click"
/>
57.
</
td
>
58.
</
tr
>
59.
<
tr
>
60.
<
td
colspan
=
"3"
>
61.
<
asp:Label
ID
=
"lblMsg"
runat
=
"server"
></
asp:Label
>
62.
</
td
>
63.
</
tr
>
64.
</
table
>
65.
</
div
>
66.
</
form
>
67.
</
body
>
68.
</
html
>
Following is the code behind:
01.
using
System;
02.
using
System.Collections.Generic;
03.
using
System.Linq;
04.
using
System.Web;
05.
using
System.Web.UI;
06.
using
System.Web.UI.WebControls;
07.
08.
namespace
WebApplication1
09.
{
10.
public
partial
class
WebForm1 : System.Web.UI.Page
11.
{
12.
protected
void
Page_Load(
object
sender, EventArgs e)
13.
{
14.
15.
}
16.
17.
protected
void
btnShow_Click(
object
sender, EventArgs e)
18.
{
19.
Control ctl = FindControl(
this
, txtControlName.Text);
20.
if
(ctl ==
null
)
21.
{
22.
lblMsg.Text =
"Not found"
;
23.
}
24.
else
25.
{
26.
lblMsg.Text = GetValueFromControl(ctl);
27.
}
28.
}
29.
30.
private
string
GetValueFromControl(Control ctl)
31.
{
32.
33.
switch
(ctl.GetType().ToString())
34.
{
35.
case
"System.Web.UI.WebControls.TextBox"
:
36.
return
((TextBox)ctl).Text;
37.
case
"System.Web.UI.WebControls.DropDownList"
:
38.
DropDownList ddl = ((DropDownList)ctl);
39.
if
(ddl.SelectedItem !=
null
)
40.
{
41.
return
ddl.SelectedItem.Value;
42.
}
43.
break
;
44.
case
"System.Web.UI.WebControls.RadioButtonList"
:
45.
RadioButtonList rbl = ((RadioButtonList)ctl);
46.
if
(rbl.SelectedItem !=
null
)
47.
{
48.
return
rbl.SelectedItem.Value;
49.
}
50.
break
;
51.
}
52.
53.
return
string
.Empty;
54.
55.
}
56.
57.
private
Control FindControl(Control parent,
string
sCtlToFind)
58.
{
59.
//search for control in either upper/lower case
60.
if
(
string
.Compare(parent.ID, sCtlToFind,
true
) == 0)
return
parent;
61.
62.
foreach
(Control ctl
in
parent.Controls)
63.
{
64.
Control ctlToReturn = FindControl(ctl, sCtlToFind);
65.
if
(ctlToReturn !=
null
)
return
ctlToReturn;
66.
}
67.
return
null
;
68.
}
69.
}
70.
}
.NET Framework 3.5, Visual Studio 2008
http://www.mini.pw.edu.pl/~mossakow/materials/presentations/index.html
Silverlight 3
Windows Presentation Foundation (WPF)
Windows Forms
ADO.NET
LINQ
ASP.NET
XML Web Services
Windows Communication Foundation (WCF)
Windows Workflow Foundation (WF)
|
||
|
||
|
||
|
||
Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding OOP.
The designers of auto mobiles sit in front of their computer (or use paper and pencil) and describe exactly the parts of the auto mobile. They describe how these parts interact, the colour of the car, the height of the car, the size of the engine, the acceleration of the car, if the car has air-conditioning system installed. Then the mechanics that observe the production line, make sure that the cars built (the actual cars) follow the blueprints outlined in the design stage of building a car. So a class is a way of describing real world entities. It is the code definition for objects. The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract (in theory) all of the characteristics and behaviour of an object. The object on the other hand is the instance of a class. The real thing, if you excuse my slang… So we must start thinking about modelling our applications in terms of objects. When someone, who has hired us to implement a web site-commerce site for his business, he could outline his view of the web site in plain words… ” I would like to have a site where I can keep track of the sales-orders that were placed through the site. I also would like to be able to see the customer details and manage my employees details”, Then you must think in terms of Orders,Customer,Employee classes-objects for this particular scenario. This is a first attempt of Abstraction for the scenario above. Abstraction is the process of representing simplified versions of real-world objects in your classes and objects. Programming with the OOP paradigm is to decide what a class should represent and breaking down your code into a group of interrelated classes. Members of a class The first thing after finalising the class names is to identify the members of a class. I will talk about Properties, methods and events. As we go on I will talk in greater detail about class members.
Methods, properties and events can be considered as the public interface of a class. Now we are ready to move on and practice what we have been saying so far. I assume that people who will read this post, have some experience with C# and Visual studio as a development platform. I will use Visual Studio 2008 Professional edition. People who have downloaded and installed Visual web developer 2008 can also follow these examples. You can download Visual Web Developer by clicking here . I will create an ASP.NET application. I will create a base class and then take it from there and try to highlight all the concepts mentioned above. The point of this example is not create super sophisticated classes and methods but to create a simple class with plain properties and methods. 1) Launch VS 2008 2) Go to File->New->Project 3) From the templates, choose ASP.NET web application. Make sure you select C# as the language of development 4) Give a name for your project. I name it “LearnCLass”. Click OK on the Templates window. 5) You will have 2 main files, Default.aspx and Default.aspx.cs Building a basic class The class I will construct regards a Person class.This class can represent any person, e.g the customer of an e-commerce shop.The Person class will store the person’s data, and it will include the built-in functionality needed to generate a block of HTML that displays the person details on a web page. We will test this class with an ASP.NET page. Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight . In your default.aspx.cs (code behind file) you have something like this: using System;Then add the class definition public class PersonNow we have the class definition we need to creating an object. We must use new keyword to do that. The new keyword instantiates the object, which means it creates a copy of the class in memory. If you define an object but don’t instantiate it, you’ll receive an error from the compiler.The members of a class (methods and properties) are accessed using dot ‘.’ operator against the reference of the object. In the Page _Load event handling routine type protected void Page_Load(object sender, EventArgs e)Run your application by hitting F5 from the keyboard and see the results. What I am trying to highlight here, is how to create an object from a class.The bit that does it is this:
Person mynewperson;
One could write it in a single line |
Inheritance
I know a lot people who use Inheritance in their applications without even realizing.
If you look at the Default.aspx.cs you can see
public partial class _Default : System.Web.UI.Page
In plain English , this means that every web page we create is a child of the Page class. Inheritance is a form of code reuse. It allows one class to acquire and extend the functionality of another class. There is no need to reinvent the wheel when other people have done this for you. Instead of that you have only to think about the peculiarities of the project at hand.
Let’s assume that we need to create another class,called Student.
In this class we want to inherit the functionality of the Person class or base class.
class Student : Person
Then we want to extend the Parent class. We want to create a new simple method to calculate the total marks achieved by the student.The whole Student class follows. I have explained in detail properties and methods in previous paragraphs.
class Student : Person
{
private int _marksEnglish;
private int _marksLiterature;
private int _marksIT;
private int _marksMaths;
private int marksTotal;
public int marksEnglish
{
get
{
return _marksEnglish;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksEnglish = value;
}
}
public int marksLiterature
{
get
{
return _marksLiterature;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksLiterature = value;
}
}
public int marksMaths
{
get
{
return _marksMaths;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksMaths = value;
}
}
public int marksIT
{
get
{
return _marksIT;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksIT = value;
}
}
public int CalculateTotalMarks()
{
marksTotal = marksEnglish + marksLiterature + marksIT + marksMaths;
return marksTotal;
}
}
In our Page_Load event , we can create a new object of type Student.
Student mystudent = new Student();If you pay attention even though we did not define the Name and Surname properties for the Student class, they are available to the class, since they are inherited. The same applies for the CalculateAge method.
Response.Write(“</br>”);
mystudent.Name=”fofo”;
Response.Write(mystudent.Name);
mystudent.marksEnglish = 12;
mystudent.marksLiterature = 13;
mystudent.marksIT = 18;
mystudent.marksMaths = 17;
mystudent.CalculateTotalMarks();
Response.Write(mystudent.CalculateTotalMarks());
Some things worth mentioning regarding inheritance are:
- C# allows only single class inheritance
- Multiple inheritance of classes is not allowed in C#
- The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# and the .NET framework
- A class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
Let’s create a new method in the base class (Person) that we want to override it later on the child class. It is just a method that calculates the pay of a person.
public double CalculatePay(double hoursWorked, double wageperhour,double tax)This method is inherited in the Student class. Let’s assume that we live in a fantastic world where student’s money is not taxed if the student worked less than 100 hours.
{
return (hoursWorked * wageperhour * tax);
}
The first thing to do is to add the word virtual to the CalculatePay method.So we have:
public virtual double CalculatePay(double hoursWorked, double wageperhour,double tax)and then to use the word override in Student class CalculatePay method
{
return (hoursWorked * wageperhour * tax);
}
public override double CalculatePay(double hoursWorked, double wageperhour,double tax)If we want to stop overriding a class we can use the special word sealed. This means that this class cannot be used as the basis for another class.
{
if (hoursWorked > 100)
{
return (hoursWorked * wageperhour * tax);
}
else
{
return (hoursWorked * wageperhour);
}
}
From our Page_Load event we can call this
Response.Write(mystudent.CalculatePay(45, 4, 0.45));
By calling the line above the CalculatePay method of the student class will be invoked.This relationship between virtual methods and the derived class methods that override them enables polymorphism.
if you change the
public class Person to public sealed class Person
and run your application you will receive an error
“cannot derive from sealed type ‘LearnCLass._Default.Person“
Now it is time to see in greater detail method overloading.
In our Person class we can define a new method
public string JoinNames(string name, string surname)Now we could have a different implementation of the method above.
{
return name + ” ” + surname;
}
public string JoinNames(string prefix, string name, string surname)In our Page_ Load event if we write the line:
{
return prefix + ” ” + name + ” ” + surname;
}
mynewperson.JoinNames(“Mr”,”nikos”, “kantzelis”)
The compiler will not complain. It will know which method to invoke depending on the number of the parameters-arguments it “sees”.Polymorphism (from the Greek meaning “having multiple forms” – “Poly” means many and “morphy” means “shape”) can be achieved by overloading a method.
What is a static class?
In .NET we can use some class members without creating an object first. These are called static members, and they’re accessed by class name. So far in the previous examples we have seen the static property DateTime.Now to retrieve a DateTime object that represents the current date and time. We didn’ create a DateTime object first.
If we wanted to have a method that determines whether a person can hold a valid driving licence, the method would look like this.
public bool AllowedToDrive(int age)The method above is a good candidate to become a static method.In order to do that, we just add the word static
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}
}
public static bool AllowedToDrive(int age)In our Page_Load event routine,we can write
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}
}
Person.AllowedToDrive(22)
As you see we do not need an object to invoke our method, just the class name.
So a static member is a member of the class and not a member of an instance of the class.
It takes some experience to determine which methods or classes. One common place where we find static classes and methods is the creation of libraries that provide general functionality, e.g find the square root of a number, find the perimeter of a circle.
The next thing to review is Interfaces. I will not cover Interfaces in detail because you can find another post of mine on Interfaces on this blog.
The Interface is basically a contract between a the Interface and a class. In the Interface we do not have implementation of properties of methods.
The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.
A .NET interface is similar to an abstract class in the sense that it’s a kind of a template. More on abstract classes later.
If we define an interface like this
interface IPersonand if we say that the Person class implements the IPerson Interface
{
double DaysVacation(int yearsOfWork);
}
class Person : IPerson
the Person class must in its body implement the DaysVacation(int yearsOfWork) method.public double DaysVacation(int yearsOfWork)What is an abstact class?
{
if (yearsOfWork > 25)
{
return 25;
}
else if (yearsOfWork < 25 && yearsOfWork > 20)
{
return 20;
}
else
{
return 10;
}
}
If we need to provide common fields and members to all subclasses, we create an Abstract class. We can create an abstract class, with the use of the abstract keyword. Abstract classes cannot be instantiated. In our example if we decide that there are some things that an object of type Person must do, then we can make the class Person abstract and then get the clild classes to provide the implementation. I will create another class to demonstrate abstract classes, because we need to change los of code in the Person class and I do not want to do that.
In abstract classes we can have abstract members and virtual members. An abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile. A virtual member must be implemented in the base class, and if need be (optionally) overriden in the derived class if want the child method to do something different.
Let’s define our abstract Vehicle class.
public abstract class VehicleNow we can have another class Car that can inherit from the Vehicle class. The method Accelerate in the Vehicle class must be implemented in the child class.
{
public string Model { get; set; }
public string Color { get; set; }
public int NumOfDoors { get; set; }
public int NumoOfWheels { get; set; }
public Vehicle(string model, string color)
{
this.Color = color;
this.Model = model;
}
public abstract string Accelarate(int speed);
public virtual double CalculatePetrolCostPerDistance( double distance)
{
double costperkilometer=0.25;
double res;
res = distance * costperkilometer;
return res;
}
}
public class Car : VehicleWe can create and use an object type Car in our Page_Load event handling routine
{
public Car(string model, string color): base(model,color)
{
//code to be added
}
public override string Accelarate(int speed)
{
return “I can accelerate. My speed is right now:”+speed.ToString();
}
public override double CalculatePetrolCostPerDistance(double distance)
{
double costperkilometer = 0.45;
double res;
res = distance * costperkilometer;
return res;
}
}
Car mycar = new Car( “bmw”, “silver”);In the child class I have implemented a simple version of the Accelarate method by using the override keyword and I chose to ovveride CalculatePetrolCostPerDistance. But If i did not need any different behaviour for the CalculatePetrolCostPerDistance then that would be ok, my class would compile just fine.
Response.Write(mycar.Accelarate(134));
Response.Write(“</br>”);
Response.Write(“The cost is: ” + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +” euros”);
Abstract classes are a lot like interfaces, however abstract classes are different in that they contain fully implemented methods alongside the abstract ones.So we do not have to implement the same methods in each of the components that implement a particular interface. An abstract class can contain fields, constructors, or destructors and implement properties while an interface cannot.
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.
What is a delegate?
For more information on this topic have a look at this post of mine.
What is Generics ?
Same applies here. I have another single post on Generics and I do not see any point repeating myself.
What is a namespace?
In my solution in the Default.aspx.cs , I have the namespace LearnCLass namespace. All my classes and code is included in this namespace.
Namespaces are a logical way to group classes. Let me give you an example of what it means. It is a way that we can identify a class beyond doubt.
Imagine that you want to phone an old friend that you have lost track, so you can invite him to your wedding. So you phone the phone directory service.
Your friend’s name is George Patouxas. The operator lets you know that there are 100 people with this name coming up. Then you tell the operator that his mother’s name and father’s name are Maria and John respectively. BINGO!! The operator tells you there is only match. So in our example the LearnCLass.Person class resides in this specific namespace and if someone wants to use it, he can use the using LearnCLass.Person declaration.
That is exactly why namespaces are for in .NET. We try to group related classes in namespaces and all of them that reside in this particular namespace will be uniquely identified.
If I have a class called Calculate in my LearnClass namespace, then there will be no conflict if need be to use another component from a third party that has also a Calculate Class.
That Calculate class will reside in the AnotherNameSpace so there will be no conflict.
Please note that in the beginning of the Default.aspx.cs we import namespaces that we need to using System.Web.UI;
Assemblies
All .NET classes (built-in or custom made) are contained in assemblies. Assemblies are the physical files that contain compiled code. Assembly files have the extension .exe if they are stand-alone applications or .dll if they’re reusable components. Assemblies are a physical package for distributing code. Often, assemblies and namespaces have the same names. For example, you’ll find the namespace System.Web in the assembly file System.Web.dll.
But in many cases there is no direct mapping between assemblies and namespaces.
What is Casting?
When we talk about casting, we can think of this concept in terms of narrowing and widening. If you move a value from one type to another that narrows the value, it will ask you to explicitly do it yourself. When you move a value from one type to another by widening it, it does not complain.
By widening I mean that if I have the declaration:
This will be fine because the floating point type can hold all the values supported by the integer type.int mynum=5;
float anothernum=mynum;
If I have this statement (narrowing)
the compiler will complain.double mynum = 3.5;
float thenum = mynum;
Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)
The compiler is basically saying “Is there any chance you are discarding information?”
But you can cast the value by using this statement.
This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.double mynum = 3.5;
float thenum = (float)mynum;
For reference types, if we have a situation like this, where the derived type (Student) is converted to base type (Person), we have imlicit conversion which is safe.
while if we type this:Student thestudent = new Student();
this will fail and we must explicitly cast it to the Student type, like this.Person theperson=new Person();
Hope it helps. If you need the source code, leave a comment and I will email it to you.Person theperson=new Person();
Student thestudent = (Student)theperson;
Object-Oriented Programming Concepts and .NET
http://www.dotnettreats.com/tipstricks/oopconcepts1.aspx
Part 1: Classes, Objects, and Structures in .NET
Summary
The following article kicks off a three-part article series that
will present definitions and samples for different Object-Oriented
Programming concepts and its implementation
in .NET. The first part will examine the concepts of classes,
objects, and structures.
The second part will examine the concepts of inheritance,
abstraction, and polimorphism.
The third and last part will examine the concepts of interface,
multiple interface
inheritance, collections, and overloading.
Contents
Introduction
Object-Oriented Programming (OOP) is a software development
paradigm that suggests developers to split a program in building blocks
known as objects. The OOP paradigm allows developers to define the
object’s data, functions, and its relationship with other objects.
Microsoft created the .NET Framework
using OOP, and knowing this concepts has helped me to understand the
.NET Framework and to design and develop better software components. The
purpose of this article is to describe the basic OOP concepts using
real world scenarios and to provide some code
samples that demonstrate how to work with OOP and .NET.
Class
The most common definition states that a class is a template for an object.
Suppose that someone builds a paper pattern for a shirt. All the shirts done with
the same paper pattern will be identical (same design, size, etc.). In this sample,
the paper pattern is the class and the shirt is the object. To build the same exact
shirt over and over, you need the paper pattern as a template. Another great
example are house plans and blueprints. The plans and blueprints define the number
of rooms, the size of the kitchen, the number of floors, and more. In this real world
sample, the house plans and blueprints are the class and the house is the object.
In OOP you
program a class as a template for a specific object or groups ob objects
that will always have the same features.
Class members
A class has different members, and developers in Microsoft
suggest to program them in the following order:
- Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
- Class declaration: Line of code where the class name and type are defined.
- Fields: Set of variables declared in a class block.
- Constants: Set of constants declared in a class block.
- Constructors: A method or group of methods that contains code to initialize the class.
- Properties: The set of descriptive data of an object.
- Events: Program responses that get fired after a user or application action.
- Methods: Set of functions of the class.
- Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.
Access keywords
Access keywords define the access to class members from the same class and from
other classes. The most common access keywords are:
- Public: Allows access to the class member from any other class.
- Private: Allows access to the class member only in the same class.
- Protected: Allows access to the class member only within the same class and from inherited classes.
- Internal: Allows access to the class member only in the same assembly.
- Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
- Static: Indicates that the member can be called without first instantiating the class.
The following sample code illustrates a sample class in C#:
/// C#
///Imported namespaces
using System;
/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {
///Class declaration
public class employee {
///Fields
private string _name;
private int _salary;
///Constants
private const int anualBonus = 1000;
///Constructor
public employee(){
}
///Properties
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int Salary {
get {
return _salary;
}
set {
_salary = value;
}
}
/// Event handlers
public event EventHandler OnPromotion {
add {
}
remove {
}
}
/// Methods
public void DuplicateSalary() {
_salary = _salary*2;
}
}
}
///Imported namespaces
using System;
/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {
///Class declaration
public class employee {
///Fields
private string _name;
private int _salary;
///Constants
private const int anualBonus = 1000;
///Constructor
public employee(){
}
///Properties
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int Salary {
get {
return _salary;
}
set {
_salary = value;
}
}
/// Event handlers
public event EventHandler OnPromotion {
add {
}
remove {
}
}
/// Methods
public void DuplicateSalary() {
_salary = _salary*2;
}
}
}
Listing 1. Sample class implementation in C#
The following sample code illustrates a sample class in VB.NET:
' VB.NET
'Imported namespaces
Imports System
' Namespace: Consider using CompanyName.Product.ComponentType
Namespace DotNetTreats.OOSE.OOP_VBNET
'Class declaration
Public Class employee
'Fields
Private _name As String
Private _salary As Integer
'Constants
Private Const anualBonus As Integer = 1000
'Constructors
Public Sub New()
MyBase.New
End Sub
'Properties
Public Property Name As String
Get
Return _name
End Get
Set
_name = value
End Set
End Property
Public Property Salary As Integer
Get
Return _salary
End Get
Set
_salary = value
End Set
End Property
' Event handlers
Public Event OnPromotion As EventHandler
'Methods
Public Sub DuplicateSalary()
_salary = (_salary * 2)
End Sub
End Class
End Namespace
'Imported namespaces
Imports System
' Namespace: Consider using CompanyName.Product.ComponentType
Namespace DotNetTreats.OOSE.OOP_VBNET
'Class declaration
Public Class employee
'Fields
Private _name As String
Private _salary As Integer
'Constants
Private Const anualBonus As Integer = 1000
'Constructors
Public Sub New()
MyBase.New
End Sub
'Properties
Public Property Name As String
Get
Return _name
End Get
Set
_name = value
End Set
End Property
Public Property Salary As Integer
Get
Return _salary
End Get
Set
_salary = value
End Set
End Property
' Event handlers
Public Event OnPromotion As EventHandler
'Methods
Public Sub DuplicateSalary()
_salary = (_salary * 2)
End Sub
End Class
End Namespace
Listing 2. Sample class implementation in VB.NET
Object
Objects are the building blocks of OOP and are commonly defined as variables
or data structures that encapsulate behavior and data in a programmed unit.
Objects are items that can be individually created, manipulated, and represent real
world things in an abstract way.
Object composition
Every object is composed by:
- Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined.
- Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.
- Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.
Structures
Not everything in the real world should be represented as a
class. Structures are suitable to represent lightweight objects.
Structures can have methods and properties and are useful
for defining types that act as user-defined primitives, but
contain arbitrary composite
fields. The .NET Framework defines some structures such as System.Drawing.Rectangle,
System.Drawing.Point, and System.Drawing.Color.
The following code sample represents a structures in C#:
/// C#
struct Point {
private int _x;
private int _y;
Point(int x, int y){
this._x = x;
this._y = y;
}
public int X {
get {
return _x;
}
set {
_x = value;
}
}
public int Y {
get {
return _y;
}
set {
_y = value;
}
}
}
struct Point {
private int _x;
private int _y;
Point(int x, int y){
this._x = x;
this._y = y;
}
public int X {
get {
return _x;
}
set {
_x = value;
}
}
public int Y {
get {
return _y;
}
set {
_y = value;
}
}
}
Listing 3. Sample structure implementation in C#
The following code sample represents a structure in VB.NET:
' VB.NET
Structure Point
Private _x As Integer
Private _y As Integer
Sub New(ByVal x As Integer, ByVal y As Integer)
MyBase.New
Me._x = x
Me._y = y
End Sub
Public Property X As Integer
Get
Return _x
End Get
Set
_x = value
End Set
End Property
Public Property Y As Integer
Get
Return _y
End Get
Set
_y = value
End Set
End Property
End Structure
Structure Point
Private _x As Integer
Private _y As Integer
Sub New(ByVal x As Integer, ByVal y As Integer)
MyBase.New
Me._x = x
Me._y = y
End Sub
Public Property X As Integer
Get
Return _x
End Get
Set
_x = value
End Set
End Property
Public Property Y As Integer
Get
Return _y
End Get
Set
_y = value
End Set
End Property
End Structure
Listing 4. Sample structure implementation in VB.NET
Conclusion
OOP is full of abstract concepts, and the best approach to understand them is practical
and not only theoretical. I learned more OOP after making some designs
and after implementing some components. The concepts presented in this article might
clarify the meaning, but I strongly recommend to go and have fun playing around
with OOP. In this article, I examined the concept of classes, objects, and structs.
The second part will examine the concepts of inheritance, abstraction, and polimorphism.
Object-Oriented Programming Concepts and .NET
Part 2: Inheritance, Abstraction, and Polimorphism in .NET
Summary
The following article is the second of a three-part article series that presents
definitions and samples for different Object-Oriented
Programming (OOP) concepts and its
implementation in .NET. The first part examined the concepts of classes, objects,
and structures. This part examines the concepts of inheritance, abstraction, and polimorphism.
The third and last part will examine the concepts of interface, multiple interface
inheritance, collections, and overloading.
Contents
Introduction
In Part 1 of Object-Oriented Programming Concepts and .NET, I defined the concepts
of class, object, and structure. In addition to defining the concepts, I explained
real world samples and presented sample code in C# and VB.NET to create classes
and structs. The first article also explains objects as independent building blocks.
In Part 2 of Object-Oriented Programming Concepts and .NET, I will explain the concepts
of inheritance, abstraction, and polimorphism. I will also present a Unified Model
Language (UML) class diagram to represent an object model that will help as a visual
aid to explain some concepts. The purpose of this article is to explain a series of
relationships between objects.
Inheritance
In the real world there are many objects that can be specialized. In OOP, a parent
class can inherit its behavior and state to children classes. This concept was developed
to manage generalization and specialization in OOP and is represented by a is-a relationship.
The following OO terms are commonly used names given to parent and child classes
in OOP:- Superclass: Parent class.
- Subclass: Child class.
- Base class: Parent class.
- Derived class: Child class
The most common real world sample to explain inheritance is the geometric shapes
object model. Squares, circles, triangles,
rectangles, pentagons, hexagons, and
octagons are geometric shapes.
The following figure shows a sample set of geometric figures:
Figure 1. Geometric shapes.
The concept of generalization in OOP means that an object encapsulates
common state an behavior for a category of objects. The general object in this sample
is the geometric shape. Most geometric shapes
have area, perimeter, and color. The
concept of specialization in OOP means that an object can inherit the common
state and behavior of a generic object; however, each object needs to define its
own special and particular state an behavior. In Figure 1, each shape has its own
color. Each shape has also particular formulas to calculate its area and perimeter.
Inheritance makes code elegant and less repetitive. If we know that all shapes have
color, should we program a color attribute for each shape? The answer is no! Would
it be a better idea to create a shape class that has a color attribute and to make
all the specialized shapes to inherit the color attribute? The answer is yes!An object model for this sample could have a shape parent class and a derived class for each specific shape. The following UML class diagram shows the set of classes needed to model the geometric shapes sample. Observe the field, properties, and methods for each class:
Figure 2. The Shape class is the parent class. Square, Rectangle, and Circle
are derived classes that inherit from Shape. The triangle-connector in
the diagram represents an is-a relationship.
The .NET framework has many base classes. Everything is derived from System.Object.
You can create almost anything you imagine using the built-in functionality provided
in the
.NET Framework Class Library.
To create a derived class in C#, the class declaration should be done as:
class child: parent
To create a derived class in VB.NET, the class declaration should be done as:
Class child
Inherits parent
End Class
Inherits parent
End Class
Multiple inheritance
Multiple inheritance is the possibility that a child class can have multiple parents.
Human beings have always two parents, so a child will have characteristics from
both parents.
In OOP, multiple inheritance might become difficult to handle because it allows
ambiguity for the compiler. There are programming languages such as C++ that allow
multiple inheritance; however, other programming languages such as Java and the
.NET Framework languages do not allow multiple inheritance. Multiple inheritance
can be emulated in .NET using Multiple Interface Inheritance, which I will explain
in Part 3 of this series.
Sealed class
A sealed class is a class that does not allow inheritance. Some object model
designs need to allow the creation of new instances but not inheritance, if this is the case, the class
should be declared as sealed.
To create a sealed class in C#, the class declaration should be done as:
sealed class Shape
To create a sealed class in VB.NET, the class declaration should be done as:
NotInheritable Class Shape
Abstraction
Abstraction is "the process of identifying common patterns that have systematic
variations; an abstraction represents the common pattern and provides a means for
specifying which variation to use" (Richard Gabriel).
An abstract class is a parent class that allows inheritance but can never be instantiated.
Abstract classes contain one or more abstract methods that do not have implementation.
Abstract classes allow specialization
of inherited classes.
Figure 2 shows a Shape class, which is an abstract class. In the real world,
you never calculate the area or perimeter of a generic shape, you must know what
kind of geometric shape you have because each shape (eg. square, circle, rectangle,
etc.) has its own area and perimeter formulas. The parent class shape forces all
derived classes to define the behavior for CalculateArea() and CalculatePerimeter().
Another great example is a bank account. People own savings accounts, checking accounts,
credit accounts, investment accounts, but not generic bank accounts. In this case,
a bank account can be an abstract class and all the other specialized bank accounts
inherit from bank account.
To create an abstract class in C#, the class declaration should be done as:
abstract class Shape
To create an abstract class in VB.NET, the class declaration should be done as:
MustInherit Class Shape
To following code shows a sample implementation of an abstract class:
/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples{
public abstract class Shape{
private float _area;
private System.Drawing.Color _color;
private float _perimeter;
public float Area{
get{
return _area;
}
set{
_area = value;
}
}
public System.Drawing.Color Color{
get{
return _color;
}
set{
_color = value;
}
}
public float Perimeter{
get{
return _perimeter;
}
set{
_perimeter = value;
}
}
public abstract void CalculateArea();
public abstract void CalculatePerimeter();
}
}
using System;
namespace DotNetTreats.OOSE.OOPSamples{
public abstract class Shape{
private float _area;
private System.Drawing.Color _color;
private float _perimeter;
public float Area{
get{
return _area;
}
set{
_area = value;
}
}
public System.Drawing.Color Color{
get{
return _color;
}
set{
_color = value;
}
}
public float Perimeter{
get{
return _perimeter;
}
set{
_perimeter = value;
}
}
public abstract void CalculateArea();
public abstract void CalculatePerimeter();
}
}
Listing 1. The Shape abstract class in C#.
Polimorphism
Polimorphism allows objects to be represented in multiple forms. Even though classes
are derived or inherited from the same parent class, each derived class will have
its own behavior. Polimorphism is a concept linked to inheritance and assures
that derived classes have the same functions even though each derived class performs
different operations.
Figure 2 shows a Rectangle, a Circle, and Square. All of them are shapes and
as shapes their area and perimeter can be calculated; however, each shape calculates its
area in a specialized way. Declaring a member as abstract allows polimorphism.
The Shape class defines the CalculateArea() and CalculatePerimeter()
methods as abstract, this allows each derived class to override the implementation
of the parent's methods.
To following sample code shows an implementation of a derived class (rectangle).
The specific CalculateArea() and CalculatePerimeter() methods
for the rectangle class illustrate polimorphism:
/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples{
class Rectangle : Shape{
private float _height;
private float _width;
public rectangle(float height, float width){
_height = height;
_width = width;
}
public float Height{
get{
return _height;
}
set{
_height = value;
}
}
public float Width{
get{
return _width;
}
set{
_width = value;
}
}
public override void CalculateArea(){
this.Area = _height * _width;
}
public override void CalculatePerimeter(){
this.Perimeter = (_height * 2) + (_width * 2);
}
}
}
using System;
namespace DotNetTreats.OOSE.OOPSamples{
class Rectangle : Shape{
private float _height;
private float _width;
public rectangle(float height, float width){
_height = height;
_width = width;
}
public float Height{
get{
return _height;
}
set{
_height = value;
}
}
public float Width{
get{
return _width;
}
set{
_width = value;
}
}
public override void CalculateArea(){
this.Area = _height * _width;
}
public override void CalculatePerimeter(){
this.Perimeter = (_height * 2) + (_width * 2);
}
}
}
Listing 2. Polimorphism represented in the Rectangle's methods.
Virtual keyword
The virtual keyword allows polimorphism too. A virtual property
or method has an implementation in the base class, and can be overriden
in the derived classes.
To create a virtual member in C#, use the virtual keyword:
public virtual void Draw()
To create a virtual member in VB.NET, use the Overridable keyword:
Public Overridable Function Draw()
Override keyword
Overriding is the action of modifying or replacing the implementation of the parent
class with a new one. Parent classes with virtual or abstract members allow derived
classes to override them.
To override a member in C#, use the override keyword:
public override void CalculateArea()
To override a member in VB.NET, use the Overrides keyword:
Public Overrides Function CalculateArea()
Conclusion
Inheritance allows developers to manage a generalization and specialization relationship
between objects. OOP concepts such as abstraction and polimorphism help to define
better object models where object hierarchies are designed with reusability in mind.
In this article, I examined the concept of inheritance, abstraction, and polimorphism.
The third and last part of this series will examine the concepts of interface, multiple
interface inheritance, collections, and overloading.
A To Z Of ASP.Net
http://aspdotnetchamp.blogspot.in/
Validators in ASP.Net – Part 5 : Custom Validator Control
Custom validator Control:
In my previous posts, I have explained 4 validation controls. In this post I’m going to explain Custom validation control. In some situations we need to customization on validations. At this time Custom validator comes in to picture.
Custom Validator provides 2 ways to do your validation. One is Client side and another one is Server side. User can achieve the Server side validation by using the property “OnServerValidate” property. In this property user must give the server side function name which handles the validation.
A Word about Client Side and Server Side Validation
Most of the programmers are aware about the 2 types of validation. One is Server side validation and another one is Client side validation. Each of them had advantages and disadvantages also. For novice programmers, I just want to give brief intro about these.
Validators in ASP.Net – Part 4 : Regular Expression Validator
Regular Expression Validator:
In my previous posts, I have covered about 3 types of validators. In some situations the above 3 validators are helpful till some extend. Such that they may provide the flexibility to cover basic validation functionality. Regular Expression validator provide a step ahead functionality.
For example if you want to validate to check the text box, to accept a valid Email address or phone no in a particular format at these times Regular Expression validator comes to picture.
Validators in ASP.Net – A word about WebResource.axd
A WORD ABOUT WEBRESOURCE.AXD:
Its time to speak about the resource files, (As validation controls concern) which is included whenever the validation controls included in a aspx page.
In older version of ASP.Net, the file “WebUIValidation.js” has been directly pointed out thru <script> tag. As we all know “WebUIValidation.js” is resides on the web server’s .Net installation folder,
Validators in ASP.Net – Part 2
Range Validator:
In my Previous post, I have explain about the Required Field Validator. In this article I’m going to explain about the Range Validator.Like Required Field Validator, Range validator is a server side control, which is used to validate a value falls between 2 values.
In my Previous post, I have explain about the Required Field Validator. In this article I’m going to explain about the Range Validator.Like Required Field Validator, Range validator is a server side control, which is used to validate a value falls between 2 values.
Validators in ASP.Net - Part 1
For any application, validation performs a key role. For this Microsoft provides the following types of validators:
1. Required Field validator
2. Regular Expression Validator
3. Range Validator
4. Compare Validator
5. Custom Validator
6. Validation Summary
First ASP .Net Application : The Solution
In my previous post, I have explained how to add a VB.Net Web Solution. In this article I'm going to -provide the solution. If you want to see my previous post click here.
First ASP .Net Application
In this first article, I’m going to take a simple program and explain it in detail. As I told already, I’m going to explain the concepts using the language VB.Net. So the coding snippets in VB.Net only.
So this is the first tutorial, I took a simple problem which cover almost everything ( I meant, it covers ADO.Net, SQL Server Connection etc).
The Problem:
So in this tutorial, I explained how to add an Visual Studio project. In the next tutorial, I will explain the concepts.
Happy Programming!!!!
So this is the first tutorial, I took a simple problem which cover almost everything ( I meant, it covers ADO.Net, SQL Server Connection etc).
The Problem:
In a web form (don’t confuse what is a web form!!!) I’m going to add the 2 dropdown namely:Create A Project in Visual Studio:
1) Country Dropdown
2) State Dropdown
The Country Drop down contains a list of countries and the state contains list of states. Whenever the user select the country from country drop down, the respective states which is located on that Country will be loaded in to the State drop down.
Before that I will explain step by step how to add a project ASP.Net in Visual Studio 2010.Step 3:
Step 1:
Open Visual Studio 2010. The Visual studio startup screen look like this.
Step 2:
Click on “New Project”, which opens the following screen. Please take a close look in the highlighted areas.
I have choosen, Visual Basic as a languge, “ASP.Net Web Application” as Project Template and "Target Framework version as 3.5.
After clicking on the “OK” button in the above screen. Solution file named as “AllInOne” will be loaded in Visual Studio.
Step 4:
In the right hand side a little window called as “Solution Explorer”, which listed all the files by clicking the “Show All Files” icon. (Take a look at the highlighted area).
So in this tutorial, I explained how to add an Visual Studio project. In the next tutorial, I will explain the concepts.
Happy Programming!!!!
Beginning ASP.Net
How to begin ASP.Net without these tools? So before that you need the following:
1. Visual Studio 2005 (OR) 2008 (OR) 2010
2. ASP.Net 2.0/3.0/3.5
If you want to connect databases like SQL Server then you need to install SQL Server also.
You can download all the above in the following link: http://www.asp.net/downloads
In the above link, you can only download express editions of Visual Studio 2010 and SQL Server Database.
1. Visual Studio 2005 (OR) 2008 (OR) 2010
2. ASP.Net 2.0/3.0/3.5
If you want to connect databases like SQL Server then you need to install SQL Server also.
You can download all the above in the following link: http://www.asp.net/downloads
In the above link, you can only download express editions of Visual Studio 2010 and SQL Server Database.
RPA online training
ReplyDeleteRuby on rails online training
Abinitio online training
Android online training
Ansible online training
Appium online training