Monday, August 10, 2009

PadLeft Function

CREATE FUNCTION dbo.PadLeft

(@String varchar(100),

--Input string to be padded

@Length int,

--Length of final string

@PadChar char(1) --Padding character

) RETURNS varchar(100)

AS

BEGIN

WHILE LEN(@String + 'z') <= @Length

SET @String = @PadChar + @String

RETURN @String

END

GO

Store and retrieve file with SQL Server

// Store file in SQL Server

FileStream objFileStream = new FileStream("[Path of File]", FileMode.Open);
byte[] Data = new byte[objFileStream.Length];
objFileStream.Read(Data, 0, Convert.ToInt32(objFileStream.Length));

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand("Bytes_Insert");
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter("@Data", Data));
objCommand.ExecuteNonQuery();
objConnection.Close();
objFileStream.Close();


// Retrieve file from SQL Server

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand("Bytes_ListAll");
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;

SqlDataAdapter adpt = new SqlDataAdapter(objCommand);
DataSet ds = new DataSet();
adpt.Fill(ds);

byte[] Data = (byte[]) ds.Tables[0].Rows[0]["Data"];
File.WriteAllBytes("[Path to store File]", Data);

PadRight Function

CREATE FUNCTION dbo.PadRight


(@String varchar(100), --Input string to be padded


 @Length int,          --Length of final string


 @PadChar char(1)      --Padding character)


RETURNS varchar(100)


AS


BEGIN
WHILE LEN(@String + 'z') <= @Length


        SET @String = @String + @PadChar


RETURN @String


END

Read Excel file in Asp.Net

using Microsoft.Office.Interop.Excel;

private Excel.Application ExcelObj = null;

// Create Object with File path
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open((Server.MapPath("..//Data") + "\\"
+ fu.FileName), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, true, true);

// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;

// get the first and only worksheet from the collection of worksheets
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);

// Loop through total row count
for (int i = 0; i < worksheet.Rows.Count; i++)
{
// Get value from ranges.
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A" + i.ToString(), "B" + i.ToString());

// In Array, You will get the cell value
System.Array myvalues = (System.Array)range.Cells.Value2;

// By Row, Column
string Value1 = myvalues.GetValue(1, 1) != null ? myvalues.GetValue(1, 1).ToString() : string.Empty;
string Value2 = myvalues.GetValue(1, 2) != null ? myvalues.GetValue(1, 2).ToString() : string.Empty;

}

Read Excel File with out Excel Object
=====================================

string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("") + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
if (con.State == ConnectionState.Open)
{

OleDbDataAdapter adp = new OleDbDataAdapter("Select * From [test$A1:D65536]", con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
}
con.Close()

Create and Export-Import Excel file in Asp.Net

Create and Export-Import Excel file in Asp.Net
=======================================


// This method create an Excel file and export it for download
private void CreateExcelFileandDownload()
{

try
{
// Create a new Excel file.

string[] connectStrings = new string[] {
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\TEMP\\TestExcel2003Output.xls\";Extended Properties=\"Excel 8.0;HDR=Yes;\";",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"C:\\TEMP\\TestExcel2007Output.xlsx\";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;\";"
};

string dropTableStmt = "DROP TABLE [test]";
string createTableStmt = "CREATE TABLE [test] ( [Integer] int, [String] varchar(40), [Double] float, [Date] datetime, [Boolean] bit )";
string insertStmt = "INSERT INTO [test] ([Integer], [String], [Double], [Date], [Boolean]) VALUES ({0}, '{1}', {2}, '{3}', {4})";
object[] data = new object[] {

new object[] { 2628013, "Anderson", 0.617715356, new DateTime( 2008, 5, 5 ), true },

new object[] { 2628015, "Rainaud", 0.64933168, new DateTime( 2007, 4, 10 ), false },

new object[] { 2628017, "Dennis", 0.62140731, new DateTime( 2006, 3, 15 ), true },

new object[] { 2628019, "Schoenster", 0.599058708, new DateTime( 2005, 2, 20 ), false },

new object[] { 2628041, "Ganun", 0.593402527, new DateTime( 2004, 1, 25 ), true }

};

foreach (string connect in connectStrings)
{
OleDbConnection con = new OleDbConnection(connect);
con.Open();
if (con.State == ConnectionState.Open)
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandTimeout = 0;
try
{
// Only need this on runs subsequent to first time
cmd.CommandText = dropTableStmt;
cmd.ExecuteNonQuery();
}
catch
{
// First run will cause exception because table (worksheet) doesn't exist
}

cmd.CommandText = createTableStmt;
cmd.ExecuteNonQuery();
foreach (object[] row in data)
{
cmd.CommandText = String.Format(insertStmt, row[0], row[1], row[2], row[3], row[4]);
cmd.ExecuteNonQuery();
}

cmd.Dispose();
if (con.State == ConnectionState.Open)
con.Close();
con.Dispose();
}
}

// Download Created File

// For Office 2007 format
string FileName = @"C:\TEMP\TestExcel2007Output.xlsx";
// For Office 97 - 2003 format
string FileName2 = @"C:\TEMP\TestExcel2003Output.xls";

Response.Clear();
Response.ClearContent();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Disposition", "attachment; filename=Name.xlsx;");

byte[] buffer = System.IO.File.ReadAllBytes(FileName);

System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);

mem.WriteTo(Response.OutputStream);
Response.End();
}
catch (Exception ex)
{
// throw an exception
}

}

Use Custom paging for DataList, GridView in Asp.Net

Use Custom paging for Datalist, GridView in Asp.Net
=============================================

Suppose your HTML layout is like;
------------------------------------------

// Stylesheet
/* Start Pager 2 style */
.Pager2 { border-collapse:collapse;}
.Pager2 a { color:#0080C0; font-weight:bold; margin:1px; padding:2px 5px; border:1px solid white; text-decoration:none }
.Pager2 a:hover { color:White; font-weight:bold; border:1px #0080C0 solid; background-color:#0080C0 }
.Pager2 span { margin:1px; padding:2px 5px; background-color:#0080C0; color:White; border:1px #0080C0 solid}
/* End Pager 2 style */

// Page HTML layout
<div>
Name : <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" />

<asp:DataList ID="dlCompanylist" RepeatColumns="1" RepeatDirection="Horizontal" runat="server">
<ItemTemplate>
<table width="200px" cellpadding="1" cellspacing="1" style="border-collapse:collapse">
<tr>
<td valign="top" style="width:100px">ID :</td>
<td><%#Eval("ID").ToString() %></td>
</tr>
<tr>
<td valign="top" >Name</td><td><%#Eval("Name").ToString() %>
</td>
</tr>
<tr>
<td valign="top">Date</td>
<td><%#Eval("RegisterDate").ToString() %></td>
</tr>
<tr>
<td colspan="2" style="border-bottom:solid 1px gray"> </td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<br />
<asp:Literal ID="ltPaging" runat="server"></asp:Literal>
</div>

// Javascript Method
<script language="javascript" type="text/javascript">

function next_prev_page(val)
{

location.href = "zzCustomPaging.aspx?page=" + val;

}
</script>

// Code Behind Part
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}

private void BindGrid()
{
Company objCompany = new Company();

objCompany.name = txtName.Text.Trim();
objCompany.status = 3;
objCompany.SortBy = "Name";
objCompany.SortOrder = SortDirection.Ascending;
objCompany.PageNo = Request.QueryString["Page"] != null ? int.Parse(Request.QueryString["Page"].ToString()) - 1 : 0;
objCompany.PageSize = 5;

DataSet dsCompanyList = objCompany.GetCompanyRegisterListAll();

if (dsCompanyList != null && dsCompanyList.Tables[0].Rows.Count > 0)
{
dlCompanylist.DataSource = dsCompanyList.Tables[0];
dlCompanylist.DataBind();

ltPaging.Text = this.Paging(objCompany.PageNo + 1, int.Parse(dsCompanyList.Tables[1].Rows[0][0].ToString()), objCompany.PageSize);
}
}

private string Paging(int Page, int TotalRecords, int PageSize)
{
int PageNo = 0;
string NextPage = "";
string PreviousPage = "";
string Print = "";
string Range = "";
string Pager = "";

int Start = 0;
int StartRange = 0;
int EndRange = 0;

if (TotalRecords > PageSize)
{
double RecordForPaging = Math.Ceiling((Convert.ToDouble(TotalRecords) / Convert.ToDouble(PageSize)));
double RecordPage, v;
int NewNo;

if (RecordForPaging > Math.Floor(RecordForPaging))
{
RecordPage = (Math.Floor(RecordForPaging)) + 1;
}
else
{
RecordPage = RecordForPaging;
}

if (RecordPage <= PageSize)
v = RecordPage;
else
v = 5;

if (Page != 1)
PreviousPage = "<div class='Pager2'><a href=javascript:next_prev_page(" + (Page - 1) + ");>PREVIOUS</a></div>";
else
PreviousPage = "";

if (Page != RecordPage)
NextPage = "<div class='Pager2'><a href=javascript:next_prev_page(" + (Page + 1) + ");>NEXT</a></div>";

Print = "";

if (Page == 1)
{
for (PageNo = 1; PageNo <= v; PageNo++)
{
if (RecordPage >= PageNo)
{
if (PageNo == Page)
{
Print += " <b class='Pager2'><span>" + PageNo + "</span></b>";
}
else
{
Print += " <b class='Pager2'><a href=javascript:next_prev_page(" + PageNo + ");>" + PageNo + "</a></b>";
}
}
}
}
else if (Page <= RecordPage)
{
if (PageNo <= RecordPage)
NewNo = 2;
else
NewNo = Page - 5;

if (PageNo <= RecordPage)
NewNo = Page - 5;

for (PageNo = NewNo; PageNo <= Page + 5; PageNo++)
{
if (PageNo > 0)
{
if (PageNo == Page)
Print += " <b class='Pager2'><span>" + PageNo + "</span></b>";
else
{
if (PageNo <= RecordPage)
Print += " <b class='Pager2'><a href=javascript:next_prev_page(" + PageNo + ");>" + PageNo + "</a></b>";
}
}
}
}

Start = (Page - 1) * PageSize;
StartRange = Start + 1;
EndRange = Start + PageSize;

if (EndRange >= TotalRecords)
EndRange = TotalRecords; //end display
Range = StartRange + "-" + EndRange + " of " + TotalRecords;
Pager = "<table width='100%' border='0' style='border-collapse:collapse' ><tr><TD ALIGN='right' width='20%'><TABLE border='0'><TR>";
Pager += "<td width='70px'>" + PreviousPage + "</td><td NOWRAP width='200px'> <div>" + Print + " </div></td><td NOWRAP width='70px' align='left'>" + NextPage + "</td>";
Pager += "</TR></TABLE></TD><td WIDTH='80%' ><div align='left'>" + Range + "</div></td>";
Pager += "</td></tr></table>";
return Pager;
}

return string.Empty;
}

Use Dynamic stylesheet class for messages in Asp.Net

Hi,

In the web application, some times we need to use a message style for
only one Label, like, suppose if our data has been added successfully, we display
message like 'Records has been added successfully'. So, depend on
system's different situation, we have to display label message with style color
combination.

So, Here you can find the solution. By it, you can display your message
with sytle as per your system's situation.

Just copy and paste the style script and copy C# method in your page.

You can find it here...

<style type="text/css">

.MessageSuccess
{
background: #EFF4EA url(images/icn_successful.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
font-weight:bold;
text-align: left;
padding: 5px 20px 5px 45px;
border-top: 1px solid #1E8B18;
border-bottom: 1px solid #1E8B18;
color:#555555;

}
.MessageInfo
{
background: #FFFFD2 url(images/icn_info.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
text-align: left;
font-weight:bold;
padding: 5px 20px 5px 45px;
border-top: 1px solid #CACA00;
border-bottom: 1px solid #CACA00;
color:#555555;

}
.MessageError
{
background: #FFEAEA url(images/icn_error.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
text-align: left;
font-weight:bold;
padding: 5px 20px 5px 45px;
border-top: 1px solid #FF6F6F;
border-bottom: 1px solid #FF6F6F;
color:#555555;

}
</style>

(Download these images for stylesheet)




<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server" />
</form>

protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = "Records has been Added Successfully.";
this.SetStyle(lblMessage, MessageType.Info);
}

private void SetStyle(Label objLabel, MessageType msgType)
{
if (string.IsNullOrEmpty(objLabel.Text.Trim()))
objLabel.CssClass = "";
else
{
switch (msgType)
{
case MessageType.Error:
objLabel.CssClass = "MessageError";
break;
case MessageType.Info:
objLabel.CssClass = "MessageInfo";
break;
case MessageType.Success:
objLabel.CssClass = "MessageSuccess";
break;
}
}
}

// Define enum in the outer side of your page class.
public enum MessageType
{
Success,
Info,
Error
}

Now, Run your page and check it.

Generate a random alpha numeric string from given length

Generate a random alpha numeric string from given length.
==================================================

/// <summary>

/// Generate a random alpha numeric string from given length.
/// Author : Abhishek Joshi
/// 24 Feb, 2008
/// </summary>
/// <param name="iLength"></param>
/// <returns>Enter output string Length.</returns>
public static string GenerateAlphNumericCode(int iLength)
{
int iZero, iNine, iA, iZ, iCount = 0, iRandNum;
string sRandomString ;

// we'll need random characters, so a Random object
// should probably be created...
Random rRandom = new Random(System.DateTime.Now.Millisecond);
// convert characters into their integer equivalents (their ASCII values)
iZero = (int) '0';
iNine = (int) '9';
iA = (int) 'A';
iZ = (int)'Z';

// initialize our return string for use in the following loop
sRandomString = string.Empty;

// now we loop as many times as is necessary to build the string
// length we want
while (iCount < iLength)
{
// we fetch a random number between our high and low values
iRandNum = rRandom.Next(iZero, iZ);

// here's the cool part: we inspect the value of the random number,
// and if it matches one of the legal values that we've decided upon,
// we convert the number to a character and add it to our string
if (((iRandNum >= iZero) && (iRandNum <= iNine) || (iRandNum >= iA) && (iRandNum <= iZ)))
{
sRandomString = sRandomString + Convert.ToChar(iRandNum);
iCount = iCount + 1;

}
}
// finally, our random character string should be built, so we return it
return sRandomString;
}

How to create Image reflection in Asp.Net

How to create Image reflection in Asp.Net
=======================================

Method :
---------

public Image DrawReflection(Image _Image, Color _BackgroundColor, int _Reflectivity)
{
// Calculate the size of the new image
int height = (int)(_Image.Height + (_Image.Height * ((float)_Reflectivity / 255)));
Bitmap newImage = new Bitmap(_Image.Width, height, PixelFormat.Format24bppRgb);
newImage.SetResolution(_Image.HorizontalResolution, _Image.VerticalResolution);

using (Graphics graphics = Graphics.FromImage(newImage))
{
// Initialize main graphics buffer
graphics.Clear(_BackgroundColor);
graphics.DrawImage(_Image, new Point(0, 0));
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle destinationRectangle = new Rectangle(0, _Image.Size.Height, _Image.Size.Width, _Image.Size.Height);

// Prepare the reflected image
int reflectionHeight = (_Image.Height * _Reflectivity) / 255;
Image reflectedImage = new Bitmap(_Image.Width, reflectionHeight);

// Draw just the reflection on a second graphics buffer
using (Graphics gReflection = Graphics.FromImage(reflectedImage))
{
gReflection.DrawImage(_Image, new Rectangle(0, 0, reflectedImage.Width, reflectedImage.Height),
0, _Image.Height - reflectedImage.Height, reflectedImage.Width, reflectedImage.Height, GraphicsUnit.Pixel);
}
reflectedImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
Rectangle imageRectangle = new Rectangle(destinationRectangle.X, destinationRectangle.Y,
destinationRectangle.Width, (destinationRectangle.Height * _Reflectivity) / 255);

// Draw the image on the original graphics
graphics.DrawImage(reflectedImage, imageRectangle);

// Finish the reflection using a gradiend brush
LinearGradientBrush brush = new LinearGradientBrush(imageRectangle,
Color.FromArgb(255 - _Reflectivity, _BackgroundColor),
_BackgroundColor, 90, false);
graphics.FillRectangle(brush, imageRectangle);
}

return newImage;
}

How to Use It (Testing)
-----------------------------

Response.ContentType = "image/jpeg";

Image objImage = Image.FromFile(Server.MapPath("Image.jpg"));

Image objImage2 = this.DrawReflection(objImage, Color.White, 80);

objImage2.Save(Response.OutputStream, ImageFormat.Jpeg);

Convert a string to Proper Case

Convert a string to Proper Case
===========================

// Use this Namespace
using System.Globalization;

// Code
string myString = "thIS is tHE sAmple tExt to shoW tHIs examPle !!";

TextInfo TI = new CultureInfo("en-US",false).TextInfo;

Response.Write (TI.ToTitleCase( myString ));

Use ICallbackEventHandler in Asp.Net 2.0

Use ICallbackEventHandler in Asp.Net 2.0
==================================

For Example, you have page Layout is like this :

<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY>
<div id="divResult" runat="server">
</div>
<br/>
<input type="button" value="Text ICallBack" onclick="return GetPop()" />

</BODY>
</HTML>

Steps to Implement ICallbackEventHanler:
-------------------------------------------------

1. First define string variable in Common section of your code behind (.cs) file.

string _CallBackString;

2. Inherit ICallbackEventHandler in your page.

public partial class Customize : System.Web.UI.Page, ICallbackEventHandler

3. Now, write this code in your Page_Load() Event

ClientScriptManager cs = Page.ClientScript;

string cbRef = cs.GetCallbackEventReference(this, "arg", "ShowPop", "context");
string cbScript = "function CallPopBack(arg, context){" + cbRef + ";}";
cs.RegisterClientScriptBlock(this.GetType(), "CallPopBack", cbScript, true);

4. Now, Write some javascript code, in your design section of your page.

function GetPop()
{
var justExample = 'Hi..All..';

CallPopBack(justExample)
}
function ShowPop(result, context)
{

var strResult = new String();
strResult = result;

alert(result);
}

4. Now, In your code behind (.cs) file, write code for your EventHandle Method.

public string GetCallbackResult()
{
return _CallBackString;
}

public void RaiseCallbackEvent(string eventArgument)
{
_CallBackString = eventArgument + " " + DateTime.Now.ToShortTimeString();
}

5. Run the page and test this page.

Read-Write a Cookie in Asp.Net

Read-Write a Cookie
==================

Write Cookie
----------------

HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1); // Set the Cookie Expiration Time
Response.Cookies.Add(myCookie);


Read Cookie

---------------
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["Font"] != null)
{
userSettings = Request.Cookies["UserSettings"]["Font"];
}
}

Dynamically change web.config file

Dynamically change web.config file
==============================

Description

// Suppose you want to remove a handler from 'httpHandlers'
// and you want to remove modules from your 'httpModules'
// section of you web.config file..

// Below, this is suppose your web.confile file's sections

<httpHandlers>
<add verb="GET" type="DJ.Blog.FileUpload.UploadProgressHandler, FileUploadLibrary" path="DJUploadProgress.ashx" />
</httpHandlers>
<httpModules>
<add name="DJUpload" type="DJ.Blog.FileUpload.UploadModule, FileUploadLibrary"/>
</httpModules>

Code

// Now, you want to remove both section from you web.config file.

// Using these Namespaces

using System.Configuration;
using System.Web.Configuration;

// Write this code to your page_load() event

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
HttpHandlersSection sec = (HttpHandlersSection) objConfig.GetSection("system.web/httpHandlers");
sec.Handlers.Remove("GET", "DJUploadProgress.ashx");

HttpModulesSection sec2 = (HttpModulesSection)objConfig.GetSection("system.web/httpModules");

sec2.Modules.Remove("DJUpload");

objConfig.Save();

// Your web.cofig is now changed dynamically.

Use Form Based Authentication in Asp.Net

In the Web.Config file
========================
Do not write "--" in your Web.confg file

<--authentication mode="Forms">
<--forms loginurl="admin/Login.aspx" timeout="30" name="MyName" defaulturl="admin/AddMovie.aspx">
<--/authentication >

After the end of <--/web.config> section, start a new

<--location path="admin">
<--system.web>
<--customerrors defaultredirect="errorpage.aspx" mode="On">
<--authorization>
<--deny users="?">
<--/deny>
<--/authorization>
<--/system.web>


In the Login page 'Login' button clicks event
==========================================
objLogin = new Login();

objLogin.UserID = txtUserID.Text;
objLogin.Password = txtPassword.Text;

// Check wheather Admin is Authenticate or not.
if (objLogin.IsAdminAuthenticate())
{
FormsAuthentication.RedirectFromLoginPage(txtPassword.Text, false);
Response.Redirect("AddMovie.aspx");
}
else
{
lblMessage.Text = "Check UserID and Password.";
txtUserID.Focus();

}


}

Asp.Net Interview Question

ASP.NETInterview Questions
=========================



  1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
    inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

  2. What’s the difference between Response.Write() andResponse.Output.Write()?
    Response.Output.Write() allows you to write formatted output.

  3. What methods are fired during the page load?
    Init() - when the page is instantiated
    Load() - when the page is loaded into server memory
    PreRender() - the brief moment before the page is displayed to the user as HTML
    Unload() - when page finishes loading.

  4. When during the page processing cycle is ViewState available?
    After the Init() and before the Page_Load(), or OnLoad() for a control.

  5. What namespace does the Web page belong in the .NET Framework class hierarchy?
    System.Web.UI.Page

  6. Where do you store the information about the user’s locale?
    System.Web.UI.Page.Culture

  7. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
    CodeBehind is relevant to Visual Studio.NET only.

  8. What’s a bubbled event?
    When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

  9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
    Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

  10. What data types do the RangeValidator control support?
    Integer, String, and Date.

  11. Explain the differences between Server-side and Client-side code?
    Server-side code executes on the server. Client-side code executes in the client's browser.

  12. What type of code (server or client) is found in a Code-Behind class?
    The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

  13. Should user input data validation occur server-side or client-side? Why?
    All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

  14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
    Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

  15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
    Valid answers are:
    ·
    A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
    · A DataSet is designed to work without any continuing connection to the original data source.
    · Data in a DataSet is bulk-loaded, rather than being loaded on demand.
    · There's no concept of cursor types in a DataSet.
    · DataSets have no current record pointer You can use For Each loops to move through the data.
    · You can store many edits in a DataSet, and write them to the original data source in a single operation.
    · Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

  16. What is the Global.asax used for?
    The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

  17. What are the Application_Start and Session_Start subroutines used for?
    This is where you can set the specific variables for the Application and Session objects.

  18. Can you explain what inheritance is and an example of when you might use it?
    When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

  19. Whats an assembly?
    Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

  20. Describe the difference between inline and code behind.
    Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

  21. Explain what a diffgram is, and a good use for one?
    The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

  22. Whats MSIL, and why should my developers need an appreciation of it if at all?
    MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

  23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
    The Fill() method.

  24. Can you edit data in the Repeater control?
    No, it just reads the information from its data source.

  25. Which template must you provide, in order to display data in a Repeater control?
    ItemTemplate.

  26. How can you provide an alternating color scheme in a Repeater control?
    Use the AlternatingItemTemplate.

  27. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
    You must set the DataSource property and call the DataBind method.

  28. What base class do all Web Forms inherit from?
    The Page class.

  29. Name two properties common in every validation control?
    ControlToValidate property and Text property.

  30. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
    DataTextField property.

  31. Which control would you use if you needed to make sure the values in two different controls matched?
    CompareValidator control.

  32. How many classes can a single .NET DLL contain?
    It can contain many classes.


Web Service Questions

  1. What is the transport protocol you use to call a Web service?
    SOAP (Simple Object Access Protocol) is the preferred protocol.

  2. True or False: A Web service can only be written in .NET?
    False

  3. What does WSDL stand for?
    Web Services Description Language.

  4. Where on the Internet would you look for Web services?
    http://www.uddi.org

  5. True or False: To test a Web service you must create a Windows application or Web application to consume this service?
    False, the web service comes with a test page and it provides HTTP-GET method to test.


State Management Questions

  1. What is ViewState?
    ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

  2. What is the lifespan for items stored in ViewState?
    Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).

  3. What does the "EnableViewState" property do? Why would I want it on or off?
    It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

  4. What are the different types of Session state management options available with ASP.NET?
    ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

.NET Framework Conceptual Overview

.NET Framework Conceptual Overview
=============================

The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:

*

To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.
*

To provide a code-execution environment that minimizes software deployment and versioning conflicts.
*

To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party.
*

To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.
*

To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications.
*

To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

The .NET Framework has two main components: the common language runtime and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.

The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of third-party runtime hosts.

For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services, both of which are discussed later in this topic.

Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code (similar to Microsoft® ActiveX® controls) possible, but with significant improvements that only managed code can offer, such as semi-trusted execution and isolated file storage.

The following illustration shows the relationship of the common language runtime and the class library to your applications and to the overall system. The illustration also shows how managed code operates within a larger architecture.
.NET Framework in context
Managed code within a larger architecture

The following sections describe the main components and features of the .NET Framework in greater detail.
Features of the Common Language Runtime
==================================

The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime.

With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application.

The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally feature rich.

The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety.

In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references.

The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that language, greatly easing the migration process for existing applications.

While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs.

The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance.

Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft® SQL Server™ and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industry's best enterprise servers that support runtime hosting.
.NET Framework Class Library
=======================

The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.

For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET Framework.

As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition to these common tasks, the class library includes types that support a variety of specialized development scenarios. For example, you can use the .NET Framework to develop the following types of applications and services:

*

Console applications.
*

Windows GUI applications (Windows Forms).
*

ASP.NET applications.
*

XML Web services.
*

Windows services.

For example, the Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI development. If you write an ASP.NET Web Form application, you can use the Web Forms classes.
Client Application Development
========================

Client applications are the closest to a traditional style of application in Windows-based programming. These are the types of applications that display windows or forms on the desktop, enabling a user to perform a task. Client applications include applications such as word processors and spreadsheets, as well as custom business applications such as data-entry tools, reporting tools, and so on. Client applications usually employ windows, menus, buttons, and other GUI elements, and they likely access local resources such as the file system and peripherals such as printers.

Another kind of client application is the traditional ActiveX control (now replaced by the managed Windows Forms control) deployed over the Internet as a Web page. This application is much like other client applications: it is executed natively, has access to local resources, and includes graphical elements.

In the past, developers created such applications using C/C++ in conjunction with the Microsoft Foundation Classes (MFC) or with a rapid application development (RAD) environment such as Microsoft® Visual Basic®. The .NET Framework incorporates aspects of these existing products into a single, consistent development environment that drastically simplifies the development of client applications.

The Windows Forms classes contained in the .NET Framework are designed to be used for GUI development. You can easily create command windows, buttons, menus, toolbars, and other screen elements with the flexibility necessary to accommodate shifting business needs.

For example, the .NET Framework provides simple properties to adjust visual attributes associated with forms. In some cases the underlying operating system does not support changing these attributes directly, and in these cases the .NET Framework automatically recreates the forms. This is one of many ways in which the .NET Framework integrates the developer interface, making coding simpler and more consistent.

Unlike ActiveX controls, Windows Forms controls have semi-trusted access to a user's computer. This means that binary or natively executing code can access some of the resources on the user's system (such as GUI elements and limited file access) without being able to access or compromise other resources. Because of code access security, many applications that once needed to be installed on a user's system can now be deployed through the Web. Your applications can implement the features of a local application while being deployed like a Web page.
Server Application Development
========================

Server-side applications in the managed world are implemented through runtime hosts. Unmanaged applications host the common language runtime, which allows your custom managed code to control the behavior of the server. This model provides you with all the features of the common language runtime and class library while gaining the performance and scalability of the host server.

The following illustration shows a basic network schema with managed code running in different server environments. Servers such as IIS and SQL Server can perform standard operations while your application logic executes through the managed code.
Server-side managed code
Managed server code

ASP.NET is the hosting environment that enables developers to use the .NET Framework to target Web-based applications. However, ASP.NET is more than just a runtime host; it is a complete architecture for developing Web sites and Internet-distributed objects using managed code. Both Web Forms and XML Web services use IIS and ASP.NET as the publishing mechanism for applications, and both have a collection of supporting classes in the .NET Framework.

XML Web services, an important evolution in Web-based technology, are distributed, server-side application components similar to common Web sites. However, unlike Web-based applications, XML Web services components have no UI and are not targeted for browsers such as Internet Explorer and Netscape Navigator. Instead, XML Web services consist of reusable software components designed to be consumed by other applications, such as traditional client applications, Web-based applications, or even other XML Web services. As a result, XML Web services technology is rapidly moving application development and deployment into the highly distributed environment of the Internet.

If you have used earlier versions of ASP technology, you will immediately notice the improvements that ASP.NET and Web Forms offer. For example, you can develop Web Forms pages in any language that supports the .NET Framework. In addition, your code no longer needs to share the same file with your HTTP text (although it can continue to do so if you prefer). Web Forms pages execute in native machine language because, like any other managed application, they take full advantage of the runtime. In contrast, unmanaged ASP pages are always scripted and interpreted. ASP.NET pages are faster, more functional, and easier to develop than unmanaged ASP pages because they interact with the runtime like any managed application.

The .NET Framework also provides a collection of classes and tools to aid in development and consumption of XML Web services applications. XML Web services are built on standards such as SOAP (a remote procedure-call protocol), XML (an extensible data format), and WSDL ( the Web Services Description Language). The .NET Framework is built on these standards to promote interoperability with non-Microsoft solutions.

For example, the Web Services Description Language tool included with the .NET Framework SDK can query an XML Web service published on the Web, parse its WSDL description, and produce C# or Visual Basic source code that your application can use to become a client of the XML Web service. The source code can create classes derived from classes in the class library that handle all the underlying communication using SOAP and XML parsing. Although you can use the class library to consume XML Web services directly, the Web Services Description Language tool and the other tools contained in the SDK facilitate your development efforts with the .NET Framework.

If you develop and publish your own XML Web service, the .NET Framework provides a set of classes that conform to all the underlying communication standards, such as SOAP, WSDL, and XML. Using those classes enables you to focus on the logic of your service, without concerning yourself with the communications infrastructure required by distributed software development.

Finally, like Web Forms pages in the managed environment, your XML Web service will run with the speed of native machine language using the scalable communication of IIS.

Useful Techniques in Asp.Net

1. Finding the particular Data from the Dataset,Its Row Position and Current Page in Grid
====================================================================================
DataSet dsQuoteList = objQuote.GetQuoteBankList();

Giving a constraints to the first column that is the ID primary key like:

dsQuoteList.Tables[0].Constraints.Add("pk", dsQuoteList.Tables[0].Columns[0], true);

Now,

The below code will find the perticular ID int the given dataset and return new Datarow..

DataRow dr = dsQuoteList.Tables[0].Rows.Find("10540");

Now finding the Row position (RowIndex) in the Dataset, like..:

int RowIndx = int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()

Finally, You will get the exact position of particular Data in the Dataset.

In Addition You can also find the Current Page in the Datagrid or GridView after getting Datarow:

int PageSize = 10;

double CurrPage = Math.Ceiling(Convert.ToDouble(int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()) / PageSize ));

Done..

That's it !

2. Find the Exact words from string
==================================

using System.Text;
using System.Text.RegularExpressions;

Write in the Button Click Event :

private void button1_click(object sender, EventArgs e)
{
string strInput = "Hello World I am Here with the new sunrise";
string strOutput = FindFirstWords(strInput, 4);

// Here the result of strOutput variable is : Hello World I am
}

Function to get the Words from string:

private string FindFirstWords(string input, int HowManyFind)
{
string REGEX = @"([\w]+\s+){" + HowManyFind + "}";

StringBuilder output = new StringBuilder();

foreach (Capture capture in Regex.Match(input, REGEX).Captures)
{
output.Append(capture.Value);
}
return output.ToString();
}

3. foreach loop in Enum
==================================

objDataImport = new DataImport();
foreach (string s in Enum.GetNames(typeof(DataImport.eTotalFeature)))
{
objDataImport.CurrentFeature = (DataImport.eTotalFeature)Enum.Parse(typeof(DataImport.eTotalFeature), s);
objDataImport.FetchContent();
}

4. Read line by line from text file in C#
==========================================

string strFile = @"C:\Files\new.txt";

StreamReader objStreamReader = File.OpenText(strFile);

string strGetLine;
while ((strGetLine = objStreamReader.ReadLine()) != null)
{
Response.Write(strGetLine);
}

How to download any file with Asp.Net
=================================

string FileName = Server.MapPath("style.css").ToString();

Response.Clear();
Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=Name.css;");

byte[] buffer = System.IO.File.ReadAllBytes(FileName);

System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);

mem.WriteTo(Response.OutputStream);
Response.End();


Render GridView to Html String
==========================

In many times I have faced a problem when you want to
render html string for GridView Control, but you
probably find error like...

"Control '' of type 'GridView' must be placed inside a form tag with runat=server."

In this case you have to use one method to avoid this error..

public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
// specified ASP.NET server control at run time.

// No code required here.
}

and in the page directives just add this code marked in Bold Text..

String.Format Method (String, Object)

The following code example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.

C#
==

// This code example demonstrates the String.Format() method.
// Formatting for this example uses the "en-US" culture.

using System;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;

public static void Main()
{
// Store the output of the String.Format method in a string.
string s = "";

Console.Clear();

// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
s = String.Format(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
Console.WriteLine(s);

// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
s = String.Format(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal sortable: . . . {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
Console.WriteLine(s);

// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
s = String.Format(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
Console.WriteLine(s);
}
}


This code example produces the following results:
=================================================

Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85

Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal sortable: . . . Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004

Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003

(Y) String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);
(Y) This will output “$1,240.00″ if passed 1243.50. It will output the same
format but in parentheses if the number is negative, and will output
the string “Zero” if the number is zero.

Useful Javascript with Asp.Net

Open Popup Window in the Center of the screen.
=============================================
function OpenPop(ItemID)
{
var LeftPosition = (screen.width) ? (screen.width-505)/2 : 0;
var TopPosition = (screen.height) ? (screen.height-250)/2 : 0;

window.open('Pop_QuoteInfo.aspx?id='+ItemID,'MyTitle','height=250,width=505, top='+ TopPosition +', left='+LeftPosition+', scrollbars=yes, resizable=yes, status=no');
}

Javascript Trim() Function
=========================

function trim(inputString) {
// Removes leading and trailing spaces from the passed string. Also removes
// consecutive spaces and replaces it with one space. If something besides
// a string is passed in (null, custom object, etc.) then return the input.
if (typeof inputString != "string") { return inputString; }
var retValue = inputString;
var ch = retValue.substring(0, 1);
while (ch == " ") { // Check for spaces at the beginning of the string
retValue = retValue.substring(1, retValue.length);
ch = retValue.substring(0, 1);
}
ch = retValue.substring(retValue.length-1, retValue.length);
while (ch == " ") { // Check for spaces at the end of the string
retValue = retValue.substring(0, retValue.length-1);
ch = retValue.substring(retValue.length-1, retValue.length);
}
while (retValue.indexOf(" ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ")+1, retValue.length); // Again, there are two spaces in each of the strings
}
return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

How to set Default Button in Asp.Net
===============================

Just, Simply add this code to your page_load() event in code file.

txtUserID.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnLogin.UniqueID + "').click();return false;}} else {return true}; ");

Enable / Disable Validator Control by Javascript
========================================

function EnableDisableControl()
{
var ctl1 = document.getElementById('RequiredValidator1');

// Disable
ValidatorEnable(ctl1, false);

// Enable
ValidatorEnable(ctl1, true);
}

Set/Get value from Popup page and Parent Page
========================================

Get Value in Popup page from Parent Page
---------------------------------------------------
// Write this Javascript in Popup Page

var ParentIDValue = window.opener.document.getElementById('').value;
alert(ParentIDValue);

Set Value in Parent Page from Popup Page
--------------------------------------------------

// Write this Javascript in Popup Page

window.opener.document.getElementById('').value = "Your Value From Popup Page..";

Use Delegate and Events in Asp.Net

I'm explaining Delegates and Event with the use of UserControl and Form in the Asp.Net Webpage.

Steps for usercontrol
====================

1. First create one user control (Like ucTestDelegate)

2. Declare one Delegate (dont declare it in with in function but declare it in class)

3. Declare one event that uses this delegate (Declare it in class)

4. signature of event and Delegate function must match


// Declare one Delegate with its signature means with its return types and parameters.
public delegate void TestDelegateHandler(object sender, EventArgs e);

//Declare one Event that handle by our Delegate.
public event TestDelegateHandler TestDelegateFunction;

protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
this.lblMessage.Text = "Send Button Pressed";
TestDelegateFunction(sender, e);
}

Steps for Form
===============

1. Drag this usercontrol into page.
2. now Declare one function that has the same name and same Signature as the delegate have.
Example :

private void UcTestDelegate1_TestDelegateFunction(object sender, EventArgs e)
{
lblMessage.Text = " Page Label contains : " + "
" + "Test Delegate Function Calls";
}

3. Now in page load event of page Use the += operator to associate an event with an instance of a delegate that already exists.

protected void Page_Load(object sender, EventArgs e)
{
UcTestDelegate1.TestDelegateFunction +=new ucTestDelegate.TestDelegateHandler(UcTestDelegate1_TestDelegateFunction);
}

4. When you run Form And press send Button First the event of usercontrol calls and then of form. (To see how it calls debug both the events).

Normal string Encrypt and Decrypt

Encrypt and Decrypt string
======================

// Encrypt Method

private string EncryptString(string strSource)
{
Byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strSource);

string encryptedString = Convert.ToBase64String(b);

return encryptedString;
}


// Decrypt Method

private string DecryptString(string strSource)
{
Byte[] b = Convert.FromBase64String(strSource);

string decryptedString = System.Text.ASCIIEncoding.ASCII.GetString(b);

return decryptedString;
}

Encrypt - Decrypt with DES and MD5 Algorithm

Encrypt - Decrypt with DES Algorithm
================================

// Use this Namespace
using System.Security.Cryptography;

// Encrypt Function
public static string Encryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateEncryptor(Key_64, Iv_64), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(value);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}
return string.Empty;
}

// Decrypt Function

public static string Descryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
Byte[] buf = Convert.FromBase64String(value);
MemoryStream ms = new MemoryStream(buf);
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateDecryptor(Key_64, Iv_64), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
return string.Empty;
}


Encrypt with MD5 Algorithm
========================

// Encrypt Function

public static string EncryptWithMD5(string ClearString)
{
System.Text.UnicodeEncoding objUE = new System.Text.UnicodeEncoding();

byte[] bytClearString = objUE.GetBytes(ClearString);

MD5CryptoServiceProvider objProv = new MD5CryptoServiceProvider();

byte[] hash = objProv.ComputeHash(bytClearString);
return Convert.ToBase64String(hash);

}

SQL Server function for Count the Occurrence of Character in the string

SQL Server function for Count the Occurrence of Character in the string
============================================================
-- Author : Milind Kansagara
-- Date : 30 July, 2007
-- Desc : Count the Occurrence of Character in the string
-- Usage : select dbo.GetOccurrence('Abhishek Joshi','a')

CREATE FUNCTION [dbo].[GetOccurrence] ( @pInput VARCHAR(1000), @pSearchChar CHAR(1) )
RETURNS INT
BEGIN

DECLARE @vInputLength INT
DECLARE @vIndex INT
DECLARE @vCount INT

SET @vCount = 0
SET @vIndex = 1
SET @vInputLength = LEN(@pInput)

WHILE @vIndex <= @vInputLength
BEGIN
IF SUBSTRING(@pInput, @vIndex, 1) = @pSearchChar
SET @vCount = @vCount + 1

SET @vIndex = @vIndex + 1
END

RETURN @vCount

END

Use Index and Cursor in SQL Server 2000

Using Index
================
select *from ZIPCodes where StateName = 'New York'

-- Create Index
create nonclustered index idxStateName on ZIPCodes(StateName)
create nonclustered index idxZIPType on ZIPCodes(ZIPType)

-- Use Index
select *from ZIPCodes with(INDEX(idxZIPType)) where ZIPType = 'S'

-- List of Indexes on Perticular Table
exec sp_helpindex 'ps_client_master'

-- Drop Index
drop index ps_client_master.ps_client_master_Index_1

Using Cursors
===============

DECLARE @ClientID char(11)

declare cl CURSOR FOR
select int_id from ps_client_master

open cl

FETCH NEXT FROM cl into @ClientID
while @@FETCH_STATUS = 0
begin
print @ClientID
fetch next from cl into @ClientID
end

close cl
DEALLOCATE cl

Use Custom Paging in Asp.Net With Page Size (Faster Performance)

/*
Author : Milind Kansagara
SP Name : usp_Quoter_ListAll
Date : 15 Feb, 2007
Desc : Select all Quoter's list.

*/
CREATE procedure usp_Quoter_ListAll
(
@SortBy varchar(50)=null,
@SortOrder varchar(5)=null,
@PageNo int=null,
@PageSize int=null
)
as
begin
set nocount on
declare @strSql nvarchar(2000)
declare @strSqlCnt nvarchar(200)

set @strSqlCnt = 'select count(*) from quoters where 1=1 '

if @SortBy is null and @SortOrder is null and @PageNo is null and @PageSize is null
begin
set @strSql = 'select qtnum, name, quotes_posted, mod_pts, blocked, email_address from quoters'
end
else if @SortBy is not null and @SortOrder is not null and @PageNo is null and @PageSize is null
begin
set @strSql = 'select qtnum, name, quotes_posted, mod_pts, blocked, email_address from quoters order by ' + @SortBy + ' ' + @SortOrder
end
else if @SortBy is not null and @SortOrder is not null and @PageNo is not null and @PageSize is not null
begin
set @strSql = 'select top ' + cast(@PageSize as varchar(5) ) + ' qtnum, name, quotes_posted, mod_pts, blocked, email_address from quoters where qtnum not in ( select top ' + cast(@PageNo * @PageSize as varchar(10) ) + ' qtnum from quoters order by ' + @SortBy + ' ' + @SortOrder + ') order by ' + @SortBy + ' ' + @SortOrder
end

exec sp_executesql @strSql
exec sp_executesql @strSqlCnt

end
GO

Some reading before Interview

What are the OOPS concepts?

1) Encapsulation: It is the mechanism that binds together code and
data in manipulates, and keeps both safe from outside interference and
misuse. In short it isolates a particular code and data from all other
codes and data. A well-defined interface controls the access to that
particular code and data.

2) Inheritance: It is the process by which one object acquires the
properties of another object. This supports the hierarchical
classification. Without the use of hierarchies, each object would need
to define all its characteristics explicitly. However, by use of
inheritance, an object need only define those qualities that make it
unique within its class. It can inherit its general attributes from
its parent. A new sub-class inherits all of the attributes of all of
its ancestors.

3) Polymorphism: It is a feature that allows one interface to be used
for general class of actions. The specific action is determined by the
exact nature of the situation. In general polymorphism means "one
interface, multiple methods", This means that it is possible to design
a generic interface to a group of related activities. This helps
reduce complexity by allowing the same interface to be used to specify
a general class of action. It is the compiler's job to select the
specific action (that is, method) as it applies to each situation.

What is the difference between a Struct and a Class?

The struct type is suitable for representing lightweight objects such
as Point, Rectangle, and Color. Although it is possible to represent a
point as a class, a struct is more efficient in some scenarios. For
example, if you declare an array of 1000 Point objects, you will
allocate additional memory for referencing each object. In this case,
the struct is less expensive.
When you create a struct object using the new operator, it gets
created and the appropriate constructor is called. Unlike classes,
structs can be instantiated without using the new operator. If you do
not use new, the fields will remain unassigned and the object cannot
be used until all of the fields are initialized.
It is an error to declare a default (parameterless) constructor for a
struct. A default constructor is always provided to initialize the
struct members to their default values.
It is an error to initialize an instance field in a struct.
There is no inheritance for structs as there is for classes. A struct
cannot inherit from another struct or class, and it cannot be the base
of a class. Structs, however, inherit from the base class Object. A
struct can implement interfaces, and it does that exactly as classes
do.
A struct is a value type, while a class is a reference type.

Value type & reference types difference? Example from .NET. Integer
& struct are value types or reference types in .NET?

Most programming languages provide built-in data types, such as
integers and floating-point numbers, that are copied when they are
passed as arguments (that is, they are passed by value). In the .NET
Framework, these are called value types. The runtime supports two
kinds of value types:
Built-in value types
The .NET Framework defines built-in value types, such as System.Int32
and System.Boolean, which correspond and are identical to primitive
data types used by programming languages.
User-defined value types
Your language will provide ways to define your own value types, which
derive from System.ValueType. If you want to define a type
representing a value that is small, such as a complex number (using
two floating-point numbers), you might choose to define it as a value
type because you can pass the value type efficiently by value. If the
type you are defining would be more efficiently passed by reference,
you should define it as a class instead.
Variables of reference types, referred to as objects, store references
to the actual data. This following are the reference types:
class
interface
delegate
This following are the built-in reference types:
object
string


What is Method Overriding? How to override a function in C#?

Use the override modifier to modify a method, a property, an indexer,
or an event. An override method provides a new implementation of a
member inherited from a base class. The method overridden by an
override declaration is known as the overridden base method. The
overridden base method must have the same signature as the override
method.
You cannot override a non-virtual or static method. The overridden
base method must be virtual, abstract, or override.

Can we call a base class method without creating instance?

Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.


In which cases you use override and new base?

Use the new modifier to explicitly hide a member inherited from a base
class. To hide an inherited member, declare it in the derived class
using the same name, and modify it with the new modifier.


What are Sealed Classes in C#?

The sealed modifier is used to prevent derivation from a class. A
compile-time error occurs if a sealed class is specified as the base
class of another class. (A sealed class cannot also be an abstract
class)

UDDI
(Universal Description, Discovery and Integration)

WSDL
(Web Services Discription Language)

Web Service (Definition)

- The W3C defines a Web service[1] as a software system designed to support interoperable machine-to-machine interaction over a network.

- A Web Service is a software component that is described via WSDL and is capable of being accessed via standard network protocols such as but not limited to SOAP over HTTP.

SOAP (Definition)

- SOAP is a standard for exchanging XML-based messages over a computer network, normally using HTTP. SOAP forms the foundation layer of the web services stack, providing a basic messaging framework that more abstract layers can build on.

.Net code Compilation and Execution

* Source code is converted to Microsoft Intermediate Language and an assembly is created.
* Upon execution of a .NET assembly, its MSIL is passed through the Common Language Runtime's JIT compiler to generate native code. (NGEN compilation eliminates this step at run time.)
* The native code is executed by the computer's processor.

What is XML ?

- XML (Extensible Markup Language) is a W3C initiative that allows information and services to be encoded with meaningful structure and semantics that computers and humans can understand. XML is great for information exchange, and can easily be extended to include user-specified and industry-specified tags.
- XML is a markup language for documents containing structured information.

What is UML ?

UML is a general-purpose modeling language that includes a standardized graphical notation used to create an abstract model of a system.

.Net Remoting Interview Question

# What’s a Windows process?
It’s an application that’s running and had been allocated memory.

# What’s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.

# Explain what relationship is between a Process, Application Domain, and Application?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.

# What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

# What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.


# What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

# What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

# What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

# What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

# What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.


# Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

# What’s SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

# What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

# How do you define the lease of the object?
By implementing ILease interface when writing the class code.

# Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

# How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.

C# Interview Questions

C# Interview Questions
====================

This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.

There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.


General Questions

1. Does C# support multiple-inheritance?
No.

2. Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

3. Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.


4. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

5. What’s the top .NET class that everything is derived from?
System.Object.

6. What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

7. What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

8. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

9. Can you store multiple data types in System.Array?
No.

10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.


11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

12. What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

13. What class is underneath the SortedList class?
A sorted HashTable.

14. Will the finally block get executed if an exception has not occurred?­
Yes.

15. What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.


16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

17. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).


Class Questions


1. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass


2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

4. What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

5. When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.


6. What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

7. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

8. Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.

9. What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate


10. What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

11. What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.



Method and Property Questions


1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.

2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.

3. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.


4. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.

6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.


Events and Delegates



1. What’s a delegate?
A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.


XML Documentation Questions


1. Is XML case-sensitive?
Yes.


2. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.

3. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.


Debugging and Testing Questions


1. What debugging tools come with the .NET SDK?
1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.


2. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.


5. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

6. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

7. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).


8. Can you change the value of a variable while debugging a C# application?
Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.


ADO.NET and Database Questions


1. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.



2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4. Explain ACID rule of thumb for transactions.
A transaction must be:
1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
3. Isolated - no transaction sees the intermediate results of the current transaction).
4. Durable - the values persist if the data had been committed even if the system crashes right after.


5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.

8. What does the Dispose method do with the connection object?
Deletes it from the memory.
To Do: answer better. The current answer is not entirely correct.


9. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.


Assembly Questions


1. How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.


3. What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.

5. What is the smallest unit of execution in .NET?
an Assembly.

6. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.


7. How do you convert a value-type to a reference-type?
Use Boxing.



8.What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

9.What is CAS ?
CAS(Code Access Secutiry)
CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk. How does CAS work? The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)


10. What is Satellite Assemblies ?
Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.


11. Automatic Memory Management ?
Automatic Memory Management: From a programmer's perspective, this is probably the single biggest benefit of the .NET Framework. No, I'm not kidding. Every project I've worked on in my long career of DOS and Windows development has suffered at some point from memory management issues. Proper memory management is hard. Even very good programmers have difficulty with it. It's entirely too easy for a small mistake to cause a program to chew up memory and crash, sometimes bringing the operating system to a screeching halt in the process.

Programmers understand that they're responsible for releasing any memory that they allocate, but they're not very good at actually doing it. In addition, functions that allocate memory as a side effect abound in the Windows API and in the C runtime library. It's nearly impossible for a programmer to know all of the rules. Even when the programmer follows the rules, a small memory leak in a support library can cause big problems if called enough.

The .NET Framework solves the memory management problems by implementing a garbage collector that can keep track of allocated memory references and release the memory when it is no longer referenced. A large part of what makes this possible is the blazing speed of today's processors. When you're running a 2 GHz machine, it's easy to spare a few cycles for memory management. Not that the garbage collector takes a huge number of cycles--it's incredibly efficient.
The garbage collector isn't perfect and it doesn't solve the problem of mis-managing other scarce resources (file handles, for example), but it relieves programmers from having to worry about a huge source of bugs that trips almost everybody up in other programming environments.
On balance, automatic memory management is a huge win in almost every situation.


12.What Language familar to CLR?
Any language that can be compiled into Microsoft Intermediate Language (MSIL) is considered a .NET-compliant language. Following are a few of the popular .NET-compliant languages supported by CLR: APL,COBOL,Component Pascal,Eiffel,Fortran,Haskell,JScript,Mercury,Oberon,Pascal,Perl,Python,Smalltalk,Visual Basic,Visual C#,Visual C++