Saturday, October 1, 2011
Edit XML files using a GridView
Download source code - 2.96 KB
Introduction
This short article shows how to edit XML files using aGridView control. Additionally, the user may create new records using some text fields and a button.The XML document
Let's take a look at the structure of the XML file:<?xml version="1.0" standalone="yes"?>
<Mitarbeiter>
<ma>
<id>1</id>
<name>Florian 1</name>
<phone>345</phone>
</ma>
...
</Mitarbeiter>The document contains some records holding personal data. Each record has an ID, name, and a phone number.The web form
First, we need some controls for the web form. We need aGridView to display, edit, and delete records from the XML file. The GridView will contain two command fields: ShowEditButton and SchowDeleteButton. To create new entries, I will use three TextBox fields for the columns of the record and a Button. Here is the code for the form:<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<br />
<br />
<br />
<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtTel" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" /></div>
</form>
</body>
</html>Page_Load and PageIndexChanging
In thePageLoad event, I have to bind the XML file to the GridView. To do this, I created a routine BindGrid() as I need to bind the GridView multiple times. In the BindGrid method, PhysicalApplicationPath is used to get the complete path to the XML file. Here is the code:Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
BindGrid()
End If
End Sub
Sub BindGrid()
Dim oDs As New DataSet
oDs.ReadXml(Request.PhysicalApplicationPath + "XMLFile.xml")
GridView1.DataSource = oDs
GridView1.DataBind()
End SubNext, I have to create an event handler to implement paging for the GridView. This is as easy as setting the PageIndex for the GridView to e.NewPageIndex.Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) _
Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
BindGrid()
End SubDeleting records
To delete records from the file is easy. I assign theDataSource from the GridView to a DataSet object. Then I delete the record the user has selected using the DeleteButton from the GridView. Lastly, I update the XML file and call BindGrid().Protected Sub GridView1_RowDeleting(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) _
Handles GridView1.RowDeleting
BindGrid()
Dim oDs As DataSet = GridView1.DataSource
oDs.Tables(0).Rows(GridView1.Rows(e.RowIndex).DataItemIndex).Delete()
oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
BindGrid()
End SubUpdating records
Updating records is a little bit more work. First, I need to set theEditIndex for the GridView using e.NewEditIndex and call BindGrid again. This has to be done in the RowEditing event:Protected Sub GridView1_RowEditing(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) _
Handles GridView1.RowEditing
GridView1.EditIndex = e.NewEditIndex
BindGrid()
End SubThen, I implement the RowCancelingEvent. Very simple: I just have to set the EditIndex to -1 and bind the GridView.Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) _
Handles GridView1.RowCancelingEdit
GridView1.EditIndex = -1
BindGrid()
End SubNow I need to create the code for the RowUpdating event. When this event fires, I have to get the changed values for the record from the GridView controls into temporary variables. This is done using a cast (CType) from cells to textboxes. Using the method .Text returns the current value of the control. Maybe, using FindControl is much better. Anyway, here is the code:Protected Sub GridView1_RowUpdating(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
Handles GridView1.RowUpdating
' Get the new values from the GridView controls
Dim i As Integer = GridView1.Rows(e.RowIndex).DataItemIndex
Dim strId As String = CType(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text
Dim strName As String = CType(GridView1.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text
Dim strTel As String = CType(GridView1.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text
GridView1.EditIndex = -1
BindGrid()
' Update the XML file using the new values
Dim oDs As DataSet = GridView1.DataSource
oDs.Tables(0).Rows(i).Item(0) = strId
oDs.Tables(0).Rows(i).Item(1) = strName
oDs.Tables(0).Rows(i).Item(2) = strTel
oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
BindGrid()
End Sub When I get the changed values, I reset the EditIndex to -1 and bind the GridView. Then, I assign the DataSource from the GridView to a DataSet and update the values in the DataSet. Lastly, the new DataSet is written to the XML file.Creating new records
Lastly, I have to create new records. To do this, I use threeTextBoxes and a Button. When the button is clicked, I create a DataSet from the DataSource of the GridView. Next, I call the method Tables(0).NewRow and assign the values to the created DataRow. In the end, I Add the new DataRow to the DataSet and write the XML file using oDs.WriteXml.Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
BindGrid()
Dim oDs As DataSet = GridView1.DataSource
Dim oDr As DataRow = oDs.Tables(0).NewRow
oDr("id") = txtId.Text
oDr("name") = txtName.Text
oDr("phone") = txtTel.Text
oDs.Tables(0).Rows.Add(oDr)
oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
BindGrid()
End SubCreating new records
That's it - storing data in XML files is very easy. It is also great for deployment as we can just copy the file to the desired location. But, a short warning about this solution: it does not support transactions. The last one who stores the file will win!!!2:33 AM by Dilip kakadiya · 0
Crystal Report in ASP.NET
Reporting plays an important role in many information systems. Crystal report supports ASP.NET to design a report and render in ASP.NET page with records.
Introduction:
The purpose of this tutorial is to explore how to create crystal report in ASP.NET applications. Crystal report supports web Application reporting. Therefore ASP.NET has a feature to develop reporting with crystal reports.
Prerequisites:
1. SQL Server 2005
2. Visual studio 2005/2008
3. Crystal report
Before starting to design a report, you need a database which is going to be used by the report. Here I have designed a small database for this demonstration.

The created database name is “HouseRental” with “HouseOwnerInfo” table. There are eight columns in the “HouseOwnerInfo.
Let us design a report for this table, get owners summary report which will be used to pass date parameter to process the report.
Note: The database design is only for demonstration purpose.
Let us start designing the report. For that, there are two standard ways. The first way is we can use the crystal report and second one is we can use the Visual studio.
First open Visual studio 2008 or 2005 and create new web project called “CrystalReportInASPNET”. Then right click the project and select Add New Item from the menu.
Select Crystal Report from the templates list window. When you select crystal report, give a meaningful name to the report. Here I have given “SampleRpt.rpt”. Then click Add button.
After you click the Add button, you will get a welcome window as shown by the following figure.

Keep the Standard report format and click OK button. Then you need to create the database connection to access tables within the database. Once you click OK button, system gives a window to select the connection type as shown below.

This demonstration report is to work with SQL Server 2005 database. So you need to select SQL native client as provider (As above figure shows).
Then click Next button, to continue report creation process. Then you need to assign details of SQL Server and user credential to access the database from the report. Then you need to expand current connection tag, select your database connection then select the relevant table as shown by the following figure.

Then click Next button to continue. There you need to select fields from selected tables to design report as shown by the following figure.

Then click Next button. Now you have done necessary effort and finished the final step. As a result, you will get report like this.

Now you need to add crystal report viewer on the ASP.NET Webpage.
Let us see, how we can add the report viewer on the page, just look at these html tags.
Create a table in form object. Then add a HTML row and a column.
Then place the crystalReportViewer to the column as shown above HTML tag.
If we compile this application, it will give a compiler error “CR doesn’t exist”.
Therefore, you need to register crystal report namespace on the top of the page as shown below.
Note: when you double click on toolbox in the crystalreportviewer Visual studio will do all registration and etc.
Now write few lines to display report on the viewer.
Here we have to write code under the OnPreRender event,I hope you know about ASP.Net event life cycle. Please visit the following links for more information.
1. http://msdn.microsoft.com/en-us/library/ms178472.aspx
2. http://msdn.microsoft.com/en-us/library/ms178473.aspx
The reason for using “PreRender” event is this is the most suitable event for value setting in asp.net, Otherwise we can set in “PageLoad” event too. Here I did not use a button to load report on the viewer, therefore I have used “PreRender” event.
On my code just create a report document object and load report from the path. Here we used the Server. MapPath() method to get absolute path from the report file name.
Then build the web application and run, you will get result like follow.

Result seems cool right!
Note:
When you are trying to deploy in your live server, you may face one problem. That is database login fail to report. To ignore that, best approach is creating dataset schema to your tables, then attach the dataset to report. I hope to discuss this scenario on my next article. Keep your eyes on the http://aspnetvisual.blogspot.com/
Conclusion:
This article discussed about creates report with ASP.NET, and how to setup the CrystalReportViewer on the ASP.NET page.
Introduction:
The purpose of this tutorial is to explore how to create crystal report in ASP.NET applications. Crystal report supports web Application reporting. Therefore ASP.NET has a feature to develop reporting with crystal reports.
Prerequisites:
1. SQL Server 2005
2. Visual studio 2005/2008
3. Crystal report
Before starting to design a report, you need a database which is going to be used by the report. Here I have designed a small database for this demonstration.
The created database name is “HouseRental” with “HouseOwnerInfo” table. There are eight columns in the “HouseOwnerInfo.
Let us design a report for this table, get owners summary report which will be used to pass date parameter to process the report.
Note: The database design is only for demonstration purpose.
Let us start designing the report. For that, there are two standard ways. The first way is we can use the crystal report and second one is we can use the Visual studio.
First open Visual studio 2008 or 2005 and create new web project called “CrystalReportInASPNET”. Then right click the project and select Add New Item from the menu.
Select Crystal Report from the templates list window. When you select crystal report, give a meaningful name to the report. Here I have given “SampleRpt.rpt”. Then click Add button.
After you click the Add button, you will get a welcome window as shown by the following figure.
Keep the Standard report format and click OK button. Then you need to create the database connection to access tables within the database. Once you click OK button, system gives a window to select the connection type as shown below.
This demonstration report is to work with SQL Server 2005 database. So you need to select SQL native client as provider (As above figure shows).
Then click Next button, to continue report creation process. Then you need to assign details of SQL Server and user credential to access the database from the report. Then you need to expand current connection tag, select your database connection then select the relevant table as shown by the following figure.
Then click Next button to continue. There you need to select fields from selected tables to design report as shown by the following figure.
Then click Next button. Now you have done necessary effort and finished the final step. As a result, you will get report like this.
Now you need to add crystal report viewer on the ASP.NET Webpage.
Let us see, how we can add the report viewer on the page, just look at these html tags.
01 | <body> |
02 | <form id="form1" runat="server" style="background:lightgreen;"> |
03 | <table cellpadding="0" cellspacing="0" width="100%"> |
04 | <tr> |
05 | <td> |
06 | <CR:CrystalReportViewer ID="rptviewer" DisplayGroupTree="False" |
07 | runat="server" AutoDataBind="true" /> |
08 | </td> |
09 | </tr> |
10 | </table> |
11 | </form> |
12 | </body> |
Create a table in form object. Then add a HTML row and a column.
Then place the crystalReportViewer to the column as shown above HTML tag.
If we compile this application, it will give a compiler error “CR doesn’t exist”.
Therefore, you need to register crystal report namespace on the top of the page as shown below.
1 | <%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %> |
Note: when you double click on toolbox in the crystalreportviewer Visual studio will do all registration and etc.
Now write few lines to display report on the viewer.
1 | protected override void OnPreRender(EventArgs e) |
2 | { |
3 | // attached our report to viewer and set database login. |
4 | ReportDocument report = new ReportDocument(); |
5 | report.Load(Server.MapPath("SampleRpt.rpt")); |
6 | report.SetDatabaseLogon("username", "pwd", @"server", "database"); |
7 | rptviewer.ReportSource = report; |
8 | } |
Here we have to write code under the OnPreRender event,I hope you know about ASP.Net event life cycle. Please visit the following links for more information.
1. http://msdn.microsoft.com/en-us/library/ms178472.aspx
2. http://msdn.microsoft.com/en-us/library/ms178473.aspx
The reason for using “PreRender” event is this is the most suitable event for value setting in asp.net, Otherwise we can set in “PageLoad” event too. Here I did not use a button to load report on the viewer, therefore I have used “PreRender” event.
On my code just create a report document object and load report from the path. Here we used the Server. MapPath() method to get absolute path from the report file name.
Then build the web application and run, you will get result like follow.
Result seems cool right!
Note:
When you are trying to deploy in your live server, you may face one problem. That is database login fail to report. To ignore that, best approach is creating dataset schema to your tables, then attach the dataset to report. I hope to discuss this scenario on my next article. Keep your eyes on the http://aspnetvisual.blogspot.com/
Conclusion:
This article discussed about creates report with ASP.NET, and how to setup the CrystalReportViewer on the ASP.NET page.
1:59 AM by Dilip kakadiya · 0
Exporting GridView to Excel
In this code snippet, I will show how you can export data from a GridView control to a Microsoft Excel spreadsheet.
The Code
Listing 1: Default.aspx
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<br />
<asp:Button ID="BtnExport" runat="server" OnClick="BtnExport_Click"
Text="Export to Excel" />
</form>Listing 2: Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
private string ConnectionString
{
get { return @"Server=localhost;Database=NorthWind;Trusted_Connection=true"; }
}
protected void BtnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
In the above listing, the GridView control will be populated with the data from the Categories table of the Northwind database. You will have to give the appropriate Server name or IP instead of localhost as server name in the above connection string.
If you use this code and try to export the GridView control, you will see an error message saying that the GridView control must be placed inside the form tags with the runat = server attribute.
This is pretty confusing, since your GridView is already inside the form tags and also contains the runat = server attribute. You can easily resolve this error by adding the following lines.
Listing 3: Overiding VerifyRenderingInServerForm Method
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */}
Yup, that’s it. Now, when you click the button, the GridView control will be exported correctly. It will prompt you either to open the file as it is or to save it elsewhere..
1:46 AM by Dilip kakadiya · 0
ASP.NET's Membership, Roles, and Profile -1
Introduction
There's one thing messageboard websites, eCommerce websites, social network websites, and portal websites share in common: they all provide user accounts. These websites, and many others, allow (or require) visitors to create an account in order to utilize certain functionality. For example, a messageboard website, like ASPMessageboard.com, allows anonymous and authenticated visitors to view and search the posts in the various forums. However, in order to be able to post a new thread or reply to a message a visitor must have an account and must log into the site. Providing user account support for a site involves the same set of steps: creating a database table to store user account information, creating a login page, defining a system by which authenticated users' logged on status is remembered across postbacks, specifying which pages are only available for authenticated users (authorization), creating a page for visitors to create a new user account, creating a page for the site's administrators to manage the user accounts, and so forth. Prior to ASP.NET, developers had to decide how to implement all of these facets on their own. ASP.NET introduced the concept of forms-based authentication, which provided a
FormsAuthentication class to ease signing in and out of a site, as well as a protected authentication ticket to remember users' logged on status across page requests. (See Simple Authentication for an article on implementing authentication with classic ASP; refer to Using Forms Authentication in ASP.NET and Dissecting Forms Authentication for more information on ASP.NET's forms-based authentication capabilities.) Even with forms-based authentication, though, ASP.NET developers are still on the hook for defining and creating the structure for storing user account information, for creating login and logout web pages, for enabling visitors to create new accounts and administrators to manage accounts, and so on. Thankfully ASP.NET version 2.0 has lightened developers' loads by providing the membership system and the security Web controls in ASP.NET 2.0. In a nutshell, membership is an API that provides programmatic access to common user account-related tasks. For example, there are methods to create a new user account, authenticate a user's credentials, delete a user, return all user information in the site, and so on. Furthermore, there are a number of security Web controls built atop this API that make performing common user account tasks as simple as dragging and dropping a control on the page.
In this article series we will be examining the ins and outs of version 2.0's membership, roles, and pofile systems and the various security Web controls. This particular article will examine the basics of membership with a look at configuring and using the built-in
SqlMembershipProvider. As we will see, this particular provider stores user account information in a pre-defined database schema. Read on to learn more!Forms-Based Authentication - A Step in the Right Direction, But Too Small a Step
Prior to ASP.NET, web developers were forced to define all of the authentication- and authorization-related decisions. One challenge was how to remember a user's logged on status across web requests; that is, after a user has successfully entered their username and password in the login, when they visit other pages how does the site remember that the user has already logged in? Another challenge was deciding how to protect pages from unauthorized access; that is, how can a page be configured to only allow a particular set of users, or only allow authenticated users? With classic ASP these challenges were usually solved by using a Session variable to remember that a user had successfully logged in across web requests, and code on each page that checked this Session variable to determine the identity of the user visiting the page and whether or not they had access to visit the page. To help reduce the work needed for implementing user accounts, ASP.NET version 1.0 included support for forms-based authentication as well as the ability to specify authorization rules in the
Web.config file. The forms-based authentication provided a means to securely store an authentication ticket as a cookie in the user's browser to remember the user's logged on status across web requests. The FormsAuthentication class provides methods for working with this authentication ticket - both creating the ticket (logging on) and removing it (logging off). Forms-based authentication aimed to provide a standardized approach for accomplishing two of the common tasks required for implementing user accounts. Unfortunately, forms-based authentication - on its own - still leaves the developer a lot of work. The developer must still decide how to serialize user account information, must still build the login page and write code using the
FormsAuthentication class, must still create a logoff page, a page for creating a new account, a page for managing accounts, and so on. Not only did this require extra work on the developer's end, but also left important design decisions to the developer, decisions that might be made that did not follow best practices in design or security. (For example, a user might store users' passwords as plain-text in the database, rather than hashing or encrypting them. See this article for more information on the benefits of hashing passwords stored in a database.) The idea of ASP.NET version 1.0's forms-based authentication was great, but its implementation fell short. Building On Top of Forms-Based Authentication with ASP.NET 2.0's Membership
Version 2.0 of ASP.NET takes the final step that forms-based authentication in version 1.x didn't - namely, it adds programmatic support for authenticating, adding, creating, deleting, and modifying user account information, along with Web controls for helping with accomplishing these tasks. Forms-based authentication is still alive and well in version 2.0, as well as the authorization settings in
Web.config, and both are used the same way as in version 1.x. What 2.0 adds is the membership API and the security Web controls. The membership API is implemented using the provider model, meaning that while the interface is well-defined, the actual implementation can be customized. The .NET Framework includes the Membership class that contains methods like CreateUser(), GetAllUsers(), ValidateUser(), and others. However, the actual class that is invoked when the API is used through an ASP.NET web application is based on the configuration of the application. You can provide your custom user account logic by creating a class that implements the defined membership API, and then configuring the web application to use your class. Of course you don't need to define a custom class - ASP.NET ships with two built-in membership providers, one that stores user account information in a SQL Server database, and another that uses Active Directory. Therefore, the membership system and security Web controls can be used with one of the built-in providers or, if you already have user data defined in some custom manner, a custom provider can be created so that the custom user store is utilized through the same API and security controls seamlessly. (See A Look at ASP.NET 2.0's Provider Model for more information on the concept behind the provider model; in a future article in this series we'll look at the steps involved in creating a custom membership provider.) SqlMembershipProvider - Storing User Account Data in a SQL Server Database
One of the two membership providers that ship with ASP.NET 2.0 is the
SqlMembershipProvider provider, which uses a SQL Server database to store authentication information. In order to use this provider you need to create the database schema used by the provider. There are two ways to accomplish this: - Use the ASP.NET Website Administration Tool (will create the database schema in a new SQL Server 2005 database file
ASPNETDB.mdf, placed in the application'sApp_Datafolder) - Use the ASP.NET SQL Server Registration Tool (
aspnet_regsql.exe) command-line tool (use this tool to implement the schema in a SQL Server 2000 or 2005 database)
App_Data folder named ASPNETDB.mdf that has the predefined schema. (We'll examine this schema shortly.) You can also use the Website Administration Tool to specify authorization settings. For more on using the Website Administration Tool, see Website Administration Tool Overview, focusing on the Security tab. If you want to store the user account information elsewhere - perhaps in a SQL Server 2000 database, or a SQL Server 2005 database not in the App_Data folder - you'll need to use the ASP.NET SQL Server Registration Tool (aspnet_regsql.exe) tool. This tool has a graphical component or can be used through the command-line. The graphical wizard allows you to specify the location to add the needed tables. For more information on using this tool refer to the technical documentation. | The Effects of the Administration Tool |
|---|
When you use the Website Administration Tool to set the authentication type to "From the internet," it adds the following line to the site's Web.config file: <authentication mode="Forms" /> If you create the schema through the ASP.NET SQL Server Registration Tool, you'll need to manually add this line to the Web.config file (or use the Website Administration Tool). Additionally, if you place the schema in a database other than ASPNETDB.mdf in the App_Data directory, you'll need to customize the membership configuration in the Web.config, specifying the connection string to the database. |
The
SqlMembershipProvider stores user account information in two related tables: aspnet_Users- has a record for each user account, storing the bare essentials. TheUserIdcolumn uniquely identifies each user in the system, and is stored as auniqueidentifier(a GUID).aspnet_Membership- has aUserIdcolumn that ties each record back to a particular record inaspnet_Users. Theaspnet_Membershiptable stores core data associated with every user account:Email,Password, the security question and answer, and so on.
Customizing the SqlMembershipProvider
If you want to use the
SqlMembershipProvider membership provider with the default settings (meaning that the user account information will be stored in the ASPNETDB.mdf SQL Server 2005 database in the App_Data folder), then you do not need to make any changes to Web.config, other than indicating that forms authentication should be used and specifying authorization rules. (These tasks can be done for you by the Website Administration Tool, or manually. The syntax for ASP.NET version 2.0 is the same as it was in version 1.x. For more information on specifying authentication and authorization settings in Web.config refer to Authentication and Authorization and Authorizing Users and Roles.) If, however, you want to use a different database, or want to change some of the membership settings (such as whether or not email addresses must be unique, the minimum password strength, if passwords are saved as plain-text, hashed, or encrypted, whether or not a security question and answer is required, and so on), you must specify the custom settings through a hand-entered block of XML in the Web.config file. (Note: you should always set a hard-coded value for the applicationName setting. See Scott Guthrie's Always set the "applicationName" property when configuring ASP.NET 2.0 Membership and other Providers blog entry for more information.) The following chunk of XML shows how to customize the
SqlMembershipProvider settings. Specifically, this XML in bold shows the <membership> element where the settings are customized. There's also a <connectionString> section that provides the connection string for the database that contains the schema. (Presumably this schema was added to this database using the ASP.NET SQL Registration Tool.) <configuration> |
ASP.NET 2.0 includes a built-in connection string name
LocalSqlServer, which points to the ASPNETDB database in the App_Data folder. If you want to keep using the default ASPNETDB database and only change a few properties, set the connectionStringName to LocalSqlServer. In the
<membership> a new provider is added named CustomizedProvider and made the default membership provider. This custom provider uses the SqlMembershipProvider still, it simply customizes some of the values, setting the connectionStringName to MyDB (as specified in the <connectionStrings> section), the applicationName to ScottsProject, the minRequiredPasswordLength to 5, and minRequiredNonalphanumericCharacters to 0. These are but a few of the customizable SqlMembershipProvider settings. For a complete list see <add> Element for Providers for Membership. Always Set the applicationName Setting |
|---|
You should never use the default Membership settings and, instead, always customize them to provide a static applicationName value. See Always set the "applicationName" property when configuring ASP.NET 2.0 Membership and other Providers for a discussion as to why. |
| Managing Users Through the Website Administration Tool |
|---|
| Once you have configured your ASP.NET website to use the membership system, you can manage your site's users through the ASP.NET Website Administration Tool. Simply go to the Security tab and click on the "Create User" link to create a new user account or "Manage Users" link to edit or delete existing user accounts. You can also active the roles feature from the online Administration Tool, as well as assign users to roles and roles to users. The role functionality is something we will examine in future articles in this series. |
A Brief Overview of the Security Web Controls
ASP.NET 2.0 ships with all of the Web controls from version 1.x along with dozens of new ones. Of the plethora of new server controls, there are seven security Web controls. These seven controls provide a user interface for accomplishing user account-related tasks. Underneath the covers all of these controls use the membership system, meaning that even if you have a custom user store you can still use these controls if you create a custom membership provider (which will be the topic of a future article in this series!). The seven security user controls are:
- Login - presents the standard username/password login UI. By default, when the user clicks the "Login" Button a postback ensues and the control attempts to authenticate the user's supplied credentials by calling the
Membershipclass'sVerifyUser(username, password)method. If the credentials provided are valid, an authentication ticket is created for the user, otherwise an error message is displayed in the control's interface. To take custom steps when a user's credentials are invalid, create an event handler for theLoginErrorevent; to implement your own authentication logic, create an event handler for theAuthenticateevent. The Login control contains a number of properties that can be configured to alter the appearance of the control's user interface. For complete control, use theLayoutTemplate. The following screenshot shows the Login control's default UI: - LoginView - oftentimes on a page you want to display different content dependent on whether the page is being visited by an anonymous user or an authenticated user. For example, when an anonymous user visits the homepage you may want to show the Login Web control. However, when an authenticated user visits the same page you want to show a message like, "Welcome back, username," with a link to logoff.The LoginView control allows for such functionality, containing two templates,
AnonymousTemplateandLoggedInTemplate. Simply place the Web controls and HTML markup you want anonymous users to see in theAnonymousTemplateand controls and markup for authenticated users in theLoggedInTemplate. The LoginView also provides support for displaying different output based on the logged in user's role. - PasswordRecovery - allows a user to receive their existing password or a new password sent to them through their email address on file. If the membership provider stores the password in a hashed format, then "recovering" the password actually creates a new, random password, which is then sent to the user. For passwords store as plain-text or encrypted, the actual, existing password is emailed to the user.
- LoginStatus - this simple control displays a link to the Login page if an anonymous user is visiting the page. If an authenticated user is visiting the page, a Logoff link is shown instead.
- LoginName - this control simply displays the username of the currently logged on user. The currently logged on user's name can also be accessed programmatically using
User.Identity.Name, just as with ASP.NET version 1.x. - CreateUserWizard - along with a page for logging in, every user account-enabled website also needs a page from which visitors can create a new user account. The CreateUserWizard control provides a UI for creating new user accounts. Similar to the Login control, after the user fills in the required fields and clicks the "Create User" button the
Membershipclass'sCreateUser(...)method is invoked. The CreateUserWizard can be customized with templates, as needed. The following screenshot shows the CreateUserWizard control in action: The CreateUserWizard control's layout and inputs can be customized; see Customizing the CreateUserWizard Control for more information. - ChangePassword - this control allows a user to change her password.
Login.aspx and drop a Login control on the page. Voila, you have a login page without writing a single line of markup or code. If you need to customize the appearance or logic used by these controls, you have complete control. The security controls can optionally use templates, meaning that you can specify the exact markup used to render the UI. Furthermore, the security controls expose a rich event model, allowing you to tap into the programmatic processing at various points as needed. The download available at the end of this article contains pages showing how to use a number of these security Web controls; we'll examine these controls in much finer detail in future articles in this series. | Programmatically Using the Membership System |
|---|
The membership system exposes its functionality programmatically through the Membership class, which has methods like GetAllUsers(), CreateUser(), DeleteUser(), and so on. This is the class used by the security Web controls to implement their functionality. You can use this class directly from your ASP.NET pages as well. For example, you can create a page that lists all of the users in the system by binding the results of the Membership.GetAllUsers() method to a GridView. If the built-in security controls aren't cutting the mustard, you can implement your own user interface and logic using the Membership class. See the download at the end of this article for some examples of using this class programmatically. |
Conclusion
Since many websites provide user account support, it makes sense that support for such functionality be included in ASP.NET. With ASP.NET version 1.0, the goal was only half-attained. While forms-based authentication provided a standardized means for maintaining an authentication ticket to remember a user's logged on status across web requests, it did not provide any help in storing user account information or creating the necessary web pages (login, create an account, and so on). With version 2.0, ASP.NET now provides a membership service and security Web controls that complete what was lacking in version 1.x. In this article we looked at the goal of the membership system and one of the built-in membership providers,
SqlMembershipProvider. SqlMembershipProvider stores user account information in a SQL Server database, and can be customized through the web application's Web.config file. Furthermore, we overviewed ASP.NET's security Web controls, which make implementing login pages, create user account pages, and other user account-related user interface elements a walk in the park. Since the security Web controls interface with the underlying membership API, and since that API is customizable thanks to being built using the provider model, the security Web controls can be used against the SqlMembershipProvider or your own custom implementation. The membership system is but one part of the overall user account picture in ASP.NET 2.0. There are also roles and profile systems that allow for role-based authorization and customized user account properties without the need for writing any code or creating any additional database tables. We'll examine membership and the security Web controls in further detail, along with the roles and profile systems, in future articles in this series.
1:35 AM by Dilip kakadiya · 0
TreeView in ASP.NET
Introduction:
The TreeView control is one of the most important controls of ASP.NET controls. It is used to display records in a hierarchical format.
The TreeView control is one of the most important controls of ASP.NET controls. It is used to display records in a hierarchical format.
Figure 1: TreeView control structure
How to use TreeView control: Follow these steps:
Step 1: Open Visual Studio 2008 and drag a TreeView control from the toolbar and drop on page as follows:
Figure 2:
Step 2: Copy this code and paste on your page.
<asp:TreeView ID="CourseTreeView" runat="server" OnSelectedNodeChanged="CourseTreeView_SelectedNodeChanged" ShowLines="true" DataSourceID="XmlDataSource1" ExpandDepth="1" PopulateNodesFromClient="false">
<Nodes>
<asp:TreeNode Text="Puru" PopulateOnDemand="false" Value="-1" />
</Nodes>
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/treenode.xml">
</asp:XmlDataSource>
<Nodes>
<asp:TreeNode Text="Puru" PopulateOnDemand="false" Value="-1" />
</Nodes>
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/treenode.xml">
</asp:XmlDataSource>
Here I am binding the node from a xml file. This is optional. You can bind a TreeView node from a database or fix the node directly within the <node> tab.
How to open a popup upon a click of any node in a TreeView?
I am using a small JavaScript function for popup on click.
<script type="text/javascript" language="javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
alert($get("<%=TextBox1.ClientID %>").value);
}</script>
function EndRequestHandler(sender, args) {
alert($get("<%=TextBox1.ClientID %>").value);
}</script>
The following example demonstrates how to use a TreeView control and how to popup on click of any node.
Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TreeView ID="CourseTreeView" runat="server" OnSelectedNodeChanged="CourseTreeView_SelectedNodeChanged"
ShowLines="true" DataSourceID="XmlDataSource1" ExpandDepth="1" PopulateNodesFromClient="false">
<Nodes>
<asp:TreeNode Text="Puru" PopulateOnDemand="false" Value="-1" />
</Nodes>
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/treenode.xml">
</asp:XmlDataSource>
<span style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</span>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
alert($get("<%=TextBox1.ClientID %>").value);
}
</script>
</form>
</body>
</html>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TreeView ID="CourseTreeView" runat="server" OnSelectedNodeChanged="CourseTreeView_SelectedNodeChanged"
ShowLines="true" DataSourceID="XmlDataSource1" ExpandDepth="1" PopulateNodesFromClient="false">
<Nodes>
<asp:TreeNode Text="Puru" PopulateOnDemand="false" Value="-1" />
</Nodes>
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/treenode.xml">
</asp:XmlDataSource>
<span style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</span>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
alert($get("<%=TextBox1.ClientID %>").value);
}
</script>
</form>
</body>
</html>
protected void CourseTreeView_SelectedNodeChanged(object sender, EventArgs e)
{
TextBox1.Text = CourseTreeView.SelectedNode.Text;
}
{
TextBox1.Text = CourseTreeView.SelectedNode.Text;
}
Output:
Figure 3: Output of TreeView control.
If you click on any tree node, a popup will be shown as follows:
Figure 4: PopUp shown upon click of a tree node.
1:25 AM by Dilip kakadiya · 0
Remove rows with data from existing Excel (.XLS) document
How to remove rows from existing XLS (Excel) document using Bytescout Spreadsheet SDK
This source code describes how to remove rows from existing Excel (XLS) document and save changed document as new document file using Bytescout Spreadsheet lib
Download example source code:DownLoadHow to remove rows from existing XLS (Excel) document using Bytescout Spreadsheet SDK
This source code describes how to remove rows from existing Excel (XLS) document and save changed document as new document file using Bytescout Spreadsheet lib
Modified Excel document (row with Maggie name and full name was removed):
using System;
using System.Collections.Generic;
using System.Text;
using Bytescout.Spreadsheet;
namespace Removing_rows_from_existing_XLS
{
class Program
{
static void Main(string[] args)
{
// Open Spreadsheet
Spreadsheet document = new Spreadsheet("AdvancedReport.xls");
// Get Worksheet
Worksheet worksheet = document.Workbook.Worksheets[0];
// Remove row
worksheet.Rows.Delete(5, 5);
// Save document
document.SaveAs("AdvancedReport1.xls");
// Close Spreadsheet
document.Close();
}
}
}
using System.Collections.Generic;
using System.Text;
using Bytescout.Spreadsheet;
namespace Removing_rows_from_existing_XLS
{
class Program
{
static void Main(string[] args)
{
// Open Spreadsheet
Spreadsheet document = new Spreadsheet("AdvancedReport.xls");
// Get Worksheet
Worksheet worksheet = document.Workbook.Worksheets[0];
// Remove row
worksheet.Rows.Delete(5, 5);
// Save document
document.SaveAs("AdvancedReport1.xls");
// Close Spreadsheet
document.Close();
}
}
}
1:19 AM by Dilip kakadiya · 0
Getting Started with the Silverlight 5 Release Candidate
Introduction
The final release of Silverlight 5 is coming up shortly, but that does not mean that we cannot go ahead and get our feet wet with the recently released bits. The release candidate was announced on September 1st, 2011 and is freely available to download right now. I personally consider this an important release and it adds many improvements including XAML Debugging, Multiple Windows Support, Linked Text Containers, 3D Graphics and much much more.Today, I will show you where to download the bits and highlight several important features of Silverlight 5 that I think business developers would benefit the most from. By the end of this article, you should have enough information to go ahead and get started building your first Silverlight 5 Application.
Before we get started downloading the tools, I wanted to point out some a webinar that I recently did for Silverlight Show titled “Getting Started with Silverlight 5”. Several people have emailed me and found it useful for their learning and I hope you are able to get something out of it as well.
Source Code
The source code to all samples provided in this article and more can be found here.Getting Started
Let’s go ahead and get started by downloading the tools needed to build a Silverlight Application. I would like to point out that before we get started that you can install the beta on top of the final release of Silverlight 4.- Visual Studio 2010 SP1 or Visual Web Developer Express 2010 SP1 is required to develop Silverlight 5 Applications. Visual Studio 2010 SP1 or Visual Web Developer Express 2010 SP1.
- After you have installed VS2010 SP1 or Visual Web Developer Express 2010 SP1 then you will need to download and install the Silverlight 5 Tools for Visual Studio 2010 SP1.
- This download will install all components necessary for Silverlight 5 RC and Microsoft WCF RIA Services V1 SP2 RC development:
- Silverlight 5 RC Developer Runtime
- Silverlight 5 RC SDK (software development kit)
- Update for Visual Studio 2010 Service Pack 1 and Visual Web Developer Express 2010 Service Pack 1 (KB2502836)
- Microsoft WCF RIA Services V1.0 SP2 RC
- You should also install the Expression Blend Preview for Silverlight 5. The current version of Expression Blend 4 will not allow you to make changes to your Silverlight 5 UI.
- I always like to have a local copy of the help documentation on my hard drive in case I need to read it while on a flight or if my internet is down. So, I would recommend downloading the Silverlight 5 SDK CHM Help documentation. It is around ~75MB, but well worth it in those tight situations.
- For reference purposes, the developer runtimes are available here for Windows and Mac OS.
- The WCF RIA Services v1 SP2 RC can be found here but as mentioned earlier it is installed with the Silverlight 5 Tools.
- I found the Silverlight 5 Features list helpful for understanding what is and isn’t included in the release.
- You can also download the Silverlight 5 SDK but it is also installed with the Silverlight 5 Tools.
After Installation
One of the first things you are going to notice after installation is when you create a new Silverlight project in Visual Studio 2010 that you have the following option right after you type a name for your project.
You also have the ability to select Silverlight 3 or 4 from this drop-down. Let’s go ahead and look at a few key features. Don’t worry about the source code to the applications and I will provide a link at the end of the article with everything you need.
XAML Binding Debugging
One of the things that I looked forward to most in this release was the support of XAML Binding Statements Debugging. Let me go ahead and show you a screenshot.
Do you see the breakpoint that I inserted on the HyperlinkButton line? Now before you get all trigger happy you will want to know that you can only insert a breakpoint on a line that has the {Binding } expression.
Let’s just say that you had an error on a Binding expression. You would simply add the breakpoint to the line that wasn’t binding properly and run the application (with the debugger of course) and you would see the following in your locals window:

It is very easy to debug Binding expressions now with that feature. Another great feature is that if you have the Silverlight 5 Beta installed then your Silverlight 4 applications automatically get access to the debugging feature.
Multiple Window Support
Imagine having the ability to spawn multiple windows from an Out-of-Browser application with elevated trust with just a couple of lines of code. Well, you now have that ability with Silverlight 5.
Linked Text Containers
This feature enables the text of a RichTextBlock control to overflow from one into the next. Multiple RichTextBlockOverflows can be chained together to spread text across a layout. Let’s go ahead and take a look at a screenshot of a RichTextBlock with a RichTextBlockOverflow working together.
As you can see from this screenshot, we had a RichTextBlock in the upper left and its content overflowed onto the RichTextBlockOverFlow #1, #2 and #3. You can think of this as something that is similar to a newspaper article. As the browser expands or contracts the content fills the available area.
NOTE: Post-beta, Microsoft changed this to use the non-editable RichTextBlock instead of RichTextBox. So a word of warning, many post-beta demos of this functionality on the web will no longer work. You can view my Silverlight 5 demo page for a working demo of this functionality.
Conclusion
We have downloaded the required tools and became familiar with some of the new features in Silverlight 5 including XAML Debugging, Multiple Windows and Linked Text Containers. The Silverlight 5 Release Candidate actually contains a lot more things that I didn’t have room to cover. I would recommend you to explore P/Invoke which would allow you to do cool things such as detect when a USB drive is inserted into the computer. If you wish to see the source code for the features I showed today as well as other Silverlight 5 features then visit this page. I would also invite you to connect with me on Twitter and subscribe to my blog. Thank you for reading.1:07 AM by Dilip kakadiya · 0
Subscribe to:
Posts (Atom)