List To DataTable and Vice Versa using C#

public class ObjectConverter
 {
     public DataTable ListToDataTable(List items)
     { 
          DataTable dataTable = new DataTable(typeof(T).Name);
          //Get all the properties
          PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public |         BindingFlags.Instance);
          foreach (PropertyInfo prop in Props)
          {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
          }
          foreach (T item in items)
          {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
             {
               //inserting property values to datatable rows
               values[i] = Props[i].GetValue(item, null);
             }
            dataTable.Rows.Add(values);
          }
          return dataTable;
     }

     public static List DataTableToList(DataTable dt)
     {
       List lstdata = new List();
       foreach (DataRow row in dt.Rows)
        {
           T item = GetItem(row);
           lstdata.Add(item);
        }
        return lstdata;
      }

      private static T GetItem(DataRow dr)
      {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance();

        foreach (DataColumn column in dr.Table.Columns)
        {
          foreach (PropertyInfo pro in temp.GetProperties())
          {
            if (pro.Name == column.ColumnName)
               pro.SetValue(obj, dr[column.ColumnName], null);
            else
               continue;
          }
        }
        return obj;
       }
 }
Calling : 
 ObjectConverter converter = new ObjectConverter();
 
 DataTable dtstudentDetails=new DataTable();
 dtstudentDetails = converter.ListToDataTable(lststudentDetails); 

 List lststudentDetails = new List(); 
 lststudentDetails = converter.DataTableToList(dtstudentDetails);

Event Handlers in C#

An event handler is a callback routine that operates asynchronously and handles inputs received into a program (events).

You can create server event handlers for controls and for the page in a variety of ways.

in the below example, in Button1_Click, Button2_Click event is also executed.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<html>
<head runat=”server”>
<title>Event Handlers</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Button1″ />
<asp:Button ID=”Button2″ runat=”server” OnClick=”Button2_Click” Text=”Button2″ />
</div>
</form>
</body>
</html>

using System;

public partial class _Default : System.Web.UI.Page
{
public string message;

protected override void OnInit(EventArgs e)
{
base.OnInit(e);

//Attach event handler for Page Load event.
this.Load += new EventHandler(Page_Load);

//Attache event handler for button1 Click event.
this.Button1.Click += new EventHandler(Button2_Click);
}

protected void Page_Load(object sender, EventArgs e)
{
//Displays message when the Page.Load event is fired.
//message = “In the Page_Load event handler.”;
//Response.Write(message);
}

protected void Button1_Click(object sender, EventArgs e)
{
//Displays message when the button Click event is fired.
message = “In the button1 click event Calling Button2 Click Event ->”;
Response.Write(message);
}

protected void Button2_Click(object sender, EventArgs e)
{
message = “In the button2 click event :”;
Response.Write(message);
}
}

User Control & Dynamic Loading functionality

User controls allow you to save a part of an existing ASP.NET page and reuse it in many other ASP.NET pages.

Hence common functionalities (Headers, Footers, Menus, Dashboards…) are developed as user controls and used in Project.

The following line includes a header user control from the HeaderUserControl.ascx file:

<%@ Register TagPrefix=”uc1″ TagName=”HeaderUserControl” Src=”HeaderUserControl.ascx” %>

The header is then positioned on the page using the following tag:

<uc1:HeaderUserControlid=”Header1″runat=”server”></uc1:HeaderUserControl>

Although this procedure is satisfactory for content like headers and footers that will always be required on specific pages, it would be useful if there was a way of dynamically loading specific user controls at run time.

Fortunately, it is possible to load user controls onto a page by making use of the LoadControl method.

This function has a straightforward syntax – it takes a single argument – the virtual path to the user control page. For example, to load the featured product user control the following C# code would be used within the Page_Load method:

Control FeaturedProductUserControl = LoadControl(“FeaturedProduct.ascx”);

Once the user control has been loaded, it can be added to the page by adding it to the Controls collection:

Controls.Add(FeaturedProductUserControl);

The drawback with this technique is that it offers no control over where on the page the user control will actually appear. A useful tip is, therefore, to add a place holder control to the page in the position that you want it to display the dynamically loaded user controls. A place holder does just that – it acts as a container for other controls. You can then specify that the user control appear within the place holder by adding the user control to the place holder’s controls collection:

PlaceHolderLeftMenu.Controls.Add(FeaturedProductUserControl);

Alternatively it is possible to position the user control in other ways, such as adding it to a Panel control:

PanelRightMenu.Controls.Add(FeaturedProductUserControl);

Making Full Use of Dynamically Loaded User Controls

Since it is possible to dynamically load user controls onto specific pages, it provides the idea functionality for creating page templating facilities within ASP.NET. For example, by storing the details of available user controls in a database, it would be possible to write a content management system that allowed the website’s administrative users to choose which user controls they wanted to display on each page. This page templating system is used in content management systems such as the portal layout functionality in Microsoft’s SharePoint Portal Server.

ASP.NET page life cycle Events

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, we will discuss in detail the ASP.NET page life cycle Events.

asp.net page lifecycle

(1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.

protected void Page_PreInit(object sender, EventArgs e)

{

Use this event for the following:

Check the IsPostBack property to determine whether this is the first time the page is being processed.

Create or re-create dynamic controls.

Set a master page dynamically.

Set the Theme property dynamically.

}

(2)Init This event fires after each control has been initialized, each control’s UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

protected void Page_Init(object sender, EventArgs e)

{

Raised after all controls have been initialized and any skin settings have been applied.

Use this event to read or initialize control properties.

}

(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

protected void Page_InitComplete(object sender, EventArgs e)

{

Raised by the Page object.

Use this event for processing tasks that require all initialization be complete.

}

(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance

(1)Loads ViewState : ViewState data are loaded to controls

Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request.

(2)Loads Postback data : postback data are now handed to the page controls

Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.

protected override void OnPreLoad(EventArgs e)

{

Use this event if you need to perform processing on your page or control before the Load event.

Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

}

(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

protected void Page_Load(object sender, EventArgs e)

{

The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.

Use the OnLoad event method to set properties in controls and establish database connections.

}

(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown’s selectedindexchange event,for example. These are the events, the code for which is written in your code-behind class(.cs file).

protected void Button1_Click(object sender, EventArgs e)

{

This is just an example of control event..

Here it is button click event that caused the postback

}

(7)LoadComplete This event signals the end of Load.

protected void Page_LoadComplete(object sender, EventArgs e)

{ Use this event for tasks that require that all other controls on the page be loaded.

}

(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

protected override void OnPreRender(EventArgs e)

{

Each data bound control whose DataSourceID property is set calls its DataBind method.The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

}

(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

protected override void OnSaveStateComplete(EventArgs e)

{

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

}

(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

Note: Right click on the web page displayed at client’s browser and view the Page’s Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.

// Render stage goes here. This is not an event

(11)UnLoad This event is used for cleanup code. After the page’s HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on

(a)Instances of classes i.e. objects

(b)Closing opened files

(c)Closing database connections.

protected void Page_UnLoad(object sender, EventArgs e)

{

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

}

Print Screen or Screenshot using C#

A simple add-on that will capture the user screen and automatically send it to the system administrator.
This add-on will be plug-in into our existing systems. It will be automatically triggered if an error is detected so the system administrator can analyze the problem on-hand before going to the user to fix the error.

using System.Drawing;
using System.Drawing.Imaging;
using System.Media;
using System.Windows.Forms;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(printscreen);

graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

printscreen.Save(@”C:\printscreen.jpg”, ImageFormat.Jpeg);  
}
}

ASP.NET Website with Membership And User Login

It is a standard requirement for websites to have a user authentication and allow users to see only certain pages. The common method of authentication is to ask for username and password. Here is a good walkthrough article that I tested to create ASP.NET website authentication using the ASP.NET membership services. I suggest you to read through it and follow each step carefully. The tutorial requires Microsoft Visual Web Developer, IIS and SQL Server Express Edition on your local computer, and access to an e-mail server.

This Walkthrough will perform the following tasks:

– Configuring an application to include ASP.NET membership services, and how to define users.
– Using login controls to get user credentials and to display information to logged-in users.
– Protecting one or more pages in your application so that only logged-in users can view them.
– Allowing new users to register at your site.
– Allowing members to change and reset their passwords.

Walkthrough: Create a Web Site with Membership and User Login

Principal Design Features Of .NET Framework

Interoperability

Because interaction between new and older applications is commonly required, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework

Common Runtime Engine

The Common Language Runtime (CLR) is the virtual machine component of the .NET Framework. All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and behaviors in the areas of memory management, security, and exception handling.

Language Independence

The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible datatypes and programming constructs supported by the CLR and how they may or may not interact with each other conforming to the Common Language Infrastructure (CLI) specification. Because of this feature, the .NET Framework supports the exchange of types and object instances between libraries and applications written using any conforming .NET language.

Simplified Deployment

The .NET Framework includes design features and tools that help manage the installation of computer software to ensure that it does not interfere with previously installed software, and that it conforms to security requirements.

Security

The design is meant to address some of the vulnerabilities, such as buffer overflows, that have been exploited by malicious software. Additionally, .NET provides a common security model for all applications.

Portability

The design of the .NET Framework allows it to theoretically be platform agnostic, and thus cross-platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented.