ASPDotnet with C#

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

  • Introduction
    • Silverlight Application
    • Silverlight Navigation Application
      • Frame and Pages
    • Hosting a Silverlight application in the ASP.NET Web application
  • Browser and Web Page Integration
    • Integration with a Web page
      • Embedding Silverlight objects using HTML code
      • Embedding Silverlight objects using JavaScript code
    • HTML Bridge
      • Calling JavaScript code from Silverlight
      • Calling Silverlight code from JavaScript
    • Custom splash screen
    • Full-screen
    • Out-of-browser
      • Updating an application
  • Isolated Storage
    • Using isolated storage:
      • Listing content of the isolated storage
      • Creating directories and files
      • Copying files from and to the file system
      • Increasing the quota
    • OpenFileDialog and SaveFileDialog
    • Application exceptions
  • ADO.NET Data Services
    • Using ADO.NET Data Services
    • Binding data to the ComboBox and DataGrid controls

Windows Presentation Foundation (WPF)

  • Introduction
    • The simplest WPF application generated by Visual Studio
    • Adding some content to windows using Visual Studio Designer
    • The XBAP application
  • Controls & Layout
    • Using images
    • Adding content to controls
    • Templates
    • Styles
    • Layout - Canvas, StackPanel, DockPanel, WrapPanel, UniformGrid, Grid
    • Custom command

Windows Forms

  • Introduction
    • The simplest Windows Forms application
    • Creating Windows Forms using Visual Studio Designer
    • Examples of using Windows Forms controls
    • Drawing using GDI+
    • Using dialog boxes in Windows Forms
    • Using a background worker thread
  • Custom Controls
    • Example of creating a Windows Forms custom control
    • Creating an editor class
    • Creating a designer class
    • Creating a type converter class
    • Adding a custom control to the toolbox

ADO.NET

  • Visual Studio Server Explorer
    • (just a few words for beginners)
  • Connected Scenario
    • DbProviderFactories
    • DbDataReader
    • DbCommand, DbParameter
    • Windows Forms, manual filling of controls
    • SQL Server 2005/2008, the Northwind database
  • Untyped DataSets
    • DataSet
    • DbProviderFactories
    • DbDataAdapter, DbCommandBuilder
    • Windows Forms, using data binding for DataGridView controls
    • SQL Server 2005/2008, the Northwind database
  • Typed DataSets, Binding Data
    • Typed DataSets
    • Formatting data in the DataGridView control
    • Manual filling the TreeView control
    • BindingNavigator
    • Windows Forms, using data binding
    • SQL Server 2005/2008, the Northwind database
  • Using Microsoft Access Database, Simple Typed DataSets
    • Typed DataSets
    • Windows Forms, basic data binding
    • Microsoft Access, custom database

LINQ

  • LINQ to Objects
    • Examples of LINQ expressions for List<FileInfo> data structure
    • Also: custom attribute, calling methods using the reflection
  • LINQ to SQL - Generating DataContext
    • Using Visual Studio for generating the DataContext class for the Northwind database
    • SQL Server 2005/2008, the Northwind database
  • LINQ to SQL - Northwind
    • Examples of LINQ expressions for a database
    • SQL Server 2005/2008, the Northwind database
  • LINQ to XML
    • Creating XML from LINQ to SQL
    • Loading data from XML file
    • Modifying XML data
    • Querying XML data
    • Saving XML file
  • LINQ to XML - RSS Reader
    • XDocument, XElement
    • Example of LINQ expression for LINQ to XML classes
    • Windows Forms, custom form for waiting using the BackgroundWorker control, WebBrowser

ASP.NET

XML Web Services

  • XML Web Services
    • Creating simple XML Web Service
    • Consuming the XML Web Service
    • Asynchronous calling of Web methods

Windows Communication Foundation (WCF)

  • Introduction
    • Creating WCF services and their clients
    • Hosting a WCF service and connecting to it from a client
    • Configuration settings for a service and a client
  • Hosting
    • Hosting models: WAS, IIS, Windows service, and managed application
    • Bindings: netNamedPipeBinding, netTcpBinding, basicHttpBinding, and wsHttpBinding
    • Tracing and message logging

Windows Workflow Foundation (WF)

  • Introduction
    • Creating WWF workflows
    • Hosting workflow runtime
    • Invoking workflows from applications with and without parameters
    • Using Code and Delay activities
  • Activities
    • Conditional workflow activities
    • Throwing exceptions from workflow to client application



.NET Framework 2.0, Visual Studio 2005

 
  • Win32 API
    • Using Visual Studio for Win32 applications
    • Handling messages
    • Using mouse and keyboard
    • GDI
  • .NET Framework
    • Console application generated by Visual Studio
    • Decompilation
    • XML Documentation
    • Creating and using an assembly
    • Reflection
    • Global Assembly Cache (GAC)
    • Debugging
  • Windows Forms
    • The simplest application in Windows Forms
    • Using Visual Studio's Designer
    • Using controls
    • Drawing
    • Using threads
    • Custom controls
  • ADO.NET
    • Using Visual Studio's Server Explorer
    • Using a DataSet with MS Access database
    • Creating SQL Server database programmatically
    • Copying data from MS Access to SQL Server programmatically
    • Creating database indenpendent application
  • ASP.NET
    • Web Starter Kit project
    • Simple calculator
      • the postback mechanism
      • ASP.NET controls and events
      • CSS styles
      • themes
    • Master Pages and Site Navigation
    • State management
  • XML Web Services
    • Creating simple XML Web Service
    • Consuming the XML Web Service
    • Asynchronous calling of Web methods
  • COM+
    • Creating a COM+ component
    • Using a COM+ component
    • Using Loosely Coupled Events



.NET Framework 1.x, Visual Studio 2002/2003

 
  • Windows Forms
    • The simplest application in Windows Forms
    • Using Visual Studio's Designer
    • Using controls
    • Drawing
    • Using threads
  • ASP.NET
    • First Web Forms application
    • Simple calculator
    • Tracing
    • User Controls
    • XML Web ServicePreventing SQL Injection in ASP.NET

    Preventing SQL Injection in ASP.NET



    What is SQL Injection?
    To answer this, let's look at a typical piece of code used in millions of web sites which attempts to validate a user who has tried to log in to a protected area of a web site:
      
    protected void Button1_Click(object sender, EventArgs e)
    {
      string connect = "MyConnString";
      string query = "Select Count(*) From Users Where Username = '" + UserName.Text + "' And Password = '" + Password.Text + "'";
      int result = 0;
      using (var conn = new SqlConnection(connect))
      {
        using (var cmd = new SqlCommand(query, conn))
        {
          conn.Open();
          result = (int)cmd.ExecuteScalar();
        }
      }
      if (result > 0)
      {
        Response.Redirect("LoggedIn.aspx");
      }
      else
      {
        Literal1.Text = "Invalid credentials";
    }
      
    
    
    This is a commonly found piece of code that runs as the result of a ButtonClick event. It connects to the database and executes some SQL against a SQL Server database that returns the number of rows where the username and password combination supplied by the user matches a row in the database. If the result is at least one matching row, the user is logged in. At runtime, the values entered by the user are merged dynamically with the SQL string, to create a valid SQL command which is then executed against the database:

    The values supplied above were "Admin" for the user name, and "Let_Me_In" for the password. The image illustrates that the merging of those values with the core SQL has worked rather nicely. You will only get logged in if there is a matching row in the database. Simples. Now look at this:

    This was achieved simply by entering ' or '1' = '1 into both the username textbox and the password textbox. If you study the SQL that has resulted from concatenating those user values with the core SQL, you will probably be able to see that it will always match at least one row. In fact, it will match all rows, so the variable result will be > 0. Sometimes, coders don't return a count. They return user's details so they can use them for allowing further permissions or similar. This SQL will return the first row that matches, which will be the first row in the table generally. Often, this is the admin account that you set up when developing the site, and has all privileges.
    This is SQL Injection. Basically, additional SQL syntax has been injected into the statement to change its behaviour. The single quotes are string delimiters as far as T-SQL is concerned, and if you simply allow users to enter these without managing them, you are asking for potential trouble. Quite often, I see well meaning people advise beginners to "escape" the quotes, using a string.Replace() method such as this:
    var username = UserName.Text.Replace("'", "''");
    var password = Password.Text.Replace("'", "''");
    string query = "Select * From Users Where Username = '" + username + "' And Password = '" + password + "'";
    
    
    
    And indeed that will have the desired effect:

    The first OR clause will never be true. Job done. However, it does not protect against all avenues of attack. Consider the very common scenario where you are querying the database for an article, product or similar by ID. Typically, the ID is stored as a number - most of them are autogenerated by the database. The code will usually look like this:
    string connect = "MyConnString";
    string query = "Select * From Products Where ProductID = " + Request["ID"];
    
    using (var conn = new SqlConnection(connect))
    {
      using (var cmd = new SqlCommand(query, conn))
      {
        conn.Open();
        //Process results
      }
    }
    
    
    Now, in this case, the value for Request["ID"] could come from a posted form, or a querystring value - perhaps from a hyperlink on a previous page. It's easy for a malicious user to amend a querystring value. In the example caught by the VS debugger below, I just put ;Drop Table Admin-- on the end of the querystring before requesting the page:

    The result, again is a legitimate SQL statement that will be run against the database. And the result will be that my Admin table will be deleted. You might be wondering how a hacker will know the names of your tables. Chances are they don't. But think about how you name your database objects. They are bound to be commonsense names that reflect their purpose. It doesn't take long to guess. And of course, if you are using ASP.NET Membership out-of-the-box, the aspnetdb.mdf schema is available to anyone. But before you start changing all your database table names to something really obscure, that is not the answer. Dictionary attacks (where random strings are generated) are common. Finally, it takes just one disgruntled person (a former colleague?) who knows the obscure names you have used to undo all your effort.
    So far, the examples have shown attacks that will only really cause an inconvenience. Someone might break into your Content Management System and start defacing your site, or they might make parts of the database disappear. No big deal - a database restore from a backup will put things right (you DO backup your database, don't you?). Or they might help themselves to some free shipments, or discover secret information that your client would prefer their competitors didn't know. Or it could be a lot worse. Have a look at this document, which describes a certain type of penetration test.
    Penetration tests are tests designed to identify security loopholes in applications, systems and networks. This particular test makes use of the SQL Server xp_cmdshell system stored procedure. xp_cmdshell is extraordinarily powerful, and assuming that the user has the right privileges, effectively gives them total control over the machine that the SQL Server is on, as well as potentially others in the network. Now, imagine being responsible for creating the loophole through which someone was able to create an FTP site on your web server's network, and use it to store material they would not like the police to know about. Or wiped the entire server. Some people think they don't need to worry about this type of thing because their application is intended only to run on a private Intranet. I have however seen servers hosting this type of applciation being affected.
    The Prevention
    OK. I'm sure that by now, you can see that the only sensible thing to do is to prevent any possibility of your application being subject to successful SQL Injection attacks. So now we will turn to preventing them. I have seen plenty of advice like this: http://forums.asp.net/t/1254125.aspx, where the suggestion is to create a Black List if all T-SQL keywords and punctuation, and screen user input for the presence of it. If it exists, throw an error, or similar. It's not a good approach in my view. There are two potential problems with this that I can see. The first is that there may be legitimate reasons why users need to post values included in the blacklist. How many users will become frustrated in their attempt to post a comment that includes "At the end of the day..."? Most T-SQL keywords are also in use in every day language. What if they aren't alowed to submit an @ symbol? Or a semi-colon? The second problem is what happens if Microsoft makes changes to the syntax of T-SQL? Do you go round all the applications you have built over the years and rebuild your black list functions? You might think that the chances of Microsoft making changes are so slim that you shouldn't worry about this. However, until the middle of last year, neither "var" nor "=>" would have done anything in C# except generate a compiler error. You certainly won't get any guarantees from Microsoft against making changes to T-SQL. The real way to prevent SQL Injection attacks is the use of Parameter Queries.
    Parameter Queries
    Parameters in queries are placeholders for values that are supplied to a SQL query at runtime, in very much the same way as parameters act as placeholders for values supplied to a C# method at runtime. And, just as C# parameters ensure type safety, SQL parameters do a similar thing. If you attempt to pass in a value that cannot be implicitly converted to a numeric where the database field expects one, exceptions are thrown. In a previous example where the ProductID value was tampered with to append a SQL command to DROP a table, this will now cause an error rather than get executed because the semicolon and text cannot be converted to a number.
    The SqlCommand class represents a SQL query or stored procedure to be executed against the database. It has a Parameters property which is a collection of SqlParameter objects. For each parameter that appears in the SQL statement, you need to add a Parameter object to the collection. This is probably simpler to explain through code, so taking the ProductID example as a starting point, here's how to rewrite the code:
    protected void Page_Load(object sender, EventArgs e)
    {
      var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
      var query = "Select * From Products Where ProductID = @ProductID";
      using (var conn = new SqlConnection(connect))
      {
        using (var cmd = new SqlCommand(query, conn))
        {
          cmd.Parameters.Add("@ProductID", SqlDbType.Int);
          cmd.Parameters["@ProductID"].Value = Convert.ToInt32(Request["ProductID"]);
          conn.Open();
          //Process results
        }
      }
    }
    
    
    
    The connection string has been defined in the web.config file, and is obtained using the System.Configuration.ConfigurationManager class which provides acces to items in the web.config file. In this case, it retrieves the value of the item in the connectionstrings area with the name "NorthWind". The SQL query is declared with a parameter: @ProductID. All parameters are prefixed with the @ sign. The connection object is declared next, with the connection string passed into the constructor. It's in a using block, which ensures that the connection is closed and disposed of without have to explicitly type code to manage that. The same is true of the SqlCommand object.
    Adding the parameter to the SqlCommand.Parameters collection is relatively straightforward. there are two methods - the Add() method and the AddWithValue() method. The first of these has a number of overloads. I've used the Add(String, SqlDbType) option and then applied the value separately. It could be written all on one line like this:
    cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Convert.ToInt32(Request["ProductID"]);
    
    
    Alternatively, I could use the AddWithValue(string, object) option like this:
    protected void Page_Load(object sender, EventArgs e)
    {
      var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
      var query = "Select * From Products Where ProductID = @ProductID";
      using (var conn = new SqlConnection(connect))
      {
        using (var cmd = new SqlCommand(query, conn))
        {
          cmd.Parameters.AddWithValue("@ProductID", Convert.ToInt32(Request["ProductID"]);
    
          conn.Open();
          //Process results
        }
      }
    }
    
    
    
    The choice is up to you, but most professionals prefer to use one of the Add() methods where the SQL data type (and length, where appropriate) is specified. This reduces the chance of sub-optimal conversion causing performance issues on the server. It also ensures that the value being passed is of the right type in the application, rather than getting SQL Server to have to deal with it and report back errors. Having said all that, most samples on this site use the AddWithValue() option for readability.
    When ADO.NET parameterised queries are sent to SQL Server, they are executed via the system stored procedure sp_executesql:
    exec sp_executesql N'Select * From Products Where ProductID = @ProductID',N'@ProductID int',@ProductID=13
    
    
    This passes in the SQL statement, followed (in this case) by the data type, and finally with the value that the parameter in the SQL statement must use. If the value is a string, any SQL syntax it might contain is treated as part of the literal string, and not as part of the SQL statement, and this is how SQL injection is prevented.
    If a string is provided where a numeric is expected, the application will throw an error. For this reason, you should be validating all input for type and range before even attempting to pass it to a parameter.
    There is one other benefit to be had by using parameters, and that is one of performance. When SQL Server is presented with a SQL statement, it first checks its cache for an identical statement. If it finds one, it retrieves an optimised execution plan which will ensure that the statement is executed as efficiently as possible. If it cannot find an exact match, it goes through the process of creating a plan to cache prior to using that plan to execute the statement. You can see that the first part of the sp_executesql call contains the statement, and that it will always be the same. All subsequent uses of it will use the cached optimised plan. If this statement was dynamically generated using string concatenation, and the ProductID varied each time, an execution plan would need to be created and stored for every value of ProductID. "...WHERE ProductID = 13" is not the same as "...WHERE ProductID = 96".
    Stored Procedures
    It always interests me that whenever the subject of preventing SQL injection comes up in the www.asp.net forums, at least one person contributes the assertion that you must use stored procedures to make use of parameters. As I have demonstrated above, this is not true. However, if you do use stored procedures the code above can be used with just two amendments: you need to pass the name of the stored procedure instead of the SQL statement, and you must set the CommandType to CommandType.StoredProcedure. It's omitted at the moment because the default is CommandType.Text. Here's the revised code for a stored procedure which I shall call GetProductByID:
    var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
    var query = "GetProductByID";
    
    using (var conn = new SqlConnection(connect))
    {
      using (var cmd = new SqlCommand(query, conn))
      {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Convert.ToInt32(Request["ProductID"]);
        conn.Open();
        //Process results
      }
    }
    
    
    
    LINQ to SQL, Entity Framework, OleDb and ODBC
    Both LINQ to SQL and the Entity Framework generate parameterised SQL commands out-of-the-box, providing protection against SQL Injection with no additional effort. This is indeed true of many other Object Relational Mappers (nHibernate etc). If you are using MS Access, SQL injection is not such a problem, as Access is very limited in what it allows. For example, you cannot batch statements so the DROP Table example will not work. Nevertheless, the login hack will work, so you should still use parameters. A much fuller description of how OleDb parameters work with Access is given here: http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access. It should be noted that both OleDb an ODBC parameters work based on position, whereas the examples in this article that use SqlClient all work on matching the name of the parameters, and position is not important.
    How other database systems are affected varies, but it is always best to check their documentation. Nevertheless, using parameterised queries where they are supported by the database system is a sure-fire way to make your application SQL Injection proof. You really have no excuse.


    Parameter Queries in ASP.NET with MS Access

    A selection of code samples for executing queries against MS Access using parameters.

    Making use of the ASP.NET 2.0 datasource controls is fine, but it is important to understand how to manually create data access code. Best practice dictates that, at the very least, parameters are used to represent values that are passed into the SQL to be executed, rather than un-sanitised values straight from the user. The main reason for this cannot be over-emphasised in terms of its importance - it protects the application against SQL Injection attacks. In addition, parameters do not require delimiters. Therefore there is no need to worry about octothorpes (#) or apostrophes for dates, or doubling single quotes in strings.
    These samples all assume that the values being passed into the parameters have been properly validated for datatype, existence, range etc, according to the business rules for the application. The serverside validation code is not included, as it will differ from app to app, and is not the focus of these samples anyway. However, it is important to stress that all user input must be validated server-side before being included in a SQL statement. Better to reject it outright, rather than have to unpick rubbish that pollutes the database...
    The required components are an OleDbConnection object, a ConnectionString property, an OleDbCommand object and an OleDbParameterCollection. These all reside in the System.Data.OleDb namespace, which needs to be referenced. Also, the connection string is held in the Web.Config, and a static method GetConnString() has been created in a class called Utils (also static) to retrieve it:
    [C#]
    public static string GetConnString()
    {
      return WebConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
    }
    [VB]
    Public Shared Function GetConnString() As String
      Return WebConfigurationManager.ConnectionStrings("myConnStr").ConnectionString
    End Function

    For simplicity, you can replace Utils.GetConnString with a valid Access connection string such as:

    "Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|Northwind.mdb"

    To make use of |DataDirectory| make sure that your database file is in the App_Data folder of your web site.
    OleDb Parameters are recognised by their position, not by their name. Consequently, it is vital to ensure that parameters are added to the collection in the order they appear in the SQL, otherwise a "Too few parameters..." exception could occur. At the very least, your values will get inserted into the wrong fields, or nothing happens at all. For the sake of code readability, AddWithValues(string, object) can take a non-empty string giving a name to the parameter, although an empty string ("") will do.
    One final note about parameter markers: in the samples below, the markers are represented by question marks ( ? ). Access (or the Jet provider) is also happy to work with SQL Server-style parameter markers that are prefixed with @, so the first example CommandText can be replaced with:

    "Insert Into Contacts (FirstName, LastName) Values (@FirstName, @LastName)"

    INSERT

    [C#]
    string ConnString = Utils.GetConnString();
    string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
    using (OleDbConnection conn = new OleDbConnection(ConnString))
    {
      using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
      {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
        conn.Open();
        cmd.ExecuteNonQuery();
      }
    }

    [VB]
    Dim ConnString As String = Utils.GetConnString()
    Dim SqlString As String = "Insert Into Contacts (FirstName, LastName) Values (?,?)"
    Using conn As New OleDbConnection(ConnString)
      Using cmd As New OleDbCommand(SqlString, conn)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
        conn.Open()
        cmd.ExecuteNonQuery()
      End Using
    End Using

    UPDATE

    [C#]
    string ConnString = Utils.GetConnString();
    string SqlString = "Update Contacts Set FirstName = ?, LastName = ?";
    using (OleDbConnection conn = new OleDbConnection(ConnString))
    {
      using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
      {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
        conn.Open();
        cmd.ExecuteNonQuery();
      }
    }

    [VB]
    Dim ConnString As String = Utils.GetConnString()
    Dim SqlString As String = "Update Contacts Set FirstName = ?, LastName = ?"
    Using conn As New OleDbConnection(ConnString)
      Using cmd As New OleDbCommand(SqlString, conn)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
        conn.Open()
        cmd.ExecuteNonQuery()
      End Using
    End Using

    DELETE

    [C#]
    string ConnString = Utils.GetConnString();
    string SqlString = "Delete * From Contacts Where FirstName = ? And LastName = ?";
    using (OleDbConnection conn = new OleDbConnection(ConnString))
    {
      using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
      {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
        conn.Open();
        cmd.ExecuteNonQuery();
      }
    }

    [VB]
    Dim ConnString As String = Utils.GetConnString()
    Dim SqlString As String = "Delete * From Contacts Where FirstName = ? And LastName = ?"
    Using conn As New OleDbConnection(ConnString)
      Using cmd As New OleDbCommand(SqlString, conn)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
        conn.Open()
        cmd.ExecuteNonQuery()
      End Using
    End Using

    SELECT

    [C#]
    string ConnString = Utils.GetConnString();
    string SqlString = "Select * From Contacts Where FirstName = ? And LastName = ?";
    using (OleDbConnection conn = new OleDbConnection(ConnString))
    {
      using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
      {
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text);

        conn.Open();
        using (OleDbDataReader reader = cmd.ExecuteReader())
        {
          while (reader.Read())
          {
            Response.Write(reader["FirstName"].ToString() + " " + reader["LastName"].ToString());
          }
        }
      }
    }

    [VB]
    Dim ConnString As String = Utils.GetConnString()
    Dim SqlString As String = "Select * From Contacts Where FirstName = ? And LastName = ?"
    Using conn As New OleDbConnection(ConnString)
      Using cmd As New OleDbCommand(SqlString, conn)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
        conn.Open()
        Using reader As OleDbDataReader = cmd.ExecuteReader()
          While reader.Read()
            Response.Write(reader("FirstName").ToString() + " " + reader("LastName").ToString())
          End While
        End Using
      End Using
    End Using

    Saved Queries

    The code samples above will work equally well with minimal changes for Saved Queries in MS Access. The CommandType will need to be changed to "StoredProcedure", and the name of the query needs to be passed as a string in place of the SQL statement. As an example, if a Saved Query was created in Access called AddContact, this is how the INSERT example would alter:
    [C#]
    string ConnString = Utils.GetConnString();
    string SqlString = "AddContact";
    using (OleDbConnection conn = new OleDbConnection(ConnString))
    {
      using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
      {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
        conn.Open();
        cmd.ExecuteNonQuery();
      }
    }

    [VB]
    Dim ConnString As String = Utils.GetConnString()
    Dim SqlString As String = "AddContact"
    Using Conn As New OleDbConnection(ConnString)
      Using Cmd As New OleDbCommand(SqlString, Conn)
        Cmd.CommandType = CommandType.StoredProcedure
        Cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
        Cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
        Conn.Open()
        Cmd.ExecuteNonQuery()
      End Using
    End Using
    You may end up using a legacy Access database, which has embedded spaces in the names of the queries. I know - only an idiot does this sort of thing. Well, the download version of Northwind.mdb (from Microsoft) has embedded spaces in object names... Anyway, the way to get round this is to surround the query name with [ ] brackets:

    string query = "[Current Product List]";




    Object Oriented Programming Concepts with C#3.0

    Some of the topics-concepts, I will try to cover are:
  • Classes
  • Properties
  • Methods
  • Fields
  • Members
  • Enums
  • Casting
  • Structures
  • Abstraction
  • Encapsulation
  • Interfaces
  • Static classes
  • Constructors
  • Method overloading
  • Inheritance
  • Overriding methods
  • Virtual methods
  • Abstract classes
  • Polymorphism
  • Delegates
  • Events
  • Assemblies
  • Namespaces
and many more…
Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding  OOP.
  • What is a class?
A class is an abstract concept. It is a blueprint. Try to think of a class as e.g  the blueprints of a car in the real world.
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.
  • What is a property ?
A Property allows you to access an object’s data. Properties can be read-only, so they cannot be modified, while others can be changed. A Property defines the state of an object.It describes its individual data or unique configuration.
  • What is a method ?
A method allows you to perform an action with an object. Unlike properties, methods are used for actions that perform a distinct task and may  change the object’s state-property.
  • What is an event ?
An event provides notification that something has happened. Objects can fire events to trigger the code we have placed in the event-handling routines-methods. For example, if a user clicks on a button,the button object fires a Click event, which our code can react to.
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;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{
Then add the class definition
public class Person
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;
}
Now 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)
{
Person mynewperson;
mynewperson=new Person();
mynewperson.name = “nikos”;
mynewperson.surname = “kantzelis”;
mynewperson.age = 31;
mynewperson.weight = 88;
mynewperson.height = 1.78M;
Response.Write(mynewperson.name);
}
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;
mynewperson=new Person();

One could write it in a single line

Person mynewperson=new Person();

But the snippet of code inside the Page_Load method is not very well thought.
One could write mynewperson.age = -2;
We would not like to have the code above. The reason the code above works is that the properties of the Person class,
are all public. That is the visibility of the properties is public. Another more technical word for visibility is scope.
This is very important concept and one must understand.
The main accessibility keywords are
public -Members defined as public can be accessed by any other class
private - Members defined as private can be accessed only by code procedures inside the current class
internal – Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)
protected Members defined as protected can be accessed by code procedures in the current class or by any class
that inherits from this class
So by having in our example the variables defined as public, this means that any other class or method of another class has direct access to those variables-properties.
We must not design classes like that. In order to have useful classes we must have a way to protect the data within them. This is called, Encapsulation. Encapsulation is is the hiding of the internal mechanisms and data of a class behind a defined interface.Other classes , if they need to “talk” – interact with a specific class, they can do so by just knowing its interface. Let me try to explain this better with my car analogy example. When you try to change the gear in your car, imagine the gear system as class or a component, the gear system interacts with another system that commands the car to slow down or accelerate. The gear system does not have to know how it is done, just how to interacts with it.
So let’s change public to private.
private string name;
private string surname;
private int age;
private decimal height;
private decimal weight;
Let’s run the code again. We get the following error. I am sure you get what is going on here. There is no variable name still “alive-visible” when we call it in the Page_Load event handling routine.

Error    1    ’LearnCLass._Default.Person.name’ is inaccessible due to its protection level    C:\Users\fofo\Desktop\webapps\LearnCLass\LearnCLass\Default.aspx.cs    24    25    LearnCLass

In general objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. That means that their memory is reclaimed. In the managed applications, the CLR uses a service (garbage collector) that periodically scans for released objects and reclaims the memory they hold.
So , you must be thinking that we have not accomplished anything yet. The truth is that we have not finished yet.
We must write property accessors for the member variables.
For the name member variable we have
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
With C# 3.0 we had a new feature that is called Auto-implemented properties. Have a look here in one of my past posts to find out more about that.Basically with auto implemented properties,  there is no need to implement a private field to store the value.
So we could write the code above like this

public string Name { get; set; }

much easier isn’t it?
We can do that for all property accessors if no no additional logic is required.
So we have

public string Name { get; set; }
public string Surname { get; set; }

that means that we can comment out the following lines from our class declaration.
//private string name;
//private string surname;

but for the Age,Height,Weight member variables we require some additional logic for the property accessors.
Just for this example let’s just assume that a person’s age must between 1 and 100, his height from 1 to 2.40 and his weight from 30 to 240.
public int Age
{
get
{
return age;
}
set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}
age = value;
}
}
public decimal Height
{
get
{
return height;
}
set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}
height = value;
}
}
public decimal Weight
{
get
{
return weight;
}
set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}
weight = value;
}
}
When trying to assign an invalidvalue, an exception is thrown by the class code.
Now let’s create a method for our Person Class.
We can create a very simple method like:

public void Talk()

{
// add logic later
}
or we can add a method that returns something (it is not void) and can do something useful.
So we can have a method that calculates the age of the person in years. The method follows:
public int CalculateAge(DateTime birthDate)
{DateTime now = DateTime.Today;int years = now.Year – birthDate.Year;if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;return years;
}
It is not something difficult.  We should not focus on how the method does it, right now. Basically I am just using
DateTime Class in the System namespace.
In your Page_Load event you can add to the code already there, the following bit
string myDateTimeString;int res;myDateTimeString = “17 Feb,1977″;DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());
Run your application and see the results.
The Person class so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{
public class Person
{
//private string name;
//private string surname;
private int age;
private decimal height;
private decimal weight;
public int Age
{
get
{
return age;
}
set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}
age = value;
}
}
public decimal Height
{
get
{
return height;
}
set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}
height = value;
}
}
public decimal Weight
{
get
{
return weight;
}
set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}
weight = value;
}
}
public string Name { get; set; }
public string Surname { get; set; }
public int CalculateAge(DateTime birthDate)
{
DateTime now = DateTime.Today;
int years = now.Year – birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;
return years;
}
public void Talk()
{
//add logic later
}
}
protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson=new Person();
mynewperson.Name = “nikos”;
mynewperson.Surname = “kantzelis”;
mynewperson.Age = 22;
mynewperson.Weight = 88;
mynewperson.Height = 1.78M;
Response.Write(mynewperson.Name);
Response.Write(“</br>”);
Response.Write(mynewperson.Surname);
Response.Write(“</br>”);
Response.Write(mynewperson.Age);
Response.Write(“</br>”);
Response.Write(mynewperson.Height);
Response.Write(“</br>”);
Response.Write(mynewperson.Weight);
Response.Write(“</br>”);
mynewperson.Talk();
string myDateTimeString;
int res;
myDateTimeString = “17 Feb,1977″;
DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);
Response.Write(res.ToString());
mynewperson.Talk();
}
}
}
When we create our Person object,

Person mynewperson=new Person();

you might think that we have here is a method call.When an instance of a class is created the C# system makes a call to a constructor method in that class. A constructor is a function with the same name as that of the class. Every single class must have a constructor method.It is called when we write the new keyword. Even If we do not provide a constructor method, the compiler creates a default one,without any parameters.
So in our case is:
public Person()
{
}
We often need to overload our default constructors. Let me explain what overload is.
It is possible to have more than one method with the same name and return type but with a different number and type of arguments-parameters. The compiler knows every time which method to call by looking at the number of the arguments. I will explain more about overloading later on.
Sometimes it is better to send some information to the class upfront so it is available as soon as it is constructed. So let’s overload the default constructor.
public Person( string thename, string thesurname, int theage)
{
Name = thename;
Surname=thesurname;
Age = theage;
}
We can also have a destructor.Destructors are just the opposite of constructors.
It has the same name as the containing class but prefixes it with the ~ (tilde) sign.
It is called automatically when the object is about to be destructed (when garbage collector is about to destroy your object).
It has no return type just as the constructor does not have one as well.
We declare the destructor in our case like
~Person()
{
// place our e.g resource freeing code here
}
What really happens is that the C# compiler internally converts the destructor to the Finalize() method.
The Object class is the parent of all objects in .Net.It contains a method called Finalize().
This method is  be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.
protected override void Finalize()
{
try
{
// put some code here
}
finally
{
base.Finalize();
}
}
Do not worry about the override keyword. I will explain it later on.
Many people ask me about enums and structures and what they are and how we can use them.
What is enum?
An enumeration is a group of related constants. Each constant is given a descriptive name.
Every enumerated value corresponds to a preset integer.
Sometimes we want to hold a range of particular values or states. This is a perfect place to use enums.
In our example we could have something like
public enum PersonState
{
Married = 1,
Widoewed = 2,
Single = 3,
Divorced = 4
}
And then call it from our Page_load event
PersonState personstate;
personstate =PersonState.Married;
Response.Write(“</br>”);
Response.Write(personstate);
C# compiler will  represent these states as particular numeric values . But it will do so behind the curtains.
So I can use the enum name values and have more readable code. The concept of enumerated values is extremely important, because the .NET class library uses it extensively.
What is a structure ?
Structures are lightweight objects. Structures are very similar to classes in C#.
Basically they can hold a collection of different things about a particular item.
They are denoted in C# by the struct keyword. In our example we could have a structure like this
struct NewPerson
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;
}
In the Page_Load event routine we can have
NewPerson myperson;
myperson.name = “John”;
Response.Write(myperson.name);
As you notice there is no need for the new keyword.
There is a key difference between objects and structures. Structures are managed in terms of value while objects are managed in terms of reference.
A reference holds the physical address of where the data is stored in memory. So it points to the data. It is not the actual data. On the other hand structure variables hold the actual data.
There are some limitations with structures and even if they have their place when we design a software component, they can never be used to replace a class type.
A structure  for example can neither inherit another class, nor can they be inherited. A structure can implement interfaces.
A common place where we find structures  are Net framework types like System.Int32, System.Double , System.Boolean.If you want to check it out yourselves just place the pointer of your mouse on an int declaration and right click. From the right-menu click on the “Go To Definition “. Then you will see the definitions. See the picture below.

go to def
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();
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());
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.
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.
Now, we know how to make a new class based on an existing one and extend it.If we want to change the behavior of a method in the base class in the child class we must override it.
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)
{
return (hoursWorked * wageperhour * 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.
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)
{
return (hoursWorked * wageperhour * tax);
}
and then to use the word override in Student class CalculatePay method
public override double CalculatePay(double hoursWorked, double wageperhour,double tax)
{
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 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 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)
{
return name + ” ” + surname;
}
Now we could have a different implementation of the method above.
public string JoinNames(string prefix, string name, string surname)
{
return prefix + ” ” + name + ” ” + surname;
}
In our Page_ Load event if we write the line:

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)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}
}
The method above is a good candidate to become a static method.In order to do that, we just add the word static
public static bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}
}
In our Page_Load event routine,we can write
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 IPerson
{
double DaysVacation(int yearsOfWork);
}
and if we say that the Person class implements the IPerson Interface

class Person : IPerson

the Person class must in its body implement the DaysVacation(int yearsOfWork) method.
public double DaysVacation(int yearsOfWork)
{
if (yearsOfWork > 25)
{
return 25;
}
else if (yearsOfWork < 25 && yearsOfWork > 20)
{
return 20;
}
else
{
return 10;
}
}
What is an abstact class?
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 Vehicle
{
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;
}
}
Now 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 class Car : Vehicle
{
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;
}
}
We can create and use an object type Car in our Page_Load event handling routine
Car mycar = new Car( “bmw”, “silver”);
Response.Write(mycar.Accelarate(134));
Response.Write(“</br>”);
Response.Write(“The cost is: ” + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +” euros”);
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.
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:

int mynum=5;

float anothernum=mynum;

This will be fine because the floating point type can hold all the values supported by the integer type.
If I have this statement (narrowing)

double mynum = 3.5;
float thenum = mynum;

the compiler will complain.
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.

double mynum = 3.5;
float thenum = (float)mynum;

This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.
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.

Student thestudent = new Student();

while if we type this:

Person theperson=new Person();

this will fail and we must explicitly cast it to the Student type, like this.

Person theperson=new Person();
Student thestudent = (Student)theperson;

Hope it helps. If you need the source code, leave a comment and I will email it to you.

Object-Oriented Programming Concepts and .NET

http://www.dotnettreats.com/tipstricks/oopconcepts1.aspx

Part 1: Classes, Objects, and Structures in .NET

Erika Ehrli Cabral
February 2005

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;
        
}

    }
}
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
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;
        
}
    }
}
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 As IntegerByVal As Integer)
        
MyBase.New
        Me
._x x
        
Me._y y
    
End Sub

    Public Property 
As Integer
        Get
            Return 
_x
        
End Get
        Set
            
_x value
        
End Set
    End Property

    Public Property 
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

Erika Ehrli Cabral
March 2005

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

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();

    
}
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);
        
}
    }
}
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 - Part 3 : Compare Validator

Compare Validator 
  
In this article, I’m going to explain about the compare validator. The compare validator is used to compare the values entered in a one input control with another constant value or value entered against in another control.


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.

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:
In a web form (don’t confuse what is a web form!!!) I’m going to add the 2 dropdown namely:
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.
Create A Project in Visual Studio:
Before that I will explain step by step how to add a project ASP.Net in Visual Studio 2010.
Step 1:
Open Visual Studio 2010. The Visual studio startup screen look like this.
VisualStudio-Startup-Screen
Step 2:
Click on “New Project”, which opens the following screen. Please take a close look in the highlighted areas.
VisualStudio-CreateNewProject
I have choosen, Visual Basic as a languge, “ASP.Net Web Application” as Project Template and "Target Framework version as 3.5.
VB-ASPDotNet-Application
Step 3:
After clicking on the “OK” button in the above screen. Solution file named as  “AllInOne” will be loaded in Visual Studio.
ASPDotNet-Application
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).
Solution-Explorer

ShowAllFiles-SolutionExplorer
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 comment: