Five Pillars of .NET Programming

Five Pillars of .NET Programming


VB.Net => C# converter

Read Users' Comments (0)

Delegate Example

http://www.codeproject.com/KB/cs/DelegatesOMy.aspx


Read Users' Comments (0)

ADO.NET

1). What is the namespace in which .NET has the data functionality classes ?

Following are the namespaces provided by .NET for data management :-

1. System.data :

This contains the basic objects used for accessing and storing relational data, such as
DataSet,DataTable, and DataRelation. Each of these is independent of the type of data
source and the way we connect to it.

2. System.Data.OleDB

It contains the objects that we use to connect to a data source via an OLE-DB provider,
such as OleDbConnection, OleDbCommand, etc. These objects inherit from the common
base classes, and so have the same properties, methods, and events as the SqlClient
equivalents.

3. System.Data.SqlClient

This contains the objects that we use to connect to a data source via the Tabular Data
Stream (TDS) interface of Microsoft SQL Server (only). This can generally provide better performance as it removes some of the intermediate layers required by an OLE-DB
connection.

4. System.XML

This Contains the basic objects required to create, read, store, write, and manipulate
XML documents according to W3C recommendations.

2). Can you give a overview of ADO.NET architecture ?

The most important section in ADO.NET architecture is “Data Provider”. Data Provider
provides access to datasource (SQL SERVER, ACCESS, ORACLE).In short it provides
object to achieve functionalities like opening and closing connection, retrieve data and
update data. In the below figure you can see the four main sections of a data provider :-

1. Connection.
2. Command object (This is the responsible object to use stored procedures)
3. Data Adapter (This object acts as a bridge between datastore and dataset).
4. Datareader (This object reads data from data store in forward only mode).

*** “DataView” object is used to sort and filter data in Datatable.

3). What are the two fundamental objects in ADO.NET ?

Datareader and Dataset

4). What is difference between dataset and datareader ?

DataReader provides forward-only and read-only access to data, while the
DataSet object can hold more than one table (in other words more than one
rowset) from the same data source as well as the relationships between them.

Dataset is a disconnected architecture while datareader is connected
architecture.

Dataset can persist contents while datareader can not persist contents, they
are forward only.

5). What are major difference between classic ADO and ADO.NET ?

Following are some major differences between both

√ As in classic ADO we had client and server side cursors they are no more
present in ADO.NET. Note it's a disconnected model so they are no more
applicable.
√ Locking is not supported due to disconnected model.
√ All data persist in XML as compared to classic ADO where data
persisted in Binary format also

6). What is the use of connection object ?

They are used to connect a data to a Command object.

√ An OleDbConnection object is used with an OLE-DB provider255
√ A SqlConnection object uses Tabular Data Services (TDS) with MS SQL Server

7). What is the use of command objects ?

They are used to connect connection object to Datareader or dataset. Following are the
methods provided by command object :-

√ ExecuteNonQuery :- Executes the command defined in the CommandText
property against the connection defined in the Connection property for a query
that does not return any row (an UPDATE, DELETE or INSERT). Returns
an Integer indicating the number of rows affected by the query.

√ ExecuteReader :- Executes the command defined in the CommandText property
against the connection defined in the Connection property. Returns a "reader"
object that is connected to the resulting rowset within the database, allowing
the rows to be retrieved.

√ ExecuteScalar :- Executes the command defined in the CommandText property
against the connection defined in the Connection property. Returns only
single value (effectively the first column of the first row of the resulting rowset)
any other returned columns and rows are discarded. It is fast and efficient
when only a "singleton" value is required

8). What is the use of dataadapter ?

These are objects that connect one or more Command objects to a Dataset object. They
provide logic that would get data from the data store and populates the tables in the
DataSet, or pushes the changes in the DataSet back into the data store.
√ An OleDbDataAdapter object is used with an OLE-DB provider
√ A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.

Read Users' Comments (0)

c# indexer

What is Indexer ?


An indexer is a member that enables an object to be indexed in the same way as an array.

mark.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///
/// Summary description for mark
///
public class mark
{
public mark()
{
//
// TODO: Add constructor logic here
//
}

private string[] x = new string[5];

public string this [int index]
{
get
{
return x[index];
}
set
{
x[index] = value;
}
}
}


Execute in page load event in the page

protected void Page_Load(object sender, EventArgs e)
{
mark m = new mark();
m[0] = "kasun";
m[1] = "kasunt";
m[2] = "kasunl";
m[3] = "kasun1";
m[4] = "kasun2";

Response.Write(m[4]);
}


Read Users' Comments (0)

Convert textbox name using findcontrol

int[] verdierX = new int[8];

private void Form1_Load(object sender, EventArgs e)
{
for (var i = 0; i < 8; i++)
{
TextBox tb = (TextBox)FindControl("box" + i.ToString());
verdierX[i] = (int)decimal.Parse(tb.Text);
}
}

Read Users' Comments (0)

Search page code

#region Using Directives
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ELearning.SystemCore.BLL.Object;
using ELearning.SystemCore.BLL;
using ELearning.Common;
#endregion

public partial class UserControls_UCSearchJob : System.Web.UI.UserControl
{
#region Public Properties
private int PageIndex
{
get { return (ViewState["pageIndex"] == null ? 1 : Convert.ToInt32(ViewState["pageIndex"])); }
set { ViewState["pageIndex"] = value; }
}

string _editPageName = "";
public string EditPageName
{
get { return _editPageName; }
set { _editPageName = value; }
}

#endregion

private ManageJob manageJob = new ManageJob();

protected override void CreateChildControls()
{
base.CreateChildControls();

if (!Page.IsPostBack)
InitializeControls();
}

private void InitializeControls()
{
ClearMessages();
//LoadJobs();
}

private void LoadJobs()
{
Job job = new Job();

string jobName = txtJobName.Text;
int? totalRecords = null;
int? organizationId = null;
List jobs= new List();
try
{
jobs = manageJob.GetJobForSearch(txtJobName.Text.Trim(),
organizationId,
true,
PageIndex,
CommonConst.PageSize,
out totalRecords);
if (jobs!=null && totalRecords!=0)
{
chkSelectAll.Visible = true;
rptJobList.DataSource = jobs;
rptJobList.DataBind();
ucPagin.MemberCount = NullHandler.NullHandlerForInt(totalRecords, 0);
ucPagin.PageCount = CommonConst.PageCount;
ucPagin.PageSize = CommonConst.PageSize;
ucPagin.LoadLinkButtons();

}
else
{
chkSelectAll.Visible = false;
ClearGrid();
ClearMessages();
lblErrorMessage.Text = "Position title not found.";
}
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
lblErrorMessage.Text = "Error has occurred while loading data.";
}
}
private void ClearGrid()
{
rptJobList.DataSource = null;
rptJobList.DataBind();
ucPagin.MemberCount = 0;
ucPagin.PageCount = CommonConst.PageCount;
ucPagin.PageSize = CommonConst.PageSize;
ucPagin.LoadLinkButtons();
}

private void ClearMessages()
{
lblErrorMessage.Text = string.Empty;
lblSuccessMessage.Text = string.Empty;
}


protected void rptJobList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Job job = (Job)e.Item.DataItem;

((HiddenField)e.Item.FindControl("hdnID")).Value = job.JobId.ToString();
((Label)e.Item.FindControl("lblJobId")).Text = job.JobId.ToString();
((Label)e.Item.FindControl("lblJobName")).Text = job.Name.ToString();
((Label)e.Item.FindControl("lblJobDesc")).Text = job.Description.ToString();

((LinkButton)e.Item.FindControl("lnkEdit")).CommandName = "Edit";
((LinkButton)e.Item.FindControl("lnkEdit")).CommandArgument = job.JobId.ToString();
}
}

protected void rptJobList_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
string url = string.Empty;

switch (e.CommandName)
{
case "Edit":
url = String.Format("AddJob.aspx?id={0}", e.CommandArgument.ToString());
Response.Redirect(url);
break;
}
}

protected void btnSearch_Click(object sender, EventArgs e)
{
PageIndex = 1;
ClearMessages();
LoadJobs();
}

private void ClearControls()
{
txtJobName.Text = string.Empty;
}

protected void btnDelete_Click(object sender, EventArgs e)
{
PageIndex = 1;
ClearMessages();
Delete();
//LoadJobs();
}

private void Delete()
{
ArrayList arrSelectedJobs = new ArrayList();
try
{
foreach (RepeaterItem item in rptJobList.Items)
{
CheckBox chkBox = (CheckBox)item.FindControl("chkSelect");
if (chkBox.Checked)
{
arrSelectedJobs.Add(((HiddenField)item.FindControl("hdnId")).Value);
}
}

if (arrSelectedJobs.Count > 0)
{
if (manageJob.DeleteJob(arrSelectedJobs))
{
lblSuccessMessage.Text = "Successfully Deleted!";
LoadJobs();
}
}
else
{
lblErrorMessage.Text = "No record is selected!";
}
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
lblErrorMessage.Text = "Delete Job error ";
}
}

protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
try
{
for (int itemCount = 0; itemCount <>
{
CheckBox chkBox = ((CheckBox)rptJobList.Items[itemCount].FindControl("chkSelect"));
if (chkSelectAll.Checked == true && chkBox.Enabled == true)
chkBox.Checked = true;
else
chkBox.Checked = false;
}
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
lblErrorMessage.Text = "Select All Position title error(s) ";
}
}

#region Pagin Protected Methods
protected void ucPagin_PageIndexChanged(int pageIndex)
{
PageIndex = pageIndex;
LoadJobs();
}

protected void ucPagin_Load(object sender, EventArgs e)
{
ucPagin.PageIndexChanged += new UserControls_PaginationControl_Paginator.SelectedPageIndexChanged(ucPagin_PageIndexChanged);
}

#endregion


}

Read Users' Comments (0)

Add page code

#region Using Directives

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ELearning.SystemCore.BLL.Object;
using ELearning.SystemCore.BLL;
using ELearning.Common;

#endregion

///
/// Summary description for UserControls_UCAddJob
///

public partial class UserControls_UCAddJob : System.Web.UI.UserControl
{
private int mode;
#region Public Properties
int _selectedJobId = 0;

public int SelectedJobId
{
get { return _selectedJobId; }
set { _selectedJobId = value; }
}

#endregion


#region Protected Methods

protected void Page_Load(object sender, EventArgs e)
{
ELearning.Common.Configuration.GetQueryStringValue("id", out _selectedJobId);
}

protected override void CreateChildControls()
{
base.CreateChildControls();

if (!Page.IsPostBack)
InitializeControls();
}

#endregion

#region Public Methods

#endregion

#region Private Methods

private void InitializeControls()
{
try
{
ClearControls();
mode = SetControlMode();
if (mode == (int)ELearning.Common.ELearningEnum.PageMode.Add)
{
btnAdd.Text = "Add";
}
else if (mode == (int)ELearning.Common.ELearningEnum.PageMode.Edit)
{
btnAdd.Text = "Edit";
}
else
{
ClearMessages();
lblErrorMessage.Text = "Invalid mode";
return;
}
SetForJob();
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
lblErrorMessage.Text = "Error has occured!";
}
}

private int SetControlMode()
{
try
{
if (_selectedJobId == 0)
return (int)ELearning.Common.ELearningEnum.PageMode.Add;
else
return (int)ELearning.Common.ELearningEnum.PageMode.Edit;
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
return -1;
}
}

private void SetHeader()
{
try
{
string header = string.Empty;

//Set Mode
if (mode == (int)ELearningEnum.PageMode.Add)
header = "Add Position Title";
else if (mode == (int)ELearningEnum.PageMode.Edit)
header = "Edit Position Title";

ClearMessages();
h1Heading.InnerHtml = header;
}
catch (Exception ex)
{
lblErrorMessage.Text = "Error has occurred while binding header Information.";
ELearning.ErrorLogger.Error.WriteErrorLog(ex, "Error has occurred while binding header Information.");
}
}

private void SetForJob()
{
mode = SetControlMode();
SetHeader();

if (mode == (int)ELearningEnum.PageMode.Edit)
{
LoadJob(SelectedJobId);
}
}

private void LoadJob(int jobId)
{
Job job = null;
try
{
job = new ManageJob().GetJob(jobId);
if (job != null)
{
txtJobName.Text = job.Name;
txtJobDescription.Text = job.Description;
}
else
{
ClearMessages();
lblErrorMessage.Text = "Position Title not found!";
}
}
catch (Exception ex)
{
lblErrorMessage.Text = "Data binding error!";
ELearning.ErrorLogger.Error.WriteErrorLog(ex, "Data binding error!");
}
}

private void ClearControls()
{
txtJobName.Text = string.Empty;
txtJobDescription.Text = string.Empty;
}

private void ClearMessages()
{
lblErrorMessage.Text = string.Empty;
lblSuccessMessage.Text = string.Empty;
}

#endregion
protected void btnAdd_Click(object sender, EventArgs e)
{
bool isAdd;
bool isSuccess = false;
ClearMessages();

try
{
mode = SetControlMode();
if (mode == (int)ELearning.Common.ELearningEnum.PageMode.Add)
{
isAdd = true;
}
else
{
isAdd = false;
}

int? organizationId = null;
ManageJob manageJob = new ManageJob();
int retJobId = manageJob.AddJob(isAdd,
SelectedJobId,
txtJobName.Text.Trim(),
txtJobDescription.Text.Trim(),
organizationId);


isSuccess = (retJobId > 0);
if (isSuccess)
{
if (isAdd)
{
lblSuccessMessage.Text = "Position Title successfully added!";
ClearControls();
}
else
{
lblSuccessMessage.Text = "Position Title successfully updated!";
}
}
else
{
if (retJobId == -99)
lblErrorMessage.Text = "Position Title already exists!";
else
lblErrorMessage.Text = "Error has occured!";
}
}
catch (Exception ex)
{
lblErrorMessage.Text = "Error has occured!";
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
}
}
}

Read Users' Comments (0)

Crystal Report

#region Using Directives
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ELearning.SystemCore.BLL.Object;
using ELearning.SystemCore.BLL;
using ELearning.Common;
#endregion

public partial class CRSurveyResultsGraphicReport : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
CrystalDecisions.CrystalReports.Engine.ReportDocument myReportDocument;
myReportDocument = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

DataTable dtRec = GetSurveyResultsGraphicReport();

myReportDocument.Load(Server.MapPath("Reports\\CRSurveyResultsGraphicReport.rpt"));
myReportDocument.SetDataSource(dtRec);

CRViewer.DisplayGroupTree = false;
myReportDocument.SetDataSource(dtRec);

CRViewer.DisplayGroupTree = false;
CRViewer.ReportSource = myReportDocument;
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
}
}


private DataTable GetSurveyResultsGraphicReport()
{
DataTable dtRec = new DataTable();
dtRec.Columns.Add("intSurveyId");
dtRec.Columns.Add("vcSurveyName");
dtRec.Columns.Add("intQuestionId");
dtRec.Columns.Add("intUserId");
dtRec.Columns.Add("vcUserName");
dtRec.Columns.Add("vcSurveyResponse");
dtRec.Columns.Add("Count", typeof(Int32));
DataSet ds = new DataSet();
ManageSurvey manageSurvey = new ManageSurvey();

int surveyId = 1;

ds = manageSurvey.GetSurveyResultsSummary(ManageUser.GetLoggedUser().OrganizationId, surveyId);
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dR in ds.Tables[0].Rows)
{
DataRow dRNew = dtRec.NewRow();

//dRNew["intSurveyId"] = NullHandler.AvoidNullint(dR["intSurveyId"]);
//dRNew["vcSurveyName"] = NullHandler.AvoidNullStr(dR["SurveyName"]);
dRNew["intQuestionId"] = NullHandler.AvoidNullint(dR["intSurveyQuestionId"]);
//dRNew["intUserId"] = NullHandler.AvoidNullint(dR["intUserId"]);
//dRNew["vcUserName"] = NullHandler.AvoidNullStr(dR["cUserName"]);
dRNew["vcSurveyResponse"] = NullHandler.AvoidNullStr(dR["SurveyResponse"]);
dRNew["Count"] = NullHandler.AvoidNullint(dR["Count"]);
dtRec.Rows.Add(dRNew);
}
}
return dtRec;
}
}


Read Users' Comments (0)

ServiceContractAttribute Class

Base Namespace: System.ServiceModel


Indicates that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.

An interface or class that is decorated with ServiceContractAttribute must also have at least one method marked with the OperationContractAttribute attribute to expose any functionality. See the Examples section for a code example of the simplest use of the two attributes to define and implement a service.
using System; using System.Collections.Generic; using System.Net.Security; using System.ServiceModel; using System.Text;  namespace Microsoft.WCF.Documentation {   [ServiceContract(     Namespace="http://microsoft.wcf.documentation",     Name="SampleService",     ProtectionLevel=ProtectionLevel.EncryptAndSign   )]   public interface ISampleService{     [OperationContract]     string SampleMethod(string msg);   }

Use the ServiceContractAttribute properties to modify the service contract.

  • The ConfigurationName property specifies the name of the service element in the configuration file to use.

  • The Name and Namespace properties control the name and namespace of the contract in the WSDL element.

  • The SessionMode property specifies whether the contract requires a binding that supports sessions.

  • The CallbackContract property specifies the return contract in a two-way (duplex) conversation.

  • The HasProtectionLevel and ProtectionLevel properties indicate whether all messages supporting the contract have a explicit ProtectionLevel value, and if so, what that level is.


Read Users' Comments (0)

get relationship object (object to object)

public List GetUserCourses(int userID)
{
List userCourses = new List();
try
{
TblUserCourseCollection tblUserCourses = new TblUserCourseCollection()
.Where(TblUserCourse.Columns.IntUserId, userID)
.Load();

foreach (TblUserCourse tblUserCourse in tblUserCourses)
{
if (tblUserCourse.TblCourse.BitIsActive)
{
Course course = new Course();
course.CourseId = tblUserCourse.IntCourseId;
course.Code = tblUserCourse.TblCourse.VcCode;
course.Description = tblUserCourse.TblCourse.VcDescription;
course.IsActive = tblUserCourse.TblCourse.BitIsActive;
course.Name = tblUserCourse.TblCourse.VcName;
userCourses.Add(course);

course.Lessons = new List();

if (tblUserCourse.TblCourse.TblLessonRecords != null)
{
foreach (TblLesson tblLesson in tblUserCourse.TblCourse.TblLessonRecords)
{
Lesson lesson = new Lesson();
lesson.LessonId = tblLesson.IntLessonId;
lesson.Name = tblLesson.VcName;
course.Lessons.Add(lesson);
}
}
}
}
}
catch (Exception ex)
{
ELearning.ErrorLogger.Error.WriteErrorLog(ex);
}
return userCourses;
}

Read Users' Comments (0)

Satelite assemblies

1. Explain Satellite assemblies
Satellite assemblies, are assembly files (.dll) that contain localized resources for an application. Each satellite assembly file contains the resources for one culture. An application can have many satellite assemblies, depending on how many cultures the application supports.
2. What is the different between <%# %> and <%= %>?
The <%# %> is used for databinding where as <%= %> is used to output the result of an expression. The expression inside &tl;%# %> will be executed only when you call the page's or control's DataBind method. The expression inside <%= %> will be executed and displayed as and when it appears in the page.
3. Difference between AutoEventWireUp=true and AutoEventWireUp=false
Autoevenwireup=true means whenevery your page is loaded all the events are automaticcllay called. if false, cant'
4. Why do some of the events on my page fire twice?
This is probably because you explicitly subscribed to the events in code and also specified the AutoEventWireUp of Page to true (it's true by default). If so, the Page_Load, for example, will be fired once for your event subscription and once because the Page subscribed it for you (by looking for a specific event handler method signature). To avoid this turn off AutoEventWireUp or remove your subscription code.

Read Users' Comments (0)

Globalization vs Localization

What is Globalization?

1. Globalization is process of identifying all the localizable resources in the application, that will support multiple cultures. Ideally it is perform during design phase of an application, so that the resources always remains separate from the code.
2. The process of creating an application that meets the needs of users from multiple cultures.
3. The process of developing a program core whose features and code design are not solely based on a single language or locale.
What is Localization?
1. In Localization you customize the application for new locales. This consist of translating resources that you identified during the globalization phase.
2. The process of accommodating cultural differences within an application.
3. The process of adapting a program for a specific local market.
4. Localized applications can support multiple languages, currencies, writing direction, and calendars based on the cultures that they support.
Difference between Localization and Globalization?
1. You can visualize globalization as more of architecture decisions. While localization is adapting your content to local market. Localization phase occurs before globalization phase.
2. Globalization is process of identifying how many resources needs to be localized to adopt a multiple culture support, while Localization is actual process of translating resource to a specific culture.

Read Users' Comments (0)

Session

1. What is the difference between Session.Abandon() and Session.Clear()?

The major difference is that if you call Session.Abandon(), Session_End will be fired (for InProc mode), and in the next request, Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.

2. Explain Session.Abandon()

Session.Abandon(), explicitly ending a user session. If a user requests a new page after the Abandon method is called, he or she is treated as a new user. The user is assigned a new session ID and all the items in session state previously associated with that user are removed from memory. The Abandon method is often used with sign-out pages.


3. Different Modes of Session States

Storing Session State In Process
Storing Session State In Windows Service
Storing Session State In Database Table
4. Explain Advantage and disadvantage Storing Session State In Process

Advantages:
By default, session state are stored in process. The advantage of storing session state in process is performance. You can store and retrieve items much faster in session state.

DisAdvantages:
1) If, for whatever reason, the server crashes, you lose all data stored in session state. You lose session data when an ASP.NET application is reloaded for any reason.
2) If session state is stored in process, session state cannot be shared across multiple servers. Storing session state in process limits the scalability of your Web site because you cannot configure multiple servers to handle requests. In other words, storing session state in process is incompatible with Web farms.
5. Explain Advantage and disadvantage Storing Session State In Windows Service

Advantages:
1) Crashes of ASP.net will not destroy session information.
2) It is compatible with Web Farms scenario.

DisAdvantages:
Reading and writing session state is slower than Session state In Process.
6. Explain Advantage and disadvantage Storing Session State In Database Table

Advantages:
1) Crashes of ASP.net will not destroy session information.
2) It is compatible with Web Farms scenario.
3) The advantage of this approach is that you can cluster multiple database servers so that if one server fails, another database server can take over the state management.

DisAdvantages:
Reading and writing session state is slower than Session state In Process.

7. Response.Redirect and Server.Transfer is not working in Session_End?

Session_End is fired internally by the server, based on an internal timer. And thus there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transfer does not make sense and will not work.
8. Is the session Timeout attribute a sliding timeout value?

The session Timeout is a sliding expiration time, meaning whatever your page access session state, the expiration time will be moved forward.
9. Is the session timeout attribute in minutes or seconds?
The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default is 20

10. Can I share session state between ASP.NET and ASP pages?
No.

Read Users' Comments (0)

Managing Unhandled Exception

Managing Unhandled Exception You can manage unhandled exception with custom error pages in asp.net. You should configure the element in web.config file. It has two attributes:

  • Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
    • On - Displays custom error pages at both the local and remote client.
    • Off - Disables custom error pages at both the local and remote client.
    • RemoteOnly - Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
  • defaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
  • You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.

  • statusCode="403" redirect="NoAccess.htm" />
    statusCode="404" redirect="FileNotFound.htm" />

Read Users' Comments (0)

Understanding DateTime and TimeSpan in .Net

*** Understanding DateTime and TimeSpan in .Net through real time example :

//Creating Two Instance of DateTime
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();

//Initializing DateTime Object
dt1 = DateTime.Now.Date; //Initializing with Current Date
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:00:00

//Examples for DateTime Manipulation in .Net
//Example 1 : Adding Minutes to Current Date.
dt1 = dt1.AddMinutes(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:00


//Example 2 : Adding Seconds to DateTime Object., similarly you can add milliseconds
dt1 = dt1.AddSeconds(30.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:30

//Example 3 : Adding Hours to DateTime Object in .Net.
dt1 = dt1.AddHours(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 05:05:30

//Example 4 : Adding Time to DateTime Object.
//You can replace Example 1,2 and 3 by simply adding TimeSpan with your desired
//TimeSpan value.

//Here we are adding 5 Hours, 5 Minutes and 30 Seconds.
dt1 = dt1.Add(new TimeSpan(5,5,30));
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 10:11:00

//Example 5 : Adding Days to DateTime Object in .Net
dt2 = dt1.AddDays(7.0); //Initializing dt2 object with 7 days ahead from
//dt1 DateTime value.
Response.Write(dt2.ToString() + "
");
//Output: 29-06-2007 10:11:00

//Example 6 : Adding Month to DateTime Object
dt2 = dt2.AddMonths(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2007 10:11:00

//Example 7 : Adding Year to DateTime Object
dt2 = dt2.AddYears(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2008 10:11:00


//Examples of Retrieving DateTime object value.
//Example 1 : Get Day value.
int intDay = dt1.Day;
Response.Write(intDay.ToString() + "
");
//Output: 22

//Example 2 : Get Day of Week.
DayOfWeek dow = dt1.DayOfWeek;
Response.Write(dow.ToString() + "
");
//Output: Friday
//How to find whether day of week is sunday or saturday?
if(dow == DayOfWeek.Sunday dow == DayOfWeek.Saturday)
{
//Hurray its weekend.
}

//Example 3 : Get the Day of Year
int intYear = dt1.DayOfYear; //Similarly you can get Year value.
Response.Write(intYear.ToString() + "
");
//Output: 173


//Similarly you can get Hours, Minutes, Seconds, Milliseconds value.



//Conversion of String to DateTime
//Make use of Parse Method of DateTime to "Convert String to DateTime in .Net"
DateTime dt4 = DateTime.Parse("08/06/2007");
DateTime dt5 = DateTime.Parse("10/06/2007");

//Comparing Date
//How to Find whether both dates are equal or Not?
//How to compare two dates in .Net?
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Dates are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToString() + " is Less than " + dt5.ToString() + "
");
}
else
{
Response.Write(dt4.ToString() + " is Greater than "
+ dt5.ToString() + "
");
}
//Output: 08-06-2007 00:00:00 is Less than 10-06-2007 00:00:00
/*Note: You may recieve error: "String was not recognized as a valid
DateTime." This may be occur as in India the DateTime format is followed
as "dd/mm/yyyy" But let say if you are in USA than it follow "mm/dd/yyyy" so here
there is crash situation and so you might recieve above error, so to avoid such
error make sure that user input valid date before you Parse date. */


//Difference between Date
//How to Find difference between two dates in .Net?
//How to Find days difference between two dates in .Net?
//How to subtract one date from another?
TimeSpan tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date

Response.Write("Difference between " + dt4.ToString() + " and " +
dt5.ToString() + " is " + tsDiff.Days.ToString() + " days." + "
");
//Output: Difference between 08-06-2007 00:00:00 and 10-06-2007 00:00:00 is 2 days.


//Similarly you can also find:
//How many hour difference between two dates
//How many seconds difference between two dates
//And so on... by changing tsDiff property value to hours, seconds....
//instead of tsDiff.Days.


//Compare Time
//How to Find whether both Time are equal or Not?
//How to compare Time in .Net?
dt4 = DateTime.Parse("4:30 AM");
dt5 = DateTime.Parse("7:30 PM");
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Times are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToShortTimeString() + " is Less than " + dt5.ToShortTimeString() + "
");
}
else
{
Response.Write(dt4.ToShortTimeString() + " is Greater than "
+ dt5.ToShortTimeString() + "
");
}
//Output: 04:30:00 is Less than 19:30:00


//Difference between Time
//How to Find difference between two Time value in .Net?
//How to Find Hours difference between two Time in .Net?
//How to subtract one Time from another?
//How to find elapsed Time between Two Time value in .Net?
tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " + dt5.ToString() + " is " + tsDiff.Hours.ToString() + " Hours." + "
");
//Output: Difference between 22-06-2007 04:30:00 and 22-06-2007 19:30:00 is 15 Hours.


//More on DateTime
//How many days in a given month in .Net?
int intDaysInMonth = DateTime.DaysInMonth(2007, 6); //Pass valid year, and month
Response.Write(intDaysInMonth.ToString() + "
");
//Output: 30

//How to find whether given year is Leap year or not in .Net?
Response.Write( DateTime.IsLeapYear(2007)); //Pass valid year
//Output: False

//How to find current date and time?
Response.Write("Current Date and Time: " + DateTime.Now + "
");
//Output: Current Date and Time: 22-06-2007 11:31:04

//How to find current date?
Response.Write("Current Date: " + DateTime.Today + "
");
//Output: Current Date: 22-06-2007 00:00:00

Read Users' Comments (0)

Important Interview Questions

Explain Managed Environment :

Code that operates within the CLR is called managed code. Managed code benefits from the services that the CLR offers, including garbage collection, memory management, security, etc.
Explain Unmanaged Environment :

Code that does not operate within the CLR is called unmanaged code. Unmanaged code does not get benefits offered by CLR including garbage collection, memory management, security, etc. Eg. COM components are unmanaged code.

ArrayList Concept in .Net


Provides a collection similar to an array, but that grows dynamically as

the number of elements change.

Example

static void Main()
{
ArrayList list = new ArrayList();
list.Add(11);
list.Add(22);
list.Add(33);
foreach(int num in list)
{
Console.WriteLine(num);
}
}

Output
11
22
33

Stack Concept in .Net


A collection that works on the Last In First Out (LIFO) principle,

i.e., the last item inserted is the first item removed from the collection.
Push - To add element and
Pop – To Remove element

Example

using System;
using System.Collections;

class Test
{
static void Main()
{
Stack stack = new Stack();
stack.Push(2);
stack.Push(4);
stack.Push(6);

while(stack.Count != 0)
{
Console.WriteLine(stack.Pop());
}
}
}

Output

6
4
2

Queue Concept in .Net


A collection that works on the First In First Out (FIFO) principle, i.e.,

the first item inserted is the first item removed from the collection.
Enqueue - To add element and Dequeue – To Remove element
Example:


static void Main()
{
Queue queue = new Queue();
queue.Enqueue(2);
queue.Enqueue(4);
queue.Enqueue(6);

while(queue.Count != 0)
{
Console.WriteLine(queue.Dequeue());
}
}


Output
2
4
6

Hashtable Concept in .Net

Provides a collection of key-value pairs that are organized

based on the hash code of the key.

Example:
static void Main()
{
Hashtable ht = new Hashtable(20);
ht.Add("ht01", "DotNetGuts");
ht.Add("ht02", "EasyTutor.2ya.com");
ht.Add("ht03", "DailyFreeCode.com");

Console.WriteLine("Printing Keys...");
foreach(string key in ht.Keys)
{
Console.WriteLine(key);
}

Console.WriteLine("\nPrinting Values...");
foreach(string Value in ht.Values)
{
Console.WriteLine(Value);
}

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

Console.WriteLine(ht.ContainsKey("ht01"));
Console.WriteLine(ht.ContainsValue("DailyFreeCode.com"));

Console.WriteLine("\nRemoving element with key = ht02");
ht.Remove("ht02");

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

}


Output

Printing Keys...
ht01
ht02
ht03

Printing Values...
DotNetGuts
EasyTutor.2ya.com
DailyFreeCode.com


Size of Hashtable is 3
True
True
 
Removing element with key = ht02
Size of Hashtable is 2


SortedList Concept in .Net



Provides a collection of key-value pairs where the items are sorted according to the key. The items are accessible by both the keys and the index.
Example:
static void Main()
{
SortedList sl = new SortedList();
sl.Add(18, "Java");
sl.Add(5, "C#");
sl.Add(11, "VB.Net");
sl.Add(1, "C++.Net");

Console.WriteLine("The items in the sorted order are...");
Console.WriteLine("\t Key \t\t Value");
Console.WriteLine("\t === \t\t =====");
for(int i=0; i{
Console.WriteLine("\t {0} \t\t {1}", sl.GetKey(i),
sl.GetByIndex(i));
}
}



Output

Key Value

==
1 C++.Net
5 C#
11 VB.Net
18 Java


for more ex: http://dng-collections.blogspot.com/

Read Users' Comments (0)

Connection Pooling

1. Explain Connection Pooling?


Opening a connection is a database-intensive task. It can be one of the slowest operations that you perform in an ASP.NET page. Furthermore, a database has a limited supply of connections, and each connection requires a certain amount of memory overhead (approximately 40 kilobytes per connection).

If you plan to have hundreds of users hitting your Web site simultaneously, the process of opening a database connection for each user can have a severe impact on the performance of your Web site.

Fortunately, you can safely ignore these bad warnings if you take advantage of connection pooling. When database connections are pooled, a set of connections is kept open so that they can be shared among multiple users. When you request a new connection, an active connection is removed from the pool. When you close the connection, the connection is placed back in the pool.

2. How to implement Connection Pooling?

Connection pooling is enabled for both OleDb and SqlClient connections by default. To take advantage of connection pooling, you must be careful to do two things in your ASP.NET pages.

First, you must be careful to use the same exact connection string whenever you open a database connection. Only those connections opened with the same connection string can be placed in the same connection pool. For this reason you should place your connection string in the web.config file and retrieve it from this file whenever you need to open a connection

Second, you must be careful to explicitly close whatever connection you open as quickly as possible. If you do not explicitly close a connection with the Close() method, the connection is never added back to the connection pool.


stored conveniently inside Web.config file.
  • 1. Database connections.
  • 2. Session States
  • 3. Error Handling (CustomError Page Settings.)
  • 4. Security (Authentication modes)

Read Users' Comments (0)

DataBinder.Eval() Method

DataBinder.Eval() Method

DataBinder.Eval() method saves you from writing complex expressions.

For example, make your datagrid column to template field.
Now, lets understand it various use with different example.


Example1: Concat two datagrid column into one.
Example2: Opening a default Email Program on clicking datagrid column.
Example3: Opening a Pop-up Link on clicking datagrid column.
Example4: Displaying no. of characters to be displayed for a particular datagrid column.
Here displaying 5 characters.
Example5: Displaying Calculation, Calculating UnitPrice into Quantity and displaying Total
Example6: Applying conditional formatting to datagrid cell, assigning different colors to cell depends on its InputValue.

full access :

Read Users' Comments (0)

URL Rewriting

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx

Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

nice artilcle with working code : check it out

more details



Read Users' Comments (1)comments