Thursday, March 6, 2014

Populate an ASP.NET ListBox from JSON results using jQuery

how to populate an ASP.NET ListBox using data coming from a JSON Serialized ASP.NET Web Service. Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. Let us quickly jump to the solution and see how to populate an ASP.NET ListBox from data coming from a JSON Serialized ASP.NET Web Service Populate a ListBox from JSON Results

Click on a Radio Button to retrieve 'Gender' based data




In this example, we will see how to consume an ASP.NET Web Service (EmployeeList.asmx) that is JSON Serialized. The data source for this web service is List in the Employee.cs class.

Wednesday, April 4, 2012

DML Operations in gridView with xml file


xml file】




Corets, Eva
The Sundered Grail
Fantasy
5.95
2001-09-10

The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.



Thurman, Paula
Splish Splash
Romance
4.95
2000-11-02

A deep sea diver finds true love twenty
thousand leagues beneath the sea.



Knorr, Stefan
Creepy Crawlies
Horror
4.95
2000-12-06

An anthology of horror stories about roaches,
centipedes, scorpions and other insects.



Kress, Peter
Paradox Lost
Science Fiction
6.95
2000-11-02

After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.



O'Brien, Tim
Microsoft .NET: The Programming Bible
Computer
36.95
2000-12-09

Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.



O'Brien, Tim
MSXML3: A Comprehensive Guide
Computer
36.95
2000-12-01

The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.



Galos, Mike
Visual Studio 7: A Comprehensive Guide
Computer
49.95
2001-04-16

Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.






[.cs file]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace XmlEditInsertDeleteInGridView
{
public partial class Default : System.Web.UI.Page
{
///
/// For the first time when the page loads, load data into DataTable
/// with DataSet, and save the DataTable into ViewState for further
/// usage.
///

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
ds.ReadXml(Request.MapPath("try.xml"));
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
ViewState["dt"] = ds.Tables[0];
}
}

///
/// Handle the Edit event of GridView for assigning the specific row to be
/// in the edit mode.
///

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
}

///
/// Update the specific row in the DataTable with the data from GridView,
/// re-write the data into the xml file and re-databind again.
///

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];

for (int i = 1; i < GridView1.Rows[e.RowIndex].Cells.Count; i++)
{
dt.Rows[e.RowIndex][i-1] = (GridView1.Rows[e.RowIndex].Cells[i].Controls[0] as TextBox).Text;
}
dt.AcceptChanges();
GridView1.EditIndex = -1;
GridView1.DataSource = dt;
GridView1.DataBind();
dt.WriteXml(Request.MapPath("try.xml"));
}

///
/// Cancel edit and set the mode of the GridView to normal viewing mode.
///

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
DataTable dt = (DataTable)ViewState["dt"];
GridView1.DataSource = dt;
GridView1.DataBind();
}

///
/// Insert the data into the DataTable, re-write into the xml file and
/// re-databind to the GridView.
///

protected void btnInsert_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
dt.Rows.Add(tbAuthor.Text, tbTitle.Text, tbGenre.Text, tbPrice.Text, tbPublishDate.Text, tbDescription.Text, tbId.Text);
dt.AcceptChanges();
dt.WriteXml(Request.MapPath("try.xml"));
GridView1.DataSource = dt;
GridView1.DataBind();
}

///
/// Delete the row from DataTable and write data into xml file,
/// re-databind to the GridView.
///

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
dt.Rows.RemoveAt(e.RowIndex);
dt.WriteXml(Request.MapPath("try.xml"));
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}

【aspx file】

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="XmlEditInsertDeleteInGridView.Default" %>




Xml-based CRUD Code Sample







Xml-based CRUD Code Sample——


AutoGenerateEditButton="True" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting">












Id:



author:



title:



genre:



price:



publishdate:



description:


Text="Insert" Width="141px" />


Wednesday, February 22, 2012

Page Life Cycle in ASP.NET

An important article on the different methods and order they are executed during the load of an .aspx web page. ASP.NET.

In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.

When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.

The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!

The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page's life cycle in the order listed below.
Methods Description
Page_Init Page Initialization
LoadViewState View State Loading
LoadPostData Postback Data Processing
Page_Load Page Loading
RaisePostDataChangedEvent PostBack Change Notification
RaisePostBackEvent PostBack Event Handling
Page_PreRender Page Pre Rendering Phase
SaveViewState View State Saving
Page_Render Page Rendering
Page_Unload Page Unloading


The first processed method is Page_Init(). Once the control tree has been created, the controls declared in the .aspx file are initialized. The controls can modify some of the settings set in this method to be used later in the page life cycle. Obviously no other information is available to be modified at this time.

The next processed method is LoadViewState(). The Viewstate contains stored information that is set by the page and controls of the page. This is carried to and from every aspx page request per visitor.

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

The next processed method is LoadPostData(). These are values associated with the HTML form elements the visitor has typed, changed or selected. Now the control has access to this information which can update their stored information pulled from the Viewstate.

The next processed method is Page_Load(). This method should look familiar and is usually the most common used method on the server side application code for an .aspx file. All code inside of this method is executed once at the beginning of the page.

The next processed method is RaisePostDataChangedEvent(). When a visitor completes a form and presses the submit button, an event is triggered. This change in state signals the page to do something.

The next processed method is RaisePostBackEvent(). This method allows the page to know what event has been triggered and which method to call. If the visitor clicks Button1, then Button1_Click is usually called to perform its function.

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!

The next processed method is Page_PreRender(). This method is the last chance for the Viewstate to be changed based on the PostBackEvent before the page is rendered.

The next processed method is SaveViewState(). This method saves the updated Viewstate to be processed on the next page. The final Viewstate is encoded to the _viewstate hidden field on the page during the page render.

The next processed method is Page_Render(). This method renders all of the application code to be outputted on the page. This action is done with the HtmlWriter object. Each control uses the render method and caches the HTML prior to outputting.

The last processed method is Page_Unload(). During this method, data can be released to free up resources on the server for other processes. Once this method is completed, the HTML is sent to the browser for client side processing.

Now you should have a little bit better understanding of the order of methods executed in the request of an .aspx file.

Tuesday, December 20, 2011

User-Based Authorization (C#)

In this tutorial we will look at limiting access to pages and restricting page-level functionality through a variety of techniques.

Introduction

ost web applications that offer user accounts do so in part to restrict certain visitors from accessing certain pages within the site. In most online messageboard sites, for example, all users - anonymous and authenticated - are able to view the messageboard's posts, but only authenticated users can visit the web page to create a new post. And there may be administrative pages that are only accessible to a particular user (or a particular set of users). Moreover, page-level functionality can differ on a user-by-user basis. When viewing a list of posts, authenticated users are shown an interface for rating each post, whereas this interface is not available to anonymous visitors.

ASP.NET makes it easy to define user-based authorization rules. With just a bit of markup in Web.config, specific web pages or entire directories can be locked down so that they are only accessible to a specified subset of users. Page-level functionality can be turned on or off based on the currently logged in user through programmatic and declarative means.

In this tutorial we will look at limiting access to pages and restricting page-level functionality through a variety of techniques. Let's get started!
A Look at the URL Authorization Workflow

As discussed in the An Overview of Forms Authentication tutorial, when the ASP.NET runtime processes a request for an ASP.NET resource the request raises a number of events during its lifecycle. HTTP Modules are managed classes whose code is executed in response to a particular event in the request lifecycle. ASP.NET ships with a number of HTTP Modules that perform essential tasks behind the scenes.

One such HTTP Module is FormsAuthenticationModule. As discussed in previous tutorials, the primary function of the FormsAuthenticationModule is to determine the identity of the current request. This is accomplished by inspecting the forms authentication ticket, which is either located in a cookie or embedded within the URL. This identification takes place during the AuthenticateRequest event.

Another important HTTP Module is the UrlAuthorizationModule, which is raised in response to the AuthorizeRequest event (which happens after the AuthenticateRequest event). The UrlAuthorizationModule examines configuration markup in Web.config to determine whether the current identity has authority to visit the specified page. This process is referred to as URL authorization.

We'll examine the syntax for the URL authorization rules in Step 1, but first let's look at what the UrlAuthorizationModule does depending on whether the request is authorized or not. If the UrlAuthorizationModule determines that the request is authorized, then it does nothing, and the request continues through its lifecycle. However, if the request is not authorized, then the UrlAuthorizationModule aborts the lifecycle and instructs the Response object to return an HTTP 401 Unauthorized status. When using forms authentication this HTTP 401 status is never returned to the client because if the FormsAuthenticationModule detects an HTTP 401 status is modifies it to an HTTP 302 Redirect to the login page.

Figure 1 illustrates the workflow of the ASP.NET pipeline, the FormsAuthenticationModule, and the UrlAuthorizationModule when an unauthorized request arrives. In particular, Figure 1 shows a request by an anonymous visitor for ProtectedPage.aspx, which is a page that denies access to anonymous users. Since the visitor is anonymous, the UrlAuthorizationModule aborts the request and returns an HTTP 401 Unauthorized status. The FormsAuthenticationModule then converts the 401 status into a 302 Redirect to login page. After the user is authenticated via the login page, he is redirected to ProtectedPage.aspx. This time the FormsAuthenticationModule identifies the user based on his authentication ticket. Now that the visitor is authenticated, the UrlAuthorizationModule permits access to the page.
The Forms Authentication and URL Authorization Workflow





Figure 1: The Forms Authentication and URL Authorization Workflow (Click to view full-size image)

Figure 1 depicts the interaction that occurs when an anonymous visitor attempts to access a resource that is not available to anonymous users. In such a case, the anonymous visitor is redirected to the login page with the page she attempted to visit specified in the querystring. Once the user has successfully logged on, she will be automatically redirected back to the resource she was initially attempting to view.

When the unauthorized request is made by an anonymous user, this workflow is straightforward and is easy for the visitor to understand what has happened and why. But keep in mind that the FormsAuthenticationModule will redirect any unauthorized user to the login page, even if the request is made by an authenticated user. This can result in a confusing user experience if an authenticated user attempts to visit a page for which she lacks authority.

Imagine that our website had its URL authorization rules configured such that the ASP.NET page OnlyTito.aspx was accessibly only to Tito. Now, imagine that Sam visits the site, logs on, and then attempts to visit OnlyTito.aspx. The UrlAuthorizationModule will halt the request lifecycle and return an HTTP 401 Unauthorized status, which the FormsAuthenticationModule will detect and then redirect Sam to the login page. Since Sam has already logged in, though, she may wonder why she has been sent back to the login page. She might reason that her login credentials were lost somehow, or that she entered invalid credentials. If Sam reenters her credentials from the login page she will be logged on (again) and redirected to OnlyTito.aspx. The UrlAuthorizationModule will detect that Sam cannot visit this page and she will be returned to the login page.

Figure 2 depicts this confusing workflow.
The Default Workflow Can Lead to a Confusing Cycle

Figure 2: The Default Workflow Can Lead to a Confusing Cycle (Click to view full-size image)

The workflow illustrated in Figure 2 can quickly befuddle even the most computer savvy visitor. We will look at ways to prevent this confusing cycle in Step 2.

Note: ASP.NET uses two mechanisms to determine whether the current user can access a particular web page: URL authorization and file authorization. File authorization is implemented by the FileAuthorizationModule, which determines authority by consulting the requested file(s) ACLs. File authorization is most commonly used with Windows authentication because ACLs are permissions that apply to Windows accounts. When using forms authentication, all operating system- and file system-level requests are executed by the same Windows account, regardless of the user visiting the site. Since this tutorial series focuses on forms authentication, we will not be discussing file authorization.
The Scope of URL Authorization

The UrlAuthorizationModule is managed code that is part of the ASP.NET runtime. Prior to version 7 of Microsoft's Internet Information Services (IIS) web server, there was a distinct barrier between IIS's HTTP pipeline and the ASP.NET runtime's pipeline. In short, in IIS 6 and earlier, ASP.NET's UrlAuthorizationModule only executes when a request is delegated from IIS to the ASP.NET runtime. By default, IIS processes static content itself - like HTML pages and CSS, JavaScript, and image files - and only hands off requests to the ASP.NET runtime when a page with an extension of .aspx, .asmx, or .ashx is requested.

IIS 7, however, allows for integrated IIS and ASP.NET pipelines. With a few configuration settings you can setup IIS 7 to invoke the UrlAuthorizationModule for all requests, meaning that URL authorization rules can be defined for files of any type. Additionally, IIS 7 includes its own URL authorization engine. For more information on ASP.NET integration and IIS 7's native URL authorization functionality, see Understanding IIS7 URL Authorization. For a more in-depth look at ASP.NET and IIS 7 integration, pick up a copy of Shahram Khosravi's book, Professional IIS 7 and ASP.NET Integrated Programming (ISBN: 978-0470152539).

In a nutshell, in versions prior to IIS 7, URL authorization rules are only applied to resources handled by the ASP.NET runtime. But with IIS 7 it is possible to use IIS's native URL authorization feature or to integrate ASP.NET's UrlAuthorizationModule into IIS's HTTP pipeline, thereby extending this functionality to all requests.

Note: There are some subtle yet important differences in how ASP.NET's UrlAuthorizationModule and IIS 7's URL authorization feature process the authorization rules. This tutorial does not examine IIS 7's URL authorization functionality or the differences in how it parses authorization rules compared to the UrlAuthorizationModule. For more information on these topics, refer to the IIS 7 documentation on MSDN or at www.iis.net.
Step 1: Defining URL Authorization Rules in Web.config

The UrlAuthorizationModule determines whether to grant or deny access to a requested resource for a particular identity based on the URL authorization rules defined in the application's configuration. The authorization rules are spelled out in the element in the form of and child elements. Each and child element can specify:

A particular user
A comma-delimited list of users
All anonymous users, denoted by a question mark (?)
All users, denoted by an asterisk (*)

The following markup illustrates how to use the URL authorization rules to allow users Tito and Scott and deny all others:







The element defines what users are permitted - Tito and Scott - while the element instructs that all users are denied.

Note: The and elements can also specify authorization rules for roles. We will examine role-based authorization in a future tutorial.

The following setting grants access to anyone other than Sam (including anonymous visitors):






To allow only authenticated users, use the following configuration, which denies access to all anonymous users:






The authorization rules are defined within the element in Web.config and apply to all of the ASP.NET resources in the web application. Oftentimes, an application has different authorization rules for different sections. For example, at an eCommerce site, all visitors may peruse the products, see product reviews, search the catalog, and so on. However, only authenticated users may reach the checkout or the pages to manage one's shipping history. Moreover, there may be portions of the site that are only accessible by select users, such as site administrators.

ASP.NET makes it easy to define different authorization rules for different files and folders in the site. The authorization rules specified in the root folder's Web.config file apply to all ASP.NET resources in the site. However, these default authorization settings can be overridden for a particular folder by adding a Web.config with an section.

Let's update our website so that only authenticated users can visit the ASP.NET pages in the Membership folder. To accomplish this we need to add a Web.config file to the Membership folder and set its authorization settings to deny anonymous users. Right-click the Membership folder in the Solution Explorer, choose the Add New Item menu from the context menu, and add a new Web Configuration File named Web.config.
Add a Web.config File to the Membership Folder

Figure 3: Add a Web.config File to the Membership Folder (Click to view full-size image)

At this point your project should contain two Web.config files: one in the root directory and one in the Membership folder.
Your Application Should Now Contain Two Web.config Files

Figure 4: Your Application Should Now Contain Two Web.config Files (Click to view full-size image)

Update the configuration file in the Membership folder so that it prohibits access to anonymous users.











That's all there is to it!

To test out this change, visit the homepage in a browser and make sure you are logged out. Since the default behavior of an ASP.NET application is to allow all visitors, and since we didn't make any authorization modifications to the root directory's Web.config file, we are able to visit the files in the root directory as an anonymous visitor.

Click on the Creating User Accounts link found in the left column. This will take you to the ~/Membership/CreatingUserAccounts.aspx. Since the Web.config file in the Membership folder defines authorization rules to prohibit anonymous access, the UrlAuthorizationModule aborts the request and returns an HTTP 401 Unauthorized status. The FormsAuthenticationModule modifies this to a 302 Redirect status, sending us to the login page. Note that the page we were attempting to access (CreatingUserAccounts.aspx) is passed to the login page via the ReturnUrl querystring parameter.
Since the URL Authorization Rules Prohibit Anonymous Access, We are Redirected to the Login Page

Figure 5: Since the URL Authorization Rules Prohibit Anonymous Access, We are Redirected to the Login Page (Click to view full-size image)

Upon successfully logging in, we are redirected to the CreatingUserAccounts.aspx page. This time the UrlAuthorizationModule permits access to the page because we are no longer anonymous.
Applying URL Authorization Rules to a Specific Location

The authorization settings defined in the section of Web.config apply to all of the ASP.NET resources in that directory and its subdirectories (until otherwise overridden by another Web.config file). In some cases, though, we may want all ASP.NET resources in a given directory to have a particular authorization configuration except for one or two specific pages. This can be achieved by adding a element in Web.config, pointing it to the file whose authorization rules differ, and defining its unique authorization rules therein.

To illustrate using the element to override the configuration settings for a specific resource, let's customize the authorization settings so that only Tito can visit CreatingUserAccounts.aspx. To accomplish this, add a element to the Membership folder's Web.config file and update its markup so that it looks like the following:




















The element in defines the default URL authorization rules for ASP.NET resources in the Membership folder and its subfolders. The element allows us to override these rules for a particular resource. In the above markup the element references the CreatingUserAccounts.aspx page and specifies its authorization rules such as to allow Tito, but deny everyone else.

To test out this authorization change, start by visiting the website as an anonymous user. If you attempt to visit any page in the Membership folder, such as UserBasedAuthorization.aspx, the UrlAuthorizationModule will deny the request and you will be redirected to the login page. After logging in as, say, Scott, you can visit any page in the Membership folder except for CreatingUserAccounts.aspx. Attempting to visit CreatingUserAccounts.aspx logged on as anyone but Tito will result in an unauthorized access attempt, redirecting you back to the login page.

Note: The element must appear outside of the configuration's element. You need to use a separate element for each resource whose authorization settings you want to override.
A Look at How the UrlAuthorizationModule Uses the Authorization Rules to Grant or Deny Access

The UrlAuthorizationModule determines whether to authorize a particular identity for a particular URL by analyzing the URL authorization rules one at a time, starting from the first one and working its way down. As soon as a match is found, the user is granted or denied access, depending on if the match was found in an or element. If no match is found, the user is granted access. Consequently, if you want to restrict access, it is imperative that you use a element as the last element in the URL authorization configuration. If you omit a element, all users will be granted access.

To better understand the process used by the UrlAuthorizationModule to determine authority, consider the example URL authorization rules we looked at earlier in this step. The first rule is an element that allows access to Tito and Scott. The second rules is a element that denies access to everyone. If an anonymous user visits, the UrlAuthorizationModule starts by asking, Is anonymous either Scott or Tito? The answer, obviously, is No, so it proceeds to the second rule. Is anonymous in the set of everybody? Since the answer here is Yes, the rule is put in effect and the visitor is redirected to the login page. Similarly, if Jisun is visiting, the UrlAuthorizationModule starts by asking, Is Jisun either Scott or Tito? Since she is not, the UrlAuthorizationModule proceeds to the second question, Is Jisun in the set of everybody? She is, so she, too, is denied access. Finally, if Tito visits, the first question posed by the UrlAuthorizationModule is an affirmative answer, so Tito is granted access.

Since the UrlAuthorizationModule processes the authorization rules from the top down, stopping at any match, it is important to have the more specific rules come before the less specific ones. That is, to define authorization rules that forbid Jisun and anonymous users, but allow all other authenticated users, you would start with the most specific rule - the one impacting Jisun - and then proceed to the less specific rules - those allowing all other authenticated users, but denying all anonymous users. The following URL authorization rules implements this policy by first denying Jisun, and then denying any anonymous user. Any authenticated user other than Jisun will be granted access because neither of these statements will match.






Step 2: Fixing the Workflow for Unauthorized, Authenticated Users

As we discussed earlier in this tutorial in the A Look at the URL Authorization Workflow section, anytime an unauthorized request transpires, the UrlAuthorizationModule aborts the request and returns an HTTP 401 Unauthorized status. This 401 status is modified by the FormsAuthenticationModule into a 302 Redirect status that sends the user to the login page. This workflow occurs on any unauthorized request, even if the user is authenticated.

Returning an authenticated user to the login page is likely to confuse them since they have already logged into the system. With a little bit of work we can improve this workflow by redirecting authenticated users who make unauthorized requests to a page that explains that they have attempted to access a restricted page.

Start by creating a new ASP.NET page in the web application's root folder named UnauthorizedAccess.aspx; don't forget to associate this page with the Site.master master page. After creating this page, remove the Content control that references the LoginContent ContentPlaceHolder so that the master page's default content will be displayed. Next, add a message that explains the situation, namely that the user attempted to access a protected resource. After adding such a message, the UnauthorizedAccess.aspx page's declarative markup should look similar to the following:


<%@ Page Language="C#" MasterPageFile="/Site.master" AutoEventWireup="true"
CodeFile="UnauthorizedAccess.aspx.cs" Inherits="UnauthorizedAccess"
Title="Untitled Page" %>

Runat="Server">

Unauthorized Access



You have attempted to access a page that you are not authorized to view.



If you have any questions, please contact the site administrator.




We now need to alter the workflow so that if an unauthorized request is performed by an authenticated user they are sent to the UnauthorizedAccess.aspx page instead of the login page. The logic that redirects unauthorized requests to the login page is buried within a private method of the FormsAuthenticationModule class, so we cannot customize this behavior. What we can do, however, is add our own logic to the login page that redirects the user to UnauthorizedAccess.aspx, if needed.

When the FormsAuthenticationModule redirects an unauthorized visitor to the login page it appends the requested, unauthorized URL to the querystring with the name ReturnUrl. For example, if an unauthorized user attempted to visit OnlyTito.aspx, the FormsAuthenticationModule would redirect them to Login.aspx?ReturnUrl=OnlyTito.aspx. Therefore, if the login page is reached by an authenticated user with a querystring that includes the ReturnUrl parameter, then we know that this unauthenticated user just attempted to visit a page she is not authorized to view. In such a case, we want to redirect her to UnauthorizedAccess.aspx.

To accomplish this, add the following code to the login page's Page_Load event handler:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
// This is an unauthorized, authenticated request...
Response.Redirect("~/UnauthorizedAccess.aspx");
}
}

The above code redirects authenticated, unauthorized users to the UnauthorizedAccess.aspx page. To see this logic in action, visit the site as an anonymous visitor and click on the Creating User Accounts link in the left column. This will take you to the ~/Membership/CreatingUserAccounts.aspx page, which in Step 1 we configured to only permit access to Tito. Since anonymous users are prohibited, the FormsAuthenticationModule redirects us back to the login page.

At this point we are anonymous, so Request.IsAuthenticated returns false and we are not redirected to UnauthorizedAccess.aspx. Instead, the login page is displayed. Log in as a user other than Tito, such as Bruce. After entering the appropriate credentials, the login page redirects us back to ~/Membership/CreatingUserAccounts.aspx. However, since this page is only accessible to Tito, we are unauthorized to view it and are promptly returned to the login page. This time, however, Request.IsAuthenticated returns true (and the ReturnUrl querystring parameter exists), so we are redirected to the UnauthorizedAccess.aspx page.
Authenticated, Unauthorized Users are Redirected to UnauthorizedAccess.aspx

Figure 6: Authenticated, Unauthorized Users are Redirected to UnauthorizedAccess.aspx (Click to view full-size image)

This customized workflow presents a more sensible and straightforward user experience by short circuiting the cycle depicted in Figure 2.
Step 3: Limiting Functionality Based on the Currently Logged In User

URL authorization makes it easy to specify coarse authorization rules. As we saw in Step 1, with URL authorization we can succinctly state what identities are permitted and which ones are denied from viewing a particular page or all pages in a folder. In certain scenarios, however, we may want to allow all users to visit a page, but limit the page's functionality based on the user visiting it.

Consider the case of an eCommerce website that allows authenticated visitors to review their products. When an anonymous user visits a product's page, they would see just the product information and would not be given the opportunity to leave a review. However, an authenticated user visiting the same page would see the reviewing interface. If the authenticated user had not yet reviewed this product, the interface would enable them to submit a review; otherwise it would show them their previously-submitted review. To take this scenario a step further, the product page might show additional information and offer extended features for those users that work for the eCommerce company. For example, the product page might list the inventory in stock and include options to edit the product's price and description when visited by an employee.

Such fine grain authorization rules can be implemented either declaratively or programmatically (or through some combination of the two). In the next section we will see how to implement fine grain authorization via the LoginView control. Following that, we will explore programmatic techniques. Before we can look at applying fine grain authorization rules, however, we first need to create a page whose functionality depends on the user visiting it.

Let's create a page that lists the files in a particular directory within a GridView. Along with listing each file's name, size, and other information, the GridView will include two columns of LinkButtons: one titled View and one titled Delete . If the View LinkButton is clicked, the contents of the selected file will be displayed; if the Delete LinkButton is clicked, the file will be deleted. Let's initially create this page such that its view and delete functionality is available to all users. In the Using the LoginView Control and Programmatically Limiting Functionality sections we will see how to enable or disable these features based on the user visiting the page.

Note: The ASP.NET page we are about to build uses a GridView control to display a list of files. Since this tutorial series focuses on forms authentication, authorization, user accounts, and roles, I do not want to spend too much time discussing the inner workings of the GridView control. While this tutorial provides specific step-by-step instructions for setting up this page, it does not delve into the details of why certain choices were made, or what effect particular properties have on the rendered output. For a thorough examination of the GridView control, consult my Working with Data in ASP.NET 2.0 tutorial series.

Start by opening the UserBasedAuthorization.aspx file in the Membership folder and adding a GridView control to the page named FilesGrid. From the GridView's Smart Tag, click the Edit Columns link to launch the Fields dialog box. From here, uncheck the Auto-generate fields checkbox in the lower left corner. Next, add a Select button, a Delete button, and two BoundFields from the upper left corner (the Select and Delete buttons can be found under the CommandField type). Set the Select button's SelectText property to View and the first BoundField's HeaderText and DataField properties to Name . Set the second BoundField's HeaderText property to Size in Bytes , its DataField property to Length , its DataFormatString property to {0:N0} and its HtmlEncode property to False.

After configuring the GridView's columns, click OK to close the Fields dialog box. From the Properties window, set the GridView's DataKeyNames property to FullName. At this point the GridView's declarative markup should look like the following:







HeaderText="Size in Bytes" HtmlEncode="False" />



With the GridView's markup created, we're ready to write the code that will retrieve the files in a particular directory and bind them to the GridView. Add the following code to the page's Page_Load event handler:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string appPath = Request.PhysicalApplicationPath;
DirectoryInfo dirInfo = new DirectoryInfo(appPath);

FileInfo[] files = dirInfo.GetFiles();

FilesGrid.DataSource = files;
FilesGrid.DataBind();
}
}

The above code uses the DirectoryInfo class to obtain a list of the files in the application's root folder. The GetFiles() method returns all of the files in the directory as an array of FileInfo objects, which is then bound to the GridView. The FileInfo object has an assortment of properties, such as Name, Length, and IsReadOnly, among others. As you can see from its declarative markup, the GridView displays just the Name and Length properties.

Note: The DirectoryInfo and FileInfo classes are found in the System.IO namespace. Therefore, you will either need to preface these class names with their namespace names or have the namespace imported into the class file (via using System.IO).

Take a moment to visit this page through a browser. It will display the list of files residing in the application's root directory. Clicking any of the View or Delete LinkButtons will cause a postback, but no action will occur because we've yet to create the necessary event handlers.
The GridView Lists the Files in the Web Application's Root Directory

Figure 7: The GridView Lists the Files in the Web Application's Root Directory (Click to view full-size image)

We need a means to display the contents of the selected file. Return to Visual Studio and add a TextBox named FileContents above the GridView. Set its TextMode property to MultiLine and its Columns and Rows properties to 95% and 10, respectively.


TextMode="MultiLine" Width="95%">

Next, create an event handler for the GridView's SelectedIndexChanged event and add the following code:


protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
// Open the file and display it
string fullFileName = FilesGrid.SelectedValue.ToString();
string contents = File.ReadAllText(fullFileName);
FileContents.Text = contents;
}

This code uses the GridView's SelectedValue property to determine the full file name of the selected file. Internally, the DataKeys collection is referenced in order to obtain the SelectedValue, so it is imperative that you set the GridView's DataKeyNames property to Name , as described earlier in this step. The File class is used to read the selected file's contents into a string, which is then assigned to the FileContents TextBox's Text property, thereby displaying the contents of the selected file on the page.
The Selected File's Contents are Displayed in the TextBox

Figure 8: The Selected File's Contents are Displayed in the TextBox (Click to view full-size image)

Note: If you view the contents of a file that contains HTML markup, and then attempt to view or delete a file, you will receive an HttpRequestValidationException error. This occurs because on postback the TextBox's contents are sent back to the web server. By default, ASP.NET raises an HttpRequestValidationException error whenever potentially dangerous postback content, such as HTML markup, is detected. To disable this error from occurring, turn off request validation for the page by adding ValidateRequest="false" to the @Page directive. For more information on the benefits of request validation as well as what precautions you should take when disabling it, read Request Validation - Preventing Script Attacks.

Finally, add an event handler with the following code for the GridView's RowDeleting event:


protected void FilesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string fullFileName = FilesGrid.DataKeys[e.RowIndex].Value.ToString();
FileContents.Text = string.Format("You have opted to delete {0}.", fullFileName);

// To actually delete the file, uncomment the following line
// File.Delete(fullFileName);
}

The code simply displays the full name of the file to delete in the FileContents TextBox without actually deleting the file.
Clicking the Delete Button Does Not Actually Delete the File

Figure 9: Clicking the Delete Button Does Not Actually Delete the File (Click to view full-size image)

In Step 1 we configured the URL authorization rules to prohibit anonymous users from viewing the pages in the Membership folder. In order to better exhibit fine grain authentication, let's allow anonymous users to visit the UserBasedAuthorization.aspx page, but with limited functionality. To open this page up to be accessed by all users, add the following element to the Web.config file in the Membership folder:










After adding this element, test the new URL authorization rules by logging out of the site. As an anonymous user you should be permitted to visit the UserBasedAuthorization.aspx page.

Currently, any authenticated or anonymous user can visit the UserBasedAuthorization.aspx page and view or delete files. Let's make it so that only authenticated users can view contents of a file and only Tito can delete a file. Such fine grain authorization rules can be applied declaratively, programmatically, or through a combination of both methods. Let's use the declarative approach to limit who can view the contents of a file; we'll use the programmatic approach to limit who can delete a file.
Using the LoginView Control

As we've seen in past tutorials, the LoginView control is useful for displaying different interfaces for authenticated and anonymous users, and offers an easy way to hide functionality that is not accessible to anonymous users. Since anonymous users cannot view or delete files, we only need to show the FileContents TextBox when the page is visited by an authenticated user. To achieve this, add a LoginView control to the page, name it LoginViewForFileContentsTextBox, and move the FileContents TextBox's declarative markup into the LoginView control's LoggedInTemplate.





TextMode="MultiLine" Width="95%">





The Web controls in the LoginView's templates are no longer directly accessible from the code-behind class. For example, the FilesGrid GridView's SelectedIndexChanged and RowDeleting event handlers currently reference the FileContents TextBox control with code like:


FileContents.Text = text;

However, this code is no longer valid. By moving the FileContents TextBox into the LoggedInTemplate the TextBox cannot be directly accessed. Instead, we must use the FindControl("controlId") method to programmatically reference the control. Update the FilesGrid event handlers to reference the TextBox like so:


TextBox FileContentsTextBox = LoginViewForFileContentsTextBox.FindControl("FileContents") as TextBox;
FileContentsTextBox.Text = text;

After moving the TextBox to the LoginView's LoggedInTemplate and updating the page's code to reference the TextBox using the FindControl("controlId") pattern, visit the page as an anonymous user. As Figure 10 shows, the FileContents TextBox is not displayed. However, the View LinkButton is still displayed.
The LoginView Control Only Renders the FileContents TextBox for Authenticated Users

Figure 10: The LoginView Control Only Renders the FileContents TextBox for Authenticated Users (Click to view full-size image)

One way to hide the View button for anonymous users is to convert the GridView field into a TemplateField. This will generate a template that contains the declarative markup for the View LinkButton. We can then add a LoginView control to the TemplateField and place the LinkButton within the LoginView's LoggedInTemplate, thereby hiding the View button from anonymous visitors. To accomplish this, click on the Edit Columns link from the GridView's Smart Tag to launch the Fields dialog box. Next, select the Select button from the list in the lower left corner and then click the Convert this field to a TemplateField link. Doing so will modify the field's declarative markup from:


To:


CommandName="Select" Text="View">



At this point, we can add a LoginView to the TemplateField. The following markup displays the View LinkButton only for authenticated users.






CommandName="Select" Text="View">





As Figure 11 shows, the end result is not that pretty as the View column is still displayed even though the View LinkButtons within the column are hidden. We will look at how to hide the entire GridView column (and not just the LinkButton) in the next section.
The LoginView Control Hides the View LinkButtons for Anonymous Visitors

Figure 11: The LoginView Control Hides the View LinkButtons for Anonymous Visitors (Click to view full-size image)
Programmatically Limiting Functionality

In some circumstances, declarative techniques are insufficient for limiting functionality to a page. For example, the availability of certain page functionality may be dependent on criteria beyond whether the user visiting the page is anonymous or authenticated. In such cases, the various user interface elements can be displayed or hidden through programmatic means.

In order to limit the functionality programmatically, we need to perform two tasks:

Determine whether the user visiting the page can access the functionality, and
Programmatically modify the user interface based on whether the user has access to the functionality in question.

To demonstrate the application of these two tasks, let's only allow Tito to delete files from the GridView. Our first task, then, is to determine whether it is Tito visiting the page. Once that has been determined, we need to hide (or show) the GridView's Delete column. The GridView's columns are accessible through its Columns property; a column is only rendered if its Visible property is set to true (the default).

Add the following code to the Page_Load event handler prior to binding the data to the GridView:


// Is this Tito visiting the page?
string userName = User.Identity.Name;
if (string.Compare(userName, "Tito", true) == 0)
// This is Tito, SHOW the Delete column
FilesGrid.Columns[1].Visible = true;
else
// This is NOT Tito, HIDE the Delete column
FilesGrid.Columns[1].Visible = false;

As we discussed in the An Overview of Forms Authentication tutorial, User.Identity.Name returns the identity's name. This corresponds to the username entered in the Login control. If it is Tito visiting the page, the GridView's second column's Visible property is set to true; otherwise, it is set to false. The net result is that when someone other than Tito visits the page, either another authenticated user or an anonymous user, the Delete column is not rendered (see Figure 12); however, when Tito visits the page, the Delete column is present (see Figure 13).
The Delete Column is Not Rendered When Visited By Someone Other Than Tito (Such as Bruce)

Figure 12: The Delete Column is Not Rendered When Visited By Someone Other Than Tito (Such as Bruce) (Click to view full-size image)
The Delete Column is Rendered for Tito

Figure 13: The Delete Column is Rendered for Tito (Click to view full-size image)
Step 4: Applying Authorization Rules to Classes and Methods

In Step 3 we disallowed anonymous users from viewing a file's contents and prohibited all users but Tito from deleting files. This was accomplished by hiding the associated user interface elements for unauthorized visitors through declarative and programmatic techniques. For our simple example, properly hiding the user interface elements was straightforward, but what about more complex sites where there may be many different ways to perform the same functionality? In limiting that functionality to unauthorized users, what happens if we forget to hide or disable all of the applicable user interface elements?

An easy way to ensure that a particular piece of functionality cannot be accessed by an unauthorized user is to decorate that class or method with the PrincipalPermission attribute. When the .NET runtime uses a class or executes one of its methods, it checks to ensure that the current security context has permission to use the class or execute the method. The PrincipalPermission attribute provides a mechanism through which we can define these rules.

Let's demonstrate using the PrincipalPermission attribute on the GridView's SelectedIndexChanged and RowDeleting event handlers to prohibit execution by anonymous users and users other than Tito, respectively. All we need to do is add the appropriate attribute atop each function definition:


[PrincipalPermission(SecurityAction.Demand, Authenticated=true)]
protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
...
}

[PrincipalPermission(SecurityAction.Demand, Name="Tito")]
protected void FilesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
...
}

The attribute for the SelectedIndexChanged event handler dictates that only authenticated users can execute the event handler, where as the attribute on the RowDeleting event handler limits the execution to Tito.

If, somehow, a user other than Tito attempts to execute the RowDeleting event handler or a non-authenticated user attempts to execute the SelectedIndexChanged event handler, the .NET runtime will raise a SecurityException.
If the Security Context is not Authorized to Execute the Method, a SecurityException is Thrown

Figure 14: If the Security Context is not Authorized to Execute the Method, a SecurityException is Thrown (Click to view full-size image)

Note: To allow multiple security contexts to access a class or method, decorate the class or method with a PrincipalPermission attribute for each security context. That is, to allow both Tito and Bruce to execute the RowDeleting event handler, add two PrincipalPermission attributes:


[PrincipalPermission(SecurityAction.Demand, Name="Tito")]

[PrincipalPermission(SecurityAction.Demand, Name="Bruce")]

In addition to ASP.NET pages, many applications also have an architecture that includes various layers, such as Business Logic and Data Access Layers. These layers are typically implemented as Class Libraries and offer classes and methods for performing business logic- and data-related functionality. The PrincipalPermission attribute is useful for applying authorization rules to these layers.

For more information on using the PrincipalPermission attribute to define authorization rules on classes and methods, refer to Scott Guthrie's blog entry Adding Authorization Rules to Business and Data Layers Using PrincipalPermissionAttributes.

Saturday, November 26, 2011

STATIC Keyword in depth(C#)

The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

The static modifier on a class means that the class cannot be instantiated, and that all of its members are static.

The following class is declared as static and contains only static methods:
static class CompanyEmployee
{
public static void DoSomething() { /*...*/ }
public static void DoSomethingElse() { /*...*/ }
}

A constant or type declaration is implicitly a static member.

A static member cannot be referenced through an instance. Instead, it is referenced through the type name.

For example, consider the following class:
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}
To refer to the static member x, use the fully qualified name (unless it is accessible from the same scope):
MyBaseC.MyStruct.x

*You can directly access structs and static memebers without creating the instance of class.

While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.

It is not possible to use this to reference static methods or property accessors.

If the static keyword is applied to a class, all the members of the class must be static. Otherwise a complie time error will generate stating that you can not declare instance member inside a static class.

Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.

STATIC CLASS:
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();

static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.

STATIC MEMBERS:

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).
You declare static class members by using the static keyword before the return type of the member, as shown in the following example:

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

Static Constructors (C# Programming Guide)
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Monday, November 7, 2011

CLR Architecture

Introduction

Common Language Runtime (CLR) is platform dependent, where as Intermediate Langage (IL) code is platform independent. When dotnet application is executed the request will goto operating system. Operating system will create memory process, and IL instructions will be loaded. Operating system will load CLR to process IL instructions.




The program used for calling CLR is called 'Runtime Host'. Runtime Host for desktop application is windows API function-"corbindtoruntime". Runtime Host for web based application is "Asp.Net worker process".

CLR is a runtime engine with collection of services:

'Assembly Resolver' will read manifest of exe file, it will identify private assemblies and shared assemblies required for application execution. It will forward request to 'Assembly Loader'

Assembly loader will load assemblies from application folder or GAC into application process. 'Type Checker' will verify types used by application with CLS or CTS standards. This provides Type Safety.

'Debug Manager' will activate debugger utility for line by line execution. It allows modification of code without terminating application.

'Exception Manager' will handle exceptions thrown by application. If there is no catch block (that is solution from developer), the application will be terminated.

'Com Marshals' will provide communication with Com component from dotnet application. This provides COM Interoperatability.

'Thread Support' service wil manage multiple threads with in application process. This provides Multi-Threading.

'Garbage Collector' will release unused objects memory. This provides automatic memory management

IL to native compiler is called JIT (Just in Time) compiler. This will process IL instructions into operating system native code.

Saturday, November 5, 2011

Polymorphism in OOPS

Polymorphism

What is polymorphism?
The meaning of the word polymorphism is something like one name, many forms.
How does C# implement polymorphism?
Defination:providing many functionalities with a single insatance name
Polymorphism manifests itself in C# in the form of multiple methods having the same name.
From a practical programming viewpoint, polymorphism manifests itself in two distinct forms in C#:


Fucntion Overloading
Function Overriding



Fucntion Overloading:


Ø Overloading means having more than one method with the same name, but a different number(list) of arguments or diiferent type of arguments in the same class or in a combination of base and derived classes .
Example:
class Projector
{
public static void Display( string str )
{
System.Console.WriteLine( str );
}
public static void Display( int number )
{
System.Console.WriteLine( number);
}

public static void Main()
{
Projector.Display( "Hello" );
Projector.Display( 1234 );

}
}

Output:
Hello
1234

Examples.for Method Overloading possibilities:
1)void calaculate();
2)void calaculate(int a); //ok:u can overload
3)void calaculate(string a, int b);//ok u can overload
4)void calaculate(string h, int t);//error 3 and 4 can’t overload,because signatures are same
5)int calaculate(int g); //error:2 and 5 can't overload based on return type only
//ref method
6)void calaulate(ref int x);// u can overload with all the above methods but u can’t overload with 7th method.
// out method
7)void calaculate(out int x);// u can not overload 6th and 7th methods,but with other methods u can overload 6th and 7th methods individually.


Function Overriding



2)Function Overriding:
Overriding means have a method with the same name and the same signature in the base class and derived classes.
To override a method we have to use “virtual” keyword for base class method and override keyword for derived class method.

Example:
using System;
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Derived d1 ;
d1= new Derived();
d1.Method(); // Displays 'Derived Method'
}
}
When we declare a virtual method, it must contain a method body. Other wise the compiler will generate an error.
Remember that, since virtual methods are used for achieving polymorphism and since polymorphism works only with objects, it not possible to declare a static method as virtual in C#.
Similarly the private methods are also not possible to declare virtual, since they can’t override inside a derived class.

Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference..

Both methods should have the same access level; the same return type, the same name and same method signature.








Let's understand this through small examples.
Example for NEW keyword:
We can override a method without declaring the base class method as 'virtual'. We can use the modifier 'new' to tell the compiler that the derived class method 'hides' the base class method.

class Base
{
public void Display()
{
Console.WriteLine("Base method");
}
}

class Derived:Base
{
new public void Display()
{
Console.WriteLine("Drived method");
}
}

class HideTest
{
public static void Main()
{

Base b=new Base();
b.display();
Derived d=new Derived();
d.Display();
}
}
Output:
Base method
Derived method
Example1:

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b; // creating reference variable b of type BC
b = new BC(); //creating object of type BC and assign its reference to reference variable b

b.Display();
}
}
Output
BC::Display
The above program compiles and runs successfully to give the desired output. It consists of a base class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the function Display() it inherited from the base class BC by providing its on implementatin of Display(). Class Demo consists of entrypoint function Main(). Inside Main() we first create a reference b of type BC. Then we create an object of type BC and assign its reference to reference variable b. Using the reference variable b we invoke the function Display(). As expected, Display() of class BC is executed because the reference variable b refers to the object of class BC.
Now we add a twist of line to the above program.

Example 2

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();
}
}
Output




BC::Display
BC::Display
Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That's because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display() of class BC will be invoked, no matter whom b refers to. Take one more example.
Example 3

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : BC
{
new public void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();

b = new TC();
b.Display();
}
}
Output

BC::Display
BC::Display
BC::Display
The output of the above program is a receipt of the fact that no matter to whom base class reference b refers, it invokes the functions of the class that matches its type.
But actually , If b contains the reference to a particular derived class object, then its supposed to invoke the function of that class.
Well, C# helps us do this by the usage of keywords virtual and override as shown in the following program.
Example 4

class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();
}
}
Output
BC::Display
DC::Display
The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the Derived class's implementation of Display() is decorated with the modifier override. Doing so enables C# to invoke functions like Display() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when b refers to the object of class BC it invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of class DC. Let's see if this holds true for the third generation of derived classes. Take the following program.
Example 5
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{
public override void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();

b = new TC();
b.Display();
}
}
Output
BC::Display
DC::Display
TC::Display
The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the implementation of Display() in successive Derived classes is decorated with the modifier override. Next, we succesively create objects of each class and store their reference in base class reference variable b and invoke Display(). The rite versions of Display get invoked based on the object the reference variable refers to. Time for a tiny teaser! Guess what the output would be in the following program?
Example 6
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{

}

class Demo
{
public static void Main()
{
BC b;

b = new TC();
b.Display();
}
}
Output
DC::Display
Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived from DC. Hence Display() from Derived class DC gets executed. It's as if the derived class TC looked like this:
class TC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}
to the compiler. Take one more example. Guess what its output will be.

Example 7

class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{
public new void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;

b = new TC();
b.Display();
}
}
Output

DC::Display
Agreed that TC defines its own new version of Display(). But its version of display is not invoked as Display() of TC does not override the Display() of the base class. With this understood we are done with Method overriding in C#.

Differences between Function overriding and Function overloading


Function Overloading Function Overriding
1) Both method names should be same,but signature should not be same.
1) Both method names,and signature and retun type should be same

2) In Overloading we will not use any virtual and override keywords 2) In overriding we have to use Virtual and Override keywords
3)Overloading we can implement with in single class or combination
of base and derived classes.

3)We can implement Overriding in base class and derived class but we can not implement in a single class