Friday, February 29, 2008

.NET Web Application Setup & Deployemnt

Step 1: Create an ASP.NET Web application
1. Start Visual Studio .NET or Visual Studio 2005.
2. Use Visual C# .NET or Visual C# 2005 or use Visual Basic .NET or Visual Basic 2005 to create an ASP.NET Web Application project. Name the project Project1.

Note In Visual Studio 2005, create an ASP.NET Web Site project.
3. On the Build menu, click Build Solution.

Step 2: Add a Web Setup project to your solution
1. In Solution Explorer, right-click the Project1 solution, point to Add, and then click Add New Project. The New Project dialog box appears.
2. Under Project Types, click Setup and Deployment Projects.
3. Under Templates, click Web Setup Project.
4. In the Name text box, type WebSetupProject1.
5. In the Location text box, type C:\DeployFolder, and then click OK.

Step 3: Add the Web application files to Your Web Setup project
1. In the File System (WebSetupProject1) window, right-click Web Application Folder, point to Add, and then click File. The Add Files dialog box appears.
2. Locate the C:\Inetpub\wwwroot\Project1 folder.
3. Select all the files that are in the Project1 folder, and then click Open.
4. In the File System (WebSetupProject1) window, expand Web Application Folder.
5. Under Web Application Folder, right-click bin, point to Add, and then click File. The Add Files dialog box appears.
6. Locate the C:\Inetpub\wwwroot\Project1\bin folder.
7. Click the Project1.dll file, and then click Open.

Step 4: Configure the Bootstrapper URL for your Web Setup project
1. In Solution Explorer, right-click WebSetupProject1, and then click Properties. The WebSetupProject1 Property Pages dialog box appears.
2. In the Bootstrapper list box, click Web Bootstrapper. The Web Bootstrapper Settings dialog box appears.
3. In the Setup folder URL text box, type http://devserver/Bootstrap1, and then click OK.

Note devserver is a placeholder for the name of your Web server.
4. In the WebSetupProject1 Property Pages dialog box, click OK.
5. In Solution Explorer, right-click WebSetupProject1, and then click Build.

Step 5: Copy files to the bootstrapping application folder
1. In the C:\Inetpub\Wwwroot folder, create a folder that is named Bootstrap1.
2. Create a virtual directory that is named Bootstrap1, and then map this virtual directory to the C:\Inetpub\wwwroot\Bootstrap1 folder.
3. Copy the following files from the C:\DeployFolder\WebSetupProject1\debug folder to the C:\Inetpub\wwwroot\Bootstrap1 folder: • Setup.Exe
• WebSetupProject1.msi


Step 6: Run your Web Setup project on a remote (deployment) computer
1. Start Microsoft Internet Explorer.
2. Type the following URL in the address bar, and then press ENTER:
http://devserver/Bootstrap1/Setup.Exe
Note devserver is a placeholder for the name of your Web server.
3. In the File Download dialog box, click Open.
4. In the Security Warning dialog box, click Yes.
5. In the WebSetupProject1 dialog box, click Next.
6. Keep WebSetupProject1 in the Virtual directory text box. Click Next.
7. On the Confirm Installation page of the WebSetupProject1 dialog box, click Next.
8. On the Installation Complete page of the WebSetupProject1 dialog box, click Close.
9. Locate the C:\Inetpub\wwwroot\WebSetupProject1 folder.
10. Open the following file in a text editor such as Notepad:• If you are using Visual C# .NET or Visual C# 2005, open the Project1.csproj.webinfo file.
• If you are using Visual Basic .NET or Visual Basic 2005, open the Project1.vbproj.webinfo file.

11. Modify the URLPath element as follows:

Visual C# .NET or Visual C# 2005 code


Visual Basic .NET or Visual Basic 2005 code



12. Save the file as one of the following, depending on your project:• If you are using Visual C# .NET or Visual C# 2005, save the file as WebSetupProject1.csproj.webinfo.
• If you are using Visual Basic .NET or Visual Basic 2005, save the file as WebSetupProject1.vbproj.webinfo.

13. Open the following file, depending on your project:• If you are using Visual C# .NET or Visual C# 2005, open the Project1.csproj file.
• If you are using Visual Basic .NET or Visual Basic 2005, open the Project1.vbproj file.
You may receive the error message that appears in the "Symptoms" section of this article.

Saturday, February 23, 2008

.NET: Generating a Random Number in C#

private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

Copy the above code in your class where you want to use it and call like this:

int returnValue = RandomNumber(5, 20);

.NET: How to create a scrollable DataGrid?

Place the Data Grid with the Div Tag:

.NET: Redirect .NET tracing to a file?

The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.


How to use the TextWriterTraceListener class to redirect Trace output to a file:

Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );
Trace.WriteLine( @"This will be writen to c:\log.txt!" );
Trace.Flush();

SQL-Server: Finding the Nth Highest & Nth Lowest in the SQL:

In the below way we can display any record, it can be fifth or 12th record from top. If we change the order by command to start in ascending order by changing the DESC to ASC ( or removing it , by default it is ASC ) we can get the lowest to highest and get the records from lowest ( last ) mark.

SELECT * FROM `student` where class='Six' ORDER BY mark desc LIMIT 0,1

SQL- Server: Case Statement

Sample for Case Statment:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

.NET : Framework & ASP.NET Questions

1.)Various Providers available in .NET:

1. Odbc Data Provider:System.Data.Odbc
2. OleDb Data Provider:System.Data.OleDb
3. SqlClient Data Provider:System.Data.SqlClient
4. OracleClient Data Provider:System.Data.OracleClient

2.)What is MSIL code?
This is an acronym for Microsft Intermediate Language. In .net code that a developers develops will be complied in to MSIL code by the respective compilers and this code will be targeted towards the CLR which inturn contains JIT Compilers .This MSIL code will be converted in to the machine understandable code by JIT compiler

3.What are various types of assemblies ?
1) shared assembly
2) private assembly
3) satellite assembly

4. What is an assembly and what does manifest consists?
An Assembly is the building block of .net having metadata,mainfest,culture info,ver no. Mainfest cantain the information about the Metadata

5. What is boxing and unboxing?
Box is used to convert Value type to reference type(ie. Object)
Unboxing is to convert Reference typr to Value Type

6. Types of caching?
There are 3 types of caching
1.Page caching
2.Fragment Caching
3.Output Caching

7. What are various authentication mechanisms in ASP.NET?
There are three type of authentication mechanism in asp.net:

1. Form Authentication
2. Window Authentication
3. Passport Authentication

8. What is CTS, CLS and CLR?
Common Type System CTS :A fundamental part of the .NET Framework's Common Language Runtime (CLR), the CTS specifies no particular syntax or keywords, but instead defines a common set of types that can be used with many different language syntaxes.

Common Language Specification (CLS):The Common Language Specification (CLS) describes a set of features that different languages have in common. The CLS includes a subset of the Common Type System (CTS).

The CLR is a multi-language execution environment

9. What are the main advantage in .net?
It is a Language independent, It supports all most all 40 LAngauges including third party languages

10. Where does the dispose method lie and how can it be used to clean up resources?
The dispose method is available in System.IDisposable interface. If you want to provide cleanup mechanism then implement this interface and provide the definition for dispose () method.

11. What is value type and reference type?
In simple words value types are those data types that store there values on stack memory and values are settle down at compile time example are "ENUM" and reference type are those data type that store there values in heap memory and settle down while run time i.e dynamic types examples are strings, class type etc

12. How can u manage sessions?
Session Can be managed in 3 ways using
1.in-proc
2.out-proc and
3. sql server.

13. How can u manage state?
Managing state is done by two ways
1. client side techniques like viewstate, querystring, cookies.
2. Server Side techniques like Application state, Session state.

JavaScript: Check all option for CheckBox Control.

To check all the Checkboxes in the CheckBox Control:
-----------------------------------------------------
function Allcheck()
{
var ln=document.getElementsByTagName('input');
for(i=1;i {
var input_type=ln[i].type;
if(input_type=="checkbox")
{
var Chck_ID=ln[i].id.indexOf("Check_All");
if(Chck_ID!=-1)
{
ln[i].checked=true;
}
}
}
}

Javscript E-Mail Validation:

Function for Email Validation:-
--------------------------------
function EmailValidation(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$");
if(id.match(Reg)==null)
{
alert("Please enter Valid Email-Id !");
fld.value='';
fld.focus();
return false;
}
}
}

Javscript : Function to check Float.

Function to check Float:-
----------------------------
function ChkFloat(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[\-]{0,1}[0-9]{1,}(([\.\,]{0,1}[0-9]{1,})|([0-9]{0,}))$");
if(id.match(Reg)==null)
{
alert("Please Enter Numeric Values !");
fld.value='';
fld.focus();
return false;
}
if(id.indexOf("-")!=-1)
{
alert("Please Enter Positive Values !");
fld.value='';
fld.focus();
return false;
}
}
}

SQL-Server :Example of COALESCE

To bring the Multiple Column in to single column using comma separator:

declare @var varchar(800)
select @var=COALESCE(@var +',', '')+ CAST( AS varchar(250)) from
print @var

SQL-Server : How to Kill the Database Users?

To view the Users who are all using the Database:
--------------------------------------------------
sp_who2

To Kill the User:
------------------

kill 'SPID'
eg: kill 58

SQL-Server : To view the Column Name,type,size in the Table

To view the Columns in the table called "Activity"
-----------------------------------------------------
Type: 1
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Activity'

Type: 2
select fname=col.name, dtype=type.name, col.length, col.status from syscolumns col
inner join sysobjects obj
on col.id = obj.id
inner join systypes type
on col.xtype = type.xtype
where obj.name= 'Activity'
and type.xtype = type.xusertype order by colid



To Get the total number of Columns in the Table:
---------------------------------------------------
SELECT Count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Activity'

Javascript Validation the CheckBox List:

The below code Validate the CheckBox list whether any one of the items are checked or not.

Name of the CheckBox list is : chkFunctionType

function fnValidate()
{
var flag=false;
var chkListfunction = document.getElementById ("chkFunctionType");
var arrCheckbox= chkListfunction.getElementsByTagName("input");
for(var i=0;i {
if(arrCheckbox[i].checked==true)
{
flag=true;
}
}
if(flag==false)
{
alert('Please select the Function Level');
return false;
}
}

Call this Function in the Button Click.

Javascript: Confirmation Msg

function checkdelete()
{
if(confirm('Are you certain that you want to delete this')==false)
{
return false;
}
}

Call the Function in Button OnClick="return checkdelete();"

JavaScript:Allow only Numerics in TextBox

---------------Method 1



In .aspx Page:



--------------Method 2

function validNum(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[0-9]*\[0-9]$");
if(id.match(Reg)==null)
{
alert("Please Enter Numeric Values !");
fld.value='';
fld.focus();
return false;
}
if(id.indexOf("-")!=-1)
{
alert("Please Enter Positive Values !");
fld.value='';
fld.focus();
return false;
}
}
}

In .aspx.cs Page:

Text Box Name: txtCorpName
txtCorpName.Attributes.Add("OnKeyup", "Javascript:return(validNum(this));");

onbeforeunload Javascript

There are some cases where you might want to instruct the user before he/She is navigating to the next page. That might be a meaningful message like "Are you sure you want to navigate away from the current page?"
Probably end user pressed the X button by mistake and he/she might loose his/her current state

There is onbeforeunload event for the JavaScript that fires when you are navigating away from the current page.
Here is the Code for that.



script type="text/javascript"
function close()
{
event.returnValue = "This will navigate to next page.";
}
script




body onbeforeunload="close()"



Note:
The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

Maxlength checking in Textarea Using Javascript

function maxcheck()
{
var maxval=1000;
var maxtxtlength=window.document.myform.Description.value.length;
if(parseInt(maxtxtlength)>parseInt(maxval))
{
alert("This Description field accept only 1000 characters");
window.document.myform.Description.innerText=window.document.myform.Description.value.substring(0,1000);
return false;
}
}

Accesing Parent Window through Childwindow using Javascript

///////////////////////Accessing Id///////////////////////////
alert(window.opener.document.getElementById("HidString").value)

///////////////////////End Accessing Id///////////////////////////

///////////////////////Accessing Function///////////////////////////
child.aspx
window.opener.LoadEmp(obj)

parent.aspx
function LoadEmp(ob)
{
alert(ob);
}

///////////////////////End Accessing Function///////////////////////////


///////////////////////Refershing Parent Page from Child page////////////

Response.Write("");

Reading and removing Listbox using Javascript

/////////////Reading/////////////////////////////////
var listEmp=document.getElementById("PMEmpname");

for(j=0;j
{
listEmp.options[j].value //Value field
listEmp.options[j].text //Text Field
}

///////////Deleting///////////////////////////////////

for(j=0;j{
listEmp.remove(j);
}

Using Javascript creating control without postback




















Friend Name

Email Id

Delete






/////////////////////////////////Javascript///////////////////////////
///////////////////This is for adding row/////////////////////////////
var rowcount=1;
var checkcount=1;
function fnAddRow()
{
rowcount++;
// var check=validate(); //this is for my page validation
if(check!=false)
{
var objTbl = document.getElementById("Tellafriend1");
var objTbody = objTbl.getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
//txtfriendname///
var friendnameval=document.createElement("td");
var friendnameDel = document.createElement("INPUT")
friendnameDel.setAttribute("type","text");
friendnameDel.setAttribute("name","txtfriendname"+rowcount);
friendnameDel.setAttribute("id","txtfriendname"+rowcount);
friendnameval.appendChild(friendnameDel)
row.appendChild(friendnameval);
//txtfriendname///
//txtfriendemail///
var friendemailval=document.createElement("td");
var friendemailDel = document.createElement("INPUT")
friendemailDel.setAttribute("type","text");
friendemailDel.setAttribute("name","txtfriendemail"+rowcount);
friendemailDel.setAttribute("id","txtfriendemail"+rowcount);
friendemailval.appendChild(friendemailDel)
row.appendChild(friendemailval);
//txtfriendemail///

//checkbox///
var checkval=document.createElement("td");
var ChkDel = document.createElement("INPUT")
ChkDel.setAttribute("type","checkbox");
ChkDel.setAttribute("name","chkDelete"+rowcount);
ChkDel.setAttribute("id","chkDelete"+rowcount);
checkval.appendChild(ChkDel)
row.appendChild(checkval);
//End check box checkbox///
objTbody.appendChild(row);
}
else
{
return false;
}
}
///////////////////End adding row/////////////////////////////

Note:For deleting i am using checkbox...................
///////////////Deleting Row//////////////////////////////////

function fnDelRow()
{
var ChkOption = ""
for(var i=2;i<=rowcount;i++)
{
var ChkCtrl = document.getElementById("chkDelete"+i)

if(ChkCtrl == '[object]')
{
if(ChkCtrl.checked)
{
ChkOption = "1"
delRow(ChkCtrl)
checkcount++;
}
}
}
if(ChkOption == "" && rowcount!=1)
{
alert("Select any one option to delete")
return false;
}
}
function delRow(button)
{
var row = button.parentNode.parentNode;
var tbody = document.getElementById('Tellafriend1').getElementsByTagName('tbody')[0];
tbody.removeChild(row);
}

/////////////////////////////End Deleting row////////////////////////////////

Statemanagement Using C#.Net

State Management is a process of maintaining the state of the control or variable after page postback from server or between pages. In Asp.Net we are having many ways to maintain the state management. Basically it is dividied into server side and client side state management. Depends on the resource that we have to plan. They are as follows....
1. Session state
2. Hidden Variables
3. Query String
4. Cookies
5. ViewState
6. Caching
Out of which session state and caching are server side state management. others are client side state management.
1. Session State

Session State is responsible for maintaining the state of a variable between pages and page postback. There are two types of session state. They are
a. Application state
b. Session state
An object that is instant in application state will be available to the entire application. The lifetime of that instance will be available as long as application exists. Synatax for it is

Application.lock();
Application["Name"] = "Senthil";
Application.unlock();
string strName = Application["Name"].ToString();

and an instance created in session state will be available for that session (i.e browser).


Session["RoleID"] = "ADMIN";
string strRole = Session["RoleID"].ToString();

Session state can stored in three places
a. InProc - same system
b. StateServer - storing values in other server. Use " net start aspnet_state" for configuring the state server.
c. SQLServer - In database - use "aspnet_regsql" for configuring the sql server.


This can be set in web.config




To get more info about state management, set the trace to on





If pageoutput is set to false, then we find the contents in trace.axd file which is available in the root folder.

2. Hidden variables

Hidden controls are for storing few informations and retrieving it when page gets submits. We cannot get one hidden value in another page. The syntax for hidden variables are as follows.


<%=Request.Form("hid")%>

3. QueryString

Easiest way to transfer data between pages is the querystring. But we cannot transfer a bulk of data through it. Basically querystring has two keywords ? and &.


Example

document.frm.action="login.aspx?Name=" & strName & "?Role=ADMIN"
<%= Request.QueryString["Name"] %>

4. Cookies

Cookies are client side and it is used to store few values in the client machine. We cannot create cookies in server side. Many browsers restrict using cookies in the websites. The class that supports cookies in dotnet are HttpCookies.

5. ViewState

ViewState are used to maintain the state of the control. It can be set page wise or control wise. To set it by page wise


<% @ Page EnableviewState="True" %>


For setting viewstate control wise set the viewstate property to true.

The value of the control would be retained once the pages get postback.

6. Caching

Caching too places a part in state management. Its similar to session state but the only difference is we have to set the duration for it.
Caching can be done by page levels or application levels.

Syntax for page level caching[CODE]

<% outputcache duration="10" valuebyParam="none" />[CODE]

Javascript Debugger Enabling

Step 1. Disable Script Debugger - Make this option unchecked in the IE.
function someFunct()
{
Javascript:debugger;alert(window.name)
alert("Mahesh");
}

How to Set Screen width for any kind of resolution?



2) Call the function on load event of body.