Archive for March 10th, 2008

Generating XML from a DataSet.

Monday, March 10th, 2008

Generating XML from a dataset using dataset method and GetXml
To invoke those methods and generating XML from a dataset.  .
Dim adapter As SqlDataAdapter
Dim ds As DataSet
Try
adapter = New SqlDataAdapter(”YourSQLStatement”, “YourConnectionString”)
ds = New DataSet()
adapter.Fill(ds, “myTable”)
Response.Write(ds.GetXml)
Catch exc As SqlException
Response.Write(”SQL Error Occured: ” & exc.ToString)
Catch exc As Exception
Response.Write(”Error Occured: ” & exc.ToString)
Finally
adapter = Nothing
ds = Nothing

End Try

Posted by Mahesh ( Tryangled )

The best way to store the connection string.

Monday, March 10th, 2008

using  web.config file, which holds the application wide settings. Web.config file can also be used to hold the connection string info. Let us see how we can do this.
All you need to do is to place the following file lines in your web.config file.

<configuration>
<appSettings>
<add key=”DSN” value=”Server=moon;database=Store;Trusted_Connection=yes” />
</appSettings>
</configuration>

To retrieve the key called DSN from your ASP .NET page, you need to have the following statement.

Dim dsn As String = ConfigurationSettings.AppSettings(”DSN”)

Posted by Mahesh ( Tryangled )

How to use HttpWebRequest to send POST request to another web server?

Monday, March 10th, 2008

HttpWebRequest class that can be used to send HTTP requests to any server.
Its is important to know where this feature is required. A very good example is if you are using  Paypal  to accept payments for your e-commerce application. It requires that you set up your shopping cart button to submit a POST request with all the required information. Following is an example from Paypal’s developer support web site.
<form name=”_xclick” target=”paypal”
action=”https://www.paypal.com/cgi-bin/webscr” method=”post”>
<input type=”hidden” name=”cmd” value=”_cart”>
<input type=”hidden” name=”business” value=”me@tryangled.com”>
<input type=”hidden” name=”item_name” value=”HTML book”>
<input type=”hidden” name=”amount” value=”24.99″>
<input type=”image” src=”http://www.paypal.com/images/sc-but-01.gif”
border=”0″ name=”submit” alt=”Make payments with PayPal!”>
<input type=”hidden” name=”add” value=”1″>
</form>
We will gather all the required information from the user on a regular ASPX page. And then when user clicks button to submitt information for shopping cart, then we will use HttpWebRequest object to submit the request to target web server.

private void OnPostInfoClick(object sender, System.EventArgs e)
{
string strId = UserId_TextBox.Text;
string strName = Name_TextBox.Text;

ASCIIEncoding encoding=new ASCIIEncoding();
string postData=”userid=”+strId;
postData += (”&username=”+strName);
byte[]  data = encoding.GetBytes(postData);

// Prepare web request…
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(”http://localhost/MyIdentity/Default.aspx”);
myRequest.Method = “POST”;
myRequest.ContentType=”application/x-www-form-urlencoded”;
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}

Posted by Mahesh ( Tryangled )

ASP.NET Page Life Cycle

Monday, March 10th, 2008

The Life Cycle of a page when requested for the first time:
Initializing: During this phase, the server creates an instance of the server control
Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.
PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.
Saving: During this phase, the state information of the control is saved. For example, if a value is set for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser.
Rendering: During this phase, the server creates the corresponding HTML tag for the control.
Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.
Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control.

Posted by Mahesh ( Tryangled )

To Include Multiple .Config Files in ASP.NET Web Application

Monday, March 10th, 2008

Working with Web.Config
Web.config exposes an <appSettings> element that can be used as a place to store application settings like connection strings, file paths, etc. Using the web.config is an ideal method of creating a robust application that can quickly adapt to changes in its environment.
Let us look at a basic web.config which holds our connection string.
<?xml version=”1.0″?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug=”false” strict=”false” explicit=”true” />
</system.web>
<appSettings>
<add key=”myConnInfo” value=”server=_;database=_;user=_;pass=_;” />
</appSettings>
</configuration>

To read the connection setting from the Config file, you have to use a single line of code:
System.Configuration.ConfigurationManager.AppSettings(”ConnectionInfo”)
Multiple Config Files
The appSettings element can contain a file attribute that points to an external file. I will change my web.config file to look like the following:
<?xml version=”1.0″?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug=”false” strict=”false” explicit=”true” />
</system.web>
<appSettings file=”externalSettings.config”/>
</configuration>

Next, we can create the external file “externalSettings.config” and add an appSettings section with our connection information and any other settings that we want to use.

If the external file is present, ASP.Net combines the appSettings values from web.config with those in the external file. If a key/value exists in both files, then ASP.Net will use the setting from the external file.

This feature is useful when one keeps user-specific or environment-specific settings in the external file. It is better to design web.config to contain those settings that are global, while each user setting is contained in an external file. This approach makes it easier to move around global web.config changes.

Posted by Mahesh ( Tryangled )

When and how do I use windows authentication in ASP.NET 2.0?

Monday, March 10th, 2008

Your ASP.NET application should use Windows authentication when your users have Windows accounts that can be authenticated by a server. The accounts can be local Windows accounts or domain accounts.
To use Windows authentication in ASP.NET in conjunction with Integrated Windows authentication in IIS
* Configure the virtual directory on IIS to disable anonymous access and configure it to use Integrated Windows authentication alone (by default anonymous access is enabled).
* Configure your application’s Web.config for Windows authentication (the default)

<authentication mode=”Windows”>

Posted by Mahesh ( Tryangled )

How do I use Forms Authentication with Active Directory?

Monday, March 10th, 2008

Use the built-in ActiveDirectoryMembershipProvider. Use the new login controls to create a forms authentication login page.
To use forms authentication with an Active Directory user store:

1.Configure your application for Forms Authentication in the Web.Config file as follows
<authentication mode=”Forms”>

2.Configure your application to deny access to unauthenticated users in the Web.config file as follows:
<authorization>
<deny users=”?”/>
</authorization>
3.Configure an LDAP connection string in the connectionStrings section of Web.config to point to the Active Directory to be used.
<connectionStrings>
<add name=”ADConnectionString”
connectionString=”LDAP://testdomain.test.com/CN=Users,
DC=testdomain,DC=test,DC=com” />
</connectionStrings>
4.Configure the ActiveDirectoryMembershipProvider in the Web.config file specifying at least the connection string name and optionally the credentials (using connectionUserName and connectionPassword attributes) of an account with permissions to access Active Directory.
Ensure that the defaultProvider attribute is set to the provider configured.
<membership defaultProvider=”MyADMembershipProvider”>
<providers>
<add name=”MyADMembershipProvider”
type=”System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”
connectionStringName=”ADConnectionString”
connectionUsername=”testdomain\administrator”
connectionPassword=”password”/>
</providers>
</membership>

Posted by Mahesh ( Tryangled )

Merging two Datasets into a single Datagrid

Monday, March 10th, 2008

Merge is one of the method of Dataset. The merge feature is basically used in applications where the concept of Master and Transaction table exists.
Pre-conditions for displaying two datasets in a single datagrid.

1) All the columns specified in the datagrid must be present in both datasets.
2) The data type of all columns in the datasets must be the same.
3) The column names should match.
A Merge walthrough.

Assume that we have two tables with the following structure:
Table1                                         Table2
Field1 int                                      Field1 int
Field2 varchar(10)                     Field2 varchar(10)
Field3 varchar(20)                     Field3 varchar(20)

Using batch processing, we will have two tables–master and transaction. Both of these tables will have the same number of columns, same data types, and same field names.
Now, we need a datagrid to display records from the above tables. We assume that we have a datagrid that contains the definition for all columns.
We are mainly going to see the BindGrid method that binds the datasets with the datagrid. We will see how we can bind two datasets with a single datagrid.
The BindGrid method.

The BindGrid method.

Sub BindGrid()
Dim myConnection as New SqlConnection (strConn)
Dim DS1 As DataSet
Dim DS1 As DataSet
Dim MyCommand As SqlDataAdapter
MyCommand = new SqlDataAdapter(”exec s_get_table1″, MyConnection)
DS1 = new DataSet()
MyCommand.Fill(DS1, “MyTable”)
MyCommand = new SqlDataAdapter(”exec s_get_table2″, MyConnection)
DS2 = new DataSet()
MyCommand.Fill(DS2, “MyTable”)

‘Now this code works because the table name for both datasets are the same.
‘Also the data type and column name for both tables are the same.

ds1.merge(ds2)
MyDataGrid.DataSource=DS1.tables(0).DefaultView
MyDataGrid.DataBind()
End Sub

Posted by Mahesh ( Tryangled )

How to use Try..Catch ..Finally in ASP.NET?

Monday, March 10th, 2008

This is a new error handling mechanism in ASP.NET, so as in ASP.NET. Well we have three blocks of code, were each block has it own functionality. The Try…Catch…Finally block of code surrounds the code where an exception might occur. The simple Try statement comes before the block of code, the Catch block of code is where we specify what type of error to look for, and the Finally block of code is always executed and contains cleanup routines for exception situations. Since the catch block is specific to the type of error we want to catch, we will often use multiple Catch blocks in our Try…Catch…Finally structure.
A simple Database operation

Dim mySqlConnection as New SqlConnection (ConnectionString)
Dim mySqlCommand as SqlCommand
Dim strSql as String

strSql = “insert into yourtable (f1, f2) values (’f1′, ‘f2′)”
mySqlCommand = new SqlCommand(strSql, mySqlConnection)

Try
mySqlConnection.Open()
mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
Message.text = “New Forward information added”
Catch SQLexc as sqlexception
Message.text = Message.text + sqlexc.tostring()
Catch exc as exception
if Instr(1, exc.tostring, “duplicate key”) > 0 then
Message.text = Message.text + “Cannot insert duplicate values.”
else
Message.text = Message.text + exc.tostring()
end if
Finally
mySqlConnection.Close()
End Try

Posted by Mahesh ( Tryangled )

What are the different methods that are used during the page load?

Monday, March 10th, 2008

These are the different methods that are used during the page load.
Init() - is used when the page is instantiated
Load()  is used when the page is loaded into server memory
PreRender()  is used to display the brief moment before
the page to the user as HTML
Unload()  is used when the page finishes loading.

Posted by Mahesh ( Tryangled )