With standard pages that aren’t cross-page posting, you would protect your code from this post-back behavior through the use of the Page.IsPostBackproperty as shown here: If Page.IsPostB
Trang 1Cross-Page Posting
The way in which Active Server Pages 2.0/3.0 (also called classic ASP) worked was that values from
forms were usually posted to other pages These pages were usually steps in a process that the end userworked through With the introduction of ASP.NET on the other hand, pages in this environment posted
back results to themselves in a step called a postback One of the biggest requests of Web developers in
the ASP.NET world has been the ability to do postbacks not only to the page from whence the valuesoriginated, but also the ability to do postbacks to other pages within the application This new feature issomething that has been provided with the release of ASP.NET 2.0
Cross-page posting (as it is referred) is an easy functionality to achieve now It gives you the ability topost page values from one page (Page1.aspx) to an entirely different page (Page2.aspx) Normally,when posting to the same page (as with ASP.NET 1.0/1.1), you could capture the postback in a postbackevent as shown here:
If Page.IsPostBack Then
‘ do work hereEnd If
Now, let’s take a look at Page1.aspxand see how you accomplish cross-page posting with ASP.NET 2.0
<%@ Page Language=”VB” %>
<script runat=”server”>
Protected Sub Button1_Click(ByVal sender As Object, _ByVal e As System.EventArgs)
Label1.Text = “Your name is: “ & TextBox1.Text & “<br>” & _
“Your appointment is on: “ & Calendar1.SelectedDate.ToLongDateString()End Sub
What is your name?<br />
<asp:TextBox ID=”TextBox1” Runat=”server”></asp:TextBox>
<br />
<br />
When is your appointment?<br />
<asp:Calendar ID=”Calendar1” Runat=”server”>
</asp:Calendar><br />
<asp:Button ID=”Button1” OnClick=”Button1_Click” Runat=”server”
Text=”Do a PostBack to this Page” />
<br />
<br />
<asp:Button ID=”Button2” Runat=”server”
Text=”Do a PostBack to Another Page” PostBackUrl=”~/page2.aspx” />
<br />
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2to the location of the file that this page should post to In this case, the PostBackUrlattribute states thatthis page should post to Page2.aspx You can see that this is the only thing needed on the Page1.aspx
to cause it to post back to another page As for Button1, you can see that this is a simple button whichwill cause the page to post back to itself This is nothing new as this has been the case even in ASP.NET
1.x You can see the event handler for this postback in the OnClickattribute within the Button1control.Pressing this button will cause the page to post back to itself and to populate the Label1control that is
at the bottom of the page
Clicking on the second button, though, will post to the second page, which is shown here:
“Your appointment is on: “ & _pp_Calendar1.SelectedDate.ToLongDateString()End Sub
Trang 3assigned to the FindControlmethod is the Idvalue of the ASP.NET server control from the originatingpage (in our case, TextBox1and Calendar1) Once you have assigned the values to these controlinstances, you can then start working with the new controls and their values as if they were postedfrom the same page.
You can also expose the server controls and other items as properties from Page1.aspx This is illustratedhere in this partial code sample:
End PropertyPublic ReadOnly Property pp_Calendar1() As CalendarGet
Return Calendar1End Get
End PropertyProtected Sub Button1_Click(ByVal sender As Object, _ByVal e As System.EventArgs)
Label1.Text = “Your name is: “ & TextBox1.Text & “<br>” & _
“Your appointment is on: “ & Calendar1.SelectedDate.ToLongDateString()End Sub
</script>
Once you have exposed the properties you want from Page1.aspx, then you can easily get at theseproperties in the cross-page postback by then using the new PreviousPageTypepage directive This isillustrated here in the following example:
</script>
After your properties on Page1.aspx, you can access them easily by strongly typing the PreviousPageproperty on Page2.aspxby the use of the PreviousPageTypedirective The PreviousPageTypedirective specifies the page the post will come from Using this directive allows you to specifically point
at Page1.aspx This is done using the VirtualPathattribute of the PreviousPageTypedirective TheVirtualPathattribute takes a Stringvalue whose value is the location of the directing page
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 4Once this association has been made, you can then use the PreviousPageproperty and you will seethat the pp_TextBox1and pp_Calendar1properties that were created on Page1.aspxare now present
in Visual Studio 2005’s IntelliSense You will find that working with the PreviousPageproperty is a biteasier and is less error prone than using weak-typing This is shown here in Figure 17-1
Figure 17-1
One thing to be careful of is to guard against browsers hitting a page that is expecting information from
a cross-page post and this action causing errors if the information the second page is expecting isn’tthere Pages that were looking for postback information was something you always had to guardagainst before — even when dealing with ASP.NET pages (1.0/1.1) that performed postbacks to them-selves With standard pages that aren’t cross-page posting, you would protect your code from this post-back behavior through the use of the Page.IsPostBackproperty as shown here:
If Page.IsPostBack Then
‘ code hereEnd If
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 5When cross-page posting, you will want to use the Page.IsCrossPagePostBackproperty.
“Your appointment is on: “ & _PreviousPage.pp_Calendar1.SelectedDate.ToLongDateString()Else
Server.Transfer(“Page1.aspx”)End If
End Sub
</script>
In this example, if someone hits this page without going to Page1.aspxfirst to get cross-posted toPage2.aspx, then the request will be checked to see if the request is a cross-post If it is (checked usingthe Page.IsCrossPagePostBackproperty), then the code is run, otherwise the request is redirected toPage1.aspx
ASP.NET Advanced Compilation
The last chapter, Chapter 16, covered how the compilation process works in ASP.NET You can noticethis compilation process and how it works when you hit one of the ASP.NET pages you have built forthe first time in the fact that it takes a few seconds for the page to be generated This is due to the factthat the ASP.NET application is being compiled into intermediate code when you first hit that page Onething that makes this situation even less enjoyable is that each and every page will have this lag whenthat particular page is first requested
In a page’s first request, ASP.NET compiles the page class into a DLL and then this is written to the disk
of the Web server The great thing about ASP.NET is that on the second request, instead of need to pile the page again, the DLL is accessed instead — making the request for the page far quicker than oth-erwise You will notice this yourself if you hit the refresh button on your browser to re-request the samepage You will notice a new snappiness to the page
com-Due to how the pages are compiled in ASP.NET, whenever you make changes to your pages within yourapplication, the application is recompiled again and each and every page will again have this initial drag
as it is compiled This can be quite a pain if you are working with larger sites and you really can’t affordthis kind of pause to page generation (even if it is only one time)
ASP.NET 2.0 includes a couple of precompilation tools so that you don’t have to experience this cost ofpage-by-page compilation Both of these processes precompile your entire application at once The firstprecompilation option is to invoke precompile.axddirectly in the browser as if it was a page of yourapplication If you are using the Web server that is built into Visual Studio 2005, your request would bestructured in the following format:
http://[host]:[port]/[application name]/precompile.axd
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 6Though if you are using Microsoft’s Internet Information Server, your request would be structured in thefollowing format:
http://[host]/[application name]/precompile.axd
Once run, and if successful, you will be notified in large bold text:
The application was successfully precompiled
If there is an error on any of the pages of your application, you will be notified of this through this pilation process which will make note of the page and line of the error If successful, this precompilationprocess will have gone through each element of your application and will have successfully compiled itall into a DLL, thereby removing the churn you would normally experience hitting each of your pagesfor the first time
com-The other method of precompilation is for when you are going to need to precompile your applicationsthat are meant to be deployed Contained within the NET Framework 2.0, you will find a tool —aspnet_compiler You will find this tool at C:\Windows\Microsoft.NET\Framework\v2.0.[xxxxx]\.This is a command-line tool and you will simply need to navigate the aforementioned location to use it
In the simplest case, you would use the following structure to precompile your ASP.NET application
aspnet_compiler –v [Application Name] –p[Physical Location] [Target]
For an example of using this compiler, let’s suppose that you are compiling an application called Wroxwhich is located at C:\Websites\Wrox For this, you would use the following construction:
aspnet_compiler –v /Wrox –p C:\Websites\Wrox c:\Wrox
If successful, the application will be compiled The output of a successful compilation is shown here inFigure 17-2
Figure 17-2
The nice thing about this compilation process is that it hides your code for you by packaging it into aDLL where it will be quite hidden for casually prying eyes If you look at the target location of the com-pilation process, you will still see the same structure and files as you had before, but if you look at thecontents of the aspx files, you will see the following:
This is a marker file generated by the precompilation tool,And should not be deleted!
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 7If you look at what was compiled by the aspnet_compilertool, you will find a Code.dllin the binfolder This is where all the code from the pages is located To deploy this precompiled application, youwill not only need to move the Code.dllfile, but each folder and placer file which was generated by thecompiler Move everything that was generated by the compiler to the target server and the ASP.NETapplication will be able to run without any concerns.
One important point about this second precompilation process is that it doesn’t precompile each andevery file that is contained within your application The files that are excluded from the precompilationprocess include:
Master Pages
Many Web applications are built so that each of the pages of the application has some similarities Forinstance, there might be a common header that is used on each and every page of your applicationsThere also may be other common page elements including navigation sections, advertisements, footers,and more It really isn’t so common to have your Web pages each have their own unique look and feel tothem What people are looking for in their applications is some kind of commonality to give the end userwhat works through a multipaged application
What is really needed for these types of applications is a way to provide a template that can be used byyour pages — a sort of visual inheritance (as can be done with Windows Forms) With a new feature in
ASP.NET 2.0 called master pages, you can now employ visual inheritance in your Web applications.
The use of master pages means that you are working with a template file (the master page) which has a
.master extension Once a master page is created, you can then take a content page, with an aspx
exten-sion, and make an association between the two files Doing this will allow ASP.NET to take these twofiles and combine them into a single Web page to display in a browser Figure 17-3 shows a diagram ofhow this works
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 8Figure 17-3
Let’s now take a look at how we would make this work by first creating the master page
Creating a Master Page
The first step is to create a template that will end up being our master page You can build a master pageusing any text editor (such as Notepad), but you will find it far easier to use Visual Studio 2005 or VisualWeb Developer, as I will show you here
Start within the Solution Explorer Right-click on the solution and select Add New Item In the Add NewItem dialog, you will find the option to add a master page to the solution This is illustrated here inFigure 17-4
Your master page options are quite similar to that of working with a standard aspx page You can eithercreate master pages to be inline or you can have master pages which utilize the code-behind model Ifyou wish to use the code-behind model, make sure that you have the ‘Place code in separate file’ checkbox checked in the dialog — otherwise leave it blank Creating an inline master page will produce a single.master file Using the code-behind model produces a masterfile in addition to a master.vbor.master.csfile
Master PageMyMaster.master
M
Content PageDefault.aspx
C
Combined PageDefault.aspxMC
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 10The idea is to code the master page as you would any other aspxpage This master page contains asimple table and two areas that are meant for the content pages These areas are defined with the use ofthe ContentPlaceHolderserver control This page contains two ContentPlaceHoldercontrols It will
be only in these two specified areas where content pages will be allowed to interject content into the
dynamically created page (as you will shortly see)
The nice thing about working with master pages is that you don’t only have to work with them in thecode view of the IDE, but Visual Studio 2005 also allows for you to work with them in the design view
as well This is illustrated here in Figure 17-5
You can see that in this view, you can work with the master page by simply dragging and dropping trols onto the design surface just as you would with any typical aspx page
con-Creating the Content Page
Now that there is a master page in your project that you can utilize, the next step is to create a contentpage which will do just that To do this, again right-click on the solution from within the SolutionExplorer of Visual Studio 2005 and select Add New Item This time though, we are going to add a typicalWeb Form to the project Though, before you hit the Add button, be sure that you check the Select aMaster Page check box in the dialog This informs VS2005 that we are going to be building a contentpage that will be associated with a master page Doing this will then pull up a new dialog, which willallow you to select a master page to associate this new file with This is shown here in Figure 17-6
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 11Figure 17-5
Figure 17-6
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 12In this case, if you have been following along with the example, you should only have a single masterpage available in the dialog, though it is possible to have as many different master pages as you wish in
a single project Select the Wrox.masterpage and press the OK button
The page created will have only a single line of code to it:
<%@ Page Language=”VB” MasterPageFile=”~/Wrox.master” Title=”Untitled Page” %>There is quite a bit that is different with this file than a typical aspx page First off, there is none of thedefault HTML code, script tags, and DOCTYPE declarations that are the norm The other change is theaddition of the MasterPageFileattribute in the Pagedirective This new attribute makes the associa-tion to the master page which will be used for this content page In this case, it is the Wrox.masterfilethat we created earlier
Though there isn’t much to show while in the Source view of Visual Studio when looking at a contentpage, the real power of master pages can be seen when you switch to the Design view of the same page.This is shown here in Figure 17-7
Figure 17-7
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 13This view shows you the entire template and the two content areas that this content page is allowed todeal with All the grayed-out areas are off limits and do not allow for any changes from the contentpage — while the lighted areas allow for you to deal with any type of content you wish For instance, notonly can you place raw text in these content areas, but anything that you would normally place into atypical aspx page can also be placed in these content areas as well For an example of this, let’s create asimple form in one of the content areas and place an image in the other This code is shown here:
<%@ Page Language=”VB” MasterPageFile=”~/Wrox.master” Title=”My Content Page” %>
<b>Enter in your name:<br />
<asp:TextBox ID=”TextBox1” Runat=”server”></asp:TextBox>
<asp:Button ID=”Button1” Runat=”server” Text=”Submit” OnClick=”Button1_Click” />
This content page contains two Contentserver controls Each of these Contentserver controls map to aspecific <asp:ContentPlaceHolder>control from the master page This association is made throughthe use of the ContentPlaceHolderIDattribute of the Contentcontrol
<asp:Content ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1”
Runat=”Server”> </asp:Content>
Just like typical aspx pages, you can create any event handlers you might need for your content page.This particular example uses a button-click event for when the end user submits the form Running thisexample would produce the following results as shown in Figure 17-8
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 14Figure 17-8
Declaring the Master Page Application-Wide
As shown in our examples thus far, we have been declaring the master page from the content pagethrough the use of the MasterPageFileattribute of the Pagedirective
<%@ Page Language=”VB” MasterPageFile=”~/Wrox.master” Title=”My Content Page” %>You can apply this attribute to each and every one of your content pages or you can make this declara-tion in the web.configfile of your application as shown here:
<%@ Page Language=”VB” Title=”My Content Page” %>
The nice thing with making the master page declaration in the web.configfile is you don’t have tomake this declaration on any of your solution’s content pages, and if you decide to change the templateand associate all the content pages to a brand new master page, it is a simple change in one spot tochange each and every content page instantaneously
Doing this will have no effect on the regular aspx pages in your solution They will still function as normal.Also, if you have a content page that you wish to associate to a different master page than the one that isspecified in the web.configfile, then you simply need to use the MasterPageFileattribute in the Pagedirective of the page This will override any declaration that you might have in the web.configfile
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 15Providing Default Content in Your Master Page
Earlier, we showed how to use a basic ContentPlaceHoldercontrol In addition to using it as it wasshown, you also create ContentPlaceHoldercontrols that contain default content This is illustrated here:
<asp:ContentPlaceHolder ID=”ContentPlaceHolder1” Runat=”server”>
Here is some default content!
</asp:ContentPlaceHolder>
For default content, you can again use whatever you want, including any other ASP.NET server controls
A content page that uses a master page that contains one of these ContentPlaceHoldercontrols canthen either override the default content — by just specifying content (which overrides the original con-tent declared in the master page) — or just keep the default content contained in the control
Data-Driven Applications
ASP.NET 2.0 provides some unique data access server controls that make it easy for you to get at thedata you need As data for your applications finds itself in more and more types of data stores, it cansometimes be a nightmare to figure out how to get at and aggregate these information sets onto a Webpage in a simple and logical manner ASP.NET data source controls are meant to work with a specifictype of data store by connecting to the data store and performing operations such as Inserts, Updates,and Deletes — all on your behalf The following table details the new data source controls at your disposal
Data Source Control Description
SqlDataSource Enables you to work with any SQL-based database, such as Microsoft
SQL Server or even OracleAccessDataSource Enables you to work with a Microsoft Access file (.mbd)
ObjectDataSource Enables you to work with a business object or a Visual Studio 2005
data componentXmlDataSource Enables you to work with the information from an XML file or even a
dynamic XML source (for example, an RSS feed)SiteMapDataSource Enables you to work with the hierarchical data represented in the site
map file (.sitemap)
ASP.NET itself provides a number of server controls that you can use for data-binding purposes Thatmeans that you can use these data source controls as the underlying data systems for a series of controlswith very little work on your part These data-bound controls in ASP.NET include:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 16The newest and most thought of control in the bunch is the GridViewcontrol This control was duced in ASP.NET 2.0 and makes the DataGridcontrol more or less obsolete The GridViewcontrolallows paging, sorting, and editing with very little work on your part This next section takes a look atusing the GridViewcontrol with SQL Server and allowing for these advanced features.
intro-Using the GridView and SqlDataSource Controls
For an example of using these two controls together to display some information, let’s turn to VisualStudio 2005 Start a new page and drag and drop a GridViewcontrol onto the design surface of thepage Pulling up the smart tag for the control on the design surface, you can click the Auto Format link
to give your GridViewcontrol a better look and feel rather than the default look of the control
Next, drag and drop an SqlDataSourcecontrol onto the design surface This control is a middle-tiercomponent, and therefore, it will appear as a gray box on the design surface The first step is to config-ure the SqlDataSourcecontrol to work with the data we want from our Microsoft SQL Server instance.This is shown in Figure 17-9
Figure 17-9
Working through the configuration process for the SqlDataSourcecontrol, you must choose your dataconnection and then whether you want to store this connection in the web.configfile (shown in Figure17-10) This is highly advisable
Trang 17Figure 17-10
From this configuration process, you also get to choose the table that you are going to work with, andtest out the queries that the wizard will generate For our example, select the Customers table and selectevery row by checking the *check box This is illustrated in Figure 17-11
Once you work through the configuration process, you will then notice that your web.configfile haschanged to now include the connection string
<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”>
<connectionStrings>
<add name=”NorthwindConnectionString”
connectionString=”Server=.;Integrated Security=True;Database=Northwind”providerName=”System.Data.SqlClient” />
Trang 18Figure 17-11
Once you have configured the SqlDataSourcecontrol, the next step is to tie the GridViewcontrol tothis SqlDataSourcecontrol instance This can be done through the GridViewcontrol’s smart tag asshown here in Figure 17-12 You can also enable paging and sorting for the control in the same form
Figure 17-12
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 19The code generated by the wizard (it would also be how you would code it yourself) is shown here:
Trang 20<SelectedRowStyle ForeColor=”White” Font-Bold=”True”
BackColor=”#000099”></SelectedRowStyle>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1” Runat=”server”
SelectCommand=”SELECT * FROM [Customers]”
<%$ ConnectionStrings:NorthwindConnectionString %>to get at the connection string This valuepoints at the settings that are placed inside the web.configfile for those that don’t want to hard-codetheir connection strings directly in the code of their pages If you did want to do this, you would usesomething similar to the following construction:
ConnectionString=”Server=(local);Trusted_Connection=True;Integrated Security=SSPI; Persist Security Info=True;Database=Northwind”
Now looking to the GridView control, you can see how simple it was to add the ability to perform ing and sorting capabilities to the control It was simply a matter of adding the attributes AllowPagingand AllowSortingto the control and setting their values to True(they are set to Falseby default)
pag-<asp:GridView ID=”GridView1” Runat=”server” BorderWidth=”1px”
In the end, your page should look something similar to the following as shown here in Figure 17-13
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 21Figure 17-13
Allowing for Editing and Deleting of Records
with the GridView
Now let’s expand upon the previous example by allowing for the editing and deleting of records that aredisplayed in the GridView If you are using the Visual Studio 2005 SqlDataSourceconfiguration wiz-ard to accomplish these tasks, then you are going to have to take some extra steps beyond what was pre-viously shown in the preceding GridViewexample
Go back to the SqlDataSourcecontrol on the design surface of your Web page and pull up the control’ssmart tag You will find the option to Configure Data Source Select this option to reconfigure theSqlDataSourcecontrol to allow for the editing and deletion of the data from the Customers table ofthe Northwind database
When you come to the screen in the Configure Select Statement dialog (see Figure 17-14), click theAdvanced Options button
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 22Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 23The next step is to go back to the GridViewcontrol’s smart tag and select the Refresh Schema You willalso find check boxes in the smart tag now for editing and deleting rows of data Make sure both of thesecheck boxes are checked This is illustrated in Figure 17-16.
Figure 17-16
Now let’s look at what changed in the code First off, the SqlDataSourcecontrol has now changed toallow for the updating and deletion of data
<asp:SqlDataSource ID=”SqlDataSource1” Runat=”server”
SelectCommand=”SELECT * FROM [Customers]”
= @ContactName, [ContactTitle] = @ContactTitle, [Address] = @Address, [City] =
@City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [Phone] = @Phone, [Fax] = @Fax WHERE [CustomerID] = @original_CustomerID”>
<DeleteParameters>
<asp:Parameter Type=”String” Name=”CustomerID”></asp:Parameter>
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Type=”String” Name=”CompanyName”></asp:Parameter>
<asp:Parameter Type=”String” Name=”ContactName”></asp:Parameter>
<asp:Parameter Type=”String” Name=”ContactTitle”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Address”></asp:Parameter>
<asp:Parameter Type=”String” Name=”City”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Region”></asp:Parameter>
<asp:Parameter Type=”String” Name=”PostalCode”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Country”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Phone”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Fax”></asp:Parameter>
<asp:Parameter Type=”String” Name=”CustomerID”></asp:Parameter>
</UpdateParameters>
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 24<asp:Parameter Type=”String” Name=”CustomerID”></asp:Parameter>
<asp:Parameter Type=”String” Name=”CompanyName”></asp:Parameter>
<asp:Parameter Type=”String” Name=”ContactName”></asp:Parameter>
<asp:Parameter Type=”String” Name=”ContactTitle”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Address”></asp:Parameter>
<asp:Parameter Type=”String” Name=”City”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Region”></asp:Parameter>
<asp:Parameter Type=”String” Name=”PostalCode”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Country”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Phone”></asp:Parameter>
<asp:Parameter Type=”String” Name=”Fax”></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
From this code, you can see that there are now other queries that have been added to the control Usingthe DeleteCommand, InsertCommand, and UpdateCommandattributes of the SqlDataSourcecontrol,these functions can now be performed just as Selectqueries were enabled through the use of theSelectCommandattribute As you can see in the queries, there are a lot of parameters defined withinthem These parameters are then assigned through the <DeleteParameters>, <UpdateParameters>,and <InsertParameters>elements Within each of these subsections, the actual parameters aredefined through the use of the <asp:Parameter>control where you also assign the datatype of theparameter (through the use of the Typeattribute) and the name of the parameter
Besides these changes to the SqlDataSourcecontrol, there is only one small change that has been made
to the GridViewcontrol as shown here:
<asp:BoundField HeaderText=”Fax” DataField=”Fax”
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 25The only change that is needed for the GridViewcontrol is the addition of a new column that willallow for editing and deleting commands to be initiated from This is done through the use of the
<asp:CommandField>control From this control, you can see that we also enabled the Edit and Deletebuttons through a Booleanvalue
Once built and run, your new page will look like the following as shown here in Figure 17-17
Figure 17-17
Don’t Stop There!
This chapter has limited space, so there is only room to go through this one example, but it is important
to realize that there are so many other DataSourcecontrols at your disposal The ObjectDataSource
control is rather powerful for those that wish to enforce a strict n-tier model and separate the data
retrieval logic into an object that the GridViewand other data-bound controls can work with TheXmlDataSourcecontrol is one control that you will most likely find yourself using a lot as more andmore data is getting stored as XML — including dynamic data (such as Web logs via RSS) TheseDataSourcecontrols are fine-tuned for the type of data stores for which they are targeted and you willfind a lot of benefit in exploring their capabilities in detail
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 26People rarely build Web applications that are made up of just a single page instance Instead, applicationsare usually made up of multiple pages that are all related to each other in some fashion Some applica-tions have a workflow on how end users can work from page to page, while other applications have anavigation structure that allows for free roaming throughout Sometimes a navigation structure of a sitecan get rather complex, and managing this complexity is something that can get rather cumbersome
ASP.NET 2.0 includes a way of managing the navigational structure of your Web applications This newsystem, which allows you to completely manage your application’s navigation, allows for you to firstdefine your navigational structure through an XML file and can then be bound to a couple of differentserver controls which are focused on navigation
This makes it rather easy when you have to introduce changes either to the structure of your navigation
or even name changes to pages which are contained within this structure Instead of going from page topage throughout your entire application, changing titles or page destinations, you can now make thesechanges in one place — an XML file — and the changes will be instantaneously reflected throughout yourentire application
The first step in working with the ASP.NET navigation system is to first reflect your navigational structure
in the web.sitemapfile — which is basically the XML file that will contain the complete site structure
For instance, let’s suppose that you want to have the following site structure:
HomeBooksMagazinesU.S MagazinesEuropean MagazinesThis site structure has three levels to it and multiple items in the lowest level With this structure, youcan then reflect this in the web.sitemapfile as follows:
<?xml version=”1.0” encoding=”utf-8” ?>
<siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0” >
<siteMapNode url=”default.aspx” title=”Home” description=”The site homepage”>
<siteMapNode url=”books.aspx” title=”Books”
description=”Books from our catalog” />
<siteMapNode url=”magazines.aspx” title=”Magazines”
description=”Magazines from our catalog”>
<siteMapNode url=”magazines_us.aspx” title=”U.S Magazines”
description=”Magazines from the U.S.” />
<siteMapNode url=”magazines_eur.aspx” title=”European Magazines”
description=”Magazines from Europe” />
Trang 27To create a web.sitemapfile in Visual Studio 2005, get to the Add New Items dialog and you will seethe option of adding a Site Map In this file, you can place the above content To move a level down inthe hierarchy, you would nest <siteMapNode>elements within other <siteMapNode>elements A
<siteMapNode>element can contain a couple of different attributes These attributes are defined in thefollowing table
Attribute Description
Title The titleattribute provides a textual description of the link The String
value used here is the text used for the link
Description The descriptionattribute not only reminds you what the link is for, but is
also used for the ToolTipattribute on the link The ToolTipattribute is theyellow box that shows up next to the link when the end user hovers the cursorover the link for a couple of seconds
Url The urlattribute describes where the file is located in the solution If the file
is in the root directory, simply use the file name, such as default.aspx If thefile is located in a subfolder, be sure to include the folders in the Stringvalueused for this attribute For example, MySubFolder/MyFile.aspx
Roles If ASP.NET security trimming is enabled, you can use the rolesattribute
to define which roles are allowed to view and click the provided link in thenavigation
Using the SiteMapPath Server Control
One of the available server controls that work with a web.sitemapfile is the SiteMapPathcontrol Thiscontrol provides a popular structure which you will find on many Web sites on the Internet Some folks
call this feature breadcrumb navigation, but whatever you call it, you will find it very easy to implement in
ASP.NET
To see an example of this control at work, let’s create a page that would be at the bottom of the site mapstructure So, within the project that contains your web.sitemapfile, create an ASP.NET page namedmagazines_us.aspx On this page, simply drag and drop a SiteMapPathcontrol onto the page Youwill find this control under the Navigation section in the Visual Studio Toolbox This control’s code looks
as follows:
<asp:SiteMapPath ID=”SiteMapPath1” Runat=”server”></asp:SiteMapPath>
What else do you need to do to get this control to work? Well, nothing! Simply build and run the pageand you will then see the following results as shown here in Figure 17-18
From this example, you can see that the SiteMapPathcontrol defines the end user’s place in the cation’s site structure It shows the current page the user is on (U.S Magazines) as well as the two pagesthat are above it in the hierarchy
appli-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 28Figure 17-18
The SiteMapPathcontrol requires no DataSourcecontrol, as it will automatically bind itself to any.sitemap file that it finds in the project, and nothing is required on your part to make this happen TheSiteMapPath’s smart tag allows you to customize the look and feel of the control as well so you canproduce other results in how it displays as illustrated in Figure 17-19
Figure 17-19
The code for this version of the SiteMapPathcontrol is as follows:
<asp:SiteMapPath ID=”SiteMapPath1” Runat=”server” PathSeparator=” : “ Font-Names=”Verdana” Font-Size=”0.8em”>
<PathSeparatorStyle Font-Bold=”True” ForeColor=”#507CD1”></PathSeparatorStyle>
<CurrentNodeStyle ForeColor=”#333333”></CurrentNodeStyle>
<NodeStyle Font-Bold=”True” ForeColor=”#284E98”></NodeStyle>
<RootNodeStyle Font-Bold=”True” ForeColor=”#507CD1”></RootNodeStyle>
</asp:SiteMapPath>
From this example, you can see a lot of style elements and attributes that can be used with theSiteMapPathcontrol There are many options at your disposal in order to give you the ability tocreate breadcrumb navigation that is unique
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 29Menu Server Control
Another navigation control allows for end users of your application to navigate throughout the pagesyour application offers based upon the information that is stored within the web.sitemapfile The Menuserver control produces a compact navigation system which pops out suboptions when the end userhovers their mouse over an option The end result of the Menuserver control when bound to the sitemap is as shown here in Figure 17-20
Figure 17-20
To build this, you must be working off of the web.sitemapfile that we created earlier After the
web.sitemapfile is in place, place a Menuserver control on the page along with a SiteMapDataSourcecontrol
<asp:Menu ID=”Menu1” Runat=”server” DataSourceID=”SiteMapDataSource1”>
</asp:Menu>
<asp:SiteMapDataSource ID=”SiteMapDataSource1” Runat=”server” />
The SiteMapDataSourcecontrol will automatically work with the application’s web.sitemapfile Inaddition to the SiteMapDataSourcecontrol, the other item included is the Menuserver control, whichuses the typical IDand Runatattributes in addition to the DataSourceIDattribute to connect this con-trol with what is retrieved from the SiteMapDataSourcecontrol
Like the other controls provided by ASP.NET, you can easily modify the look and feel of this control.Clicking on the Auto Format link in the control’s smart tag, you can give the control the ‘Classic’ lookand feel This setting would produce the following result as shown here in Figure 17-21
Figure 17-21
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 30Like the other controls, you can see that there are a lot of subelements that contribute to the changing ofthe control’s style This is illustrated here in the following code example:
<asp:Menu ID=”Menu1” Runat=”server” DataSourceID=”SiteMapDataSource1”
Font-Names=”Verdana” Font-Size=”0.8em” BackColor=”#B5C7DE” ForeColor=”#284E98” StaticSubMenuIndent=”10px” DynamicHorizontalOffset=”2”>
The TreeView Server Control
The last navigation server control that we will look at is the TreeViewserver control This control allowsyou to render a hierarchy of data The TreeViewcontrol is not only meant for displaying what is con-tained within the sitemapfile, but you can also use this control to represent other forms of hierarchaldata — such as data that you might store in a standard XML file
You may have encountered a similar TreeViewcontrol in NET when using the IE Web Controls, whichalso contained a TreeViewcontrol That previous TreeViewcontrol was limited to working only inMicrosoft’s Internet Explorer, while this new TreeViewcontrol will work in a wide variety of browsers
The TreeViewcontrol is similar to that of the Menucontrol in that it won’t bind automatically to theweb.sitemapfile, but instead requires an underlying DataSourcecontrol The code for displaying thecontents of the sitemapfile is shown here in the following example:
<asp:TreeView ID=”TreeView1” Runat=”server” DataSourceID=”SiteMapDataSource1”>
</asp:TreeView>
<asp:SiteMapDataSource ID=”SiteMapDataSource1” Runat=”server” />
As with the Menucontrol example, a SiteMapDataSourceis needed After a basic SiteMapDataSourcecontrol is in place, position a TreeViewcontrol on the page and set the DataSourceIdproperty toSiteMapDataSource1 This simple construction produces the result as shown here in Figure 17-22.Remember that by using the Auto Format link from the control’s smart tag, you can format theTreeViewcontrol with a wide variety of looks and feels
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 31Figure 17-22
The TreeViewis not only meant for site maps, but instead (as stated) it can build upon any underlyinghierarchal data set For instance, you can display a hierarchal data structure from a standard XML filejust as easily Let’s suppose you have an XML file as follows:
It’s quite obvious that this XML file is not meant for site navigation purposes, but instead it is meant for
an end user to make selections from As stated, the TreeViewcontrol is quite extensible For an example
of this, let’s create a page that uses the above XML file The code for the page is shown here:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 32For Each node As TreeNode In TreeView1.CheckedNodesLabel1.Text += node.Text & “ “ & node.Parent.Text & “<br>”
NextElselabel1.Text = “You didn’t select anything Sorry!”
End IfEnd Sub
<asp:Button ID=”Button1” Runat=”server”
Text=”Submit Choices” OnClick=”Button1_Click” />
<br />
<br />
<asp:Label ID=”Label1” Runat=”server”></asp:Label>
<asp:XmlDataSource ID=”XmlDataSource1” Runat=”server”
The TreeViewcontrol then binds itself to the XmlDataSourcecontrol through the use of theDataSourceIDattribute which here is pointed to XmlDataSource1 Another interesting addition inthe root TreeViewnode is the addition of the ShowLinesattribute being set to True This feature of theTreeViewwill cause each of the nodes in the hierarchy to show their connection to their parent nodethrough a visual line
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 33When working with XML files, which can basically be of any construction, you are actually going tohave to bind the nodes of the TreeViewcontrol to specific values that come from the XML file This isdone through the use of the <DataBindings>element The <DataBindings>element encapsulatesone or more TreeNodeBindingobjects Two of the more important available properties of a
TreeNodeBindingobject are the DataMemberand TextFieldproperties The DataMemberpropertypoints to the name of the XML element that the TreeViewcontrol should look for The TextFieldprop-erty specifies the XML attribute of that particular XML element If you do this correctly with the use ofthe <DataBindings>construct, you get the result shown here in Figure 17-23
Figure 17-23
In the button clickevent from our example, you can see how easy it is to iterate through each of thechecked nodes from the TreeViewselection by creating instances of TreeNodeobjects These selectionsare made from one of the TreeNodeBindingobjects which sets the ShowCheckBoxproperty to True
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 34Membership and Role Management
ASP.NET contains a built-in membership and role management system that can be initiated througheither code or through the ASP.NET Web Site Administration Tool This is an ideal system to use toauthenticate users to access a page or even your entire site This management system not only provides anew API suite for managing users, but it also gives you some server controls that interact with this API
The first set in setting up your site’s security and the user roles, open up the ASP.NET Web SiteAdministration Tool You will be able to launch this tool through a button in the Visual Studio 2005Solution Explorer or by clicking Build ➪ Configuration Manager in the Visual Studio menu From thetool, which will open up in the Document window, click on the Security tab Figure 17-24 shows whatthis tab of the tool looks like
Trang 35Figure 17-25
The first question asked from the wizard is whether your application will be available on the publicInternet or if it will be hosted on an intranet If you select Internet, then your Web site will be enabledwith forms authentication If you select Intranet, then your site will be configured to work with
Windows Integrated Authentication For our demonstration purposes, select the Internet option
Working through the wizard, you will also be asked if you are going to work with role management.Enable role management by checking the appropriate check box and add a role titled Manager After thisstep, you will actually be able to enter users into the system Fill out information for each user you want
in the system This is shown in Figure 17-26
The next step is to then create the access rules for your site You can pick specific folders and apply therules for the folder For this example, I made it so that anyone in the Managerrole would have access tothe site, while anonymous users would be denied access This is shown here in Figure 17-27
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 36Figure 17-26
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 37Clicking the Finish button will of course finish the wizard If you refresh the Solution Explorer in VisualStudio, you will notice that there is a new data store (an SQL Server Express Edition mdb file) in theApp_Datafolder This is where all of the user and role information is being stored It is important to notethat you can configure both of the systems (the membership and role management systems) to workwith other data stores besides these SQL Express data files For example, you can configure these sys-tems to work with a full-blown version of Microsoft’s SQL Server You will also notice in the SolutionExplorer, that if you didn’t already have a web.configfile, you have one now The contents added tothe web.configfile include:
The next step is to create a login page as everyone will be hitting any page in this application as ananonymous user first The login page will allow for people to enter in their credentials in order to beauthorized in the Managerrole that we created earlier
ASP.NET includes a slew of controls that make working with the membership and role management tems easier On the login page (Login.aspx), let’s place a simple Loginserver control on the page
sys-<asp:Login ID=”Login1” Runat=”server”></asp:Login>
The nice thing here is that you have to do absolutely nothing to tie this Logincontrol to the mdfdatabase that was created earlier through the wizard Now go back to another page in the application(besides the Login.aspxpage) and start up that page In my case, I started up Default.aspx(whichonly contains a simple text statement), but from Figure 17-28 you can see (by looking at the URL speci-fied in the browser) that I was redirected to Login.aspxinstead as I wasn’t yet authenticated
The Login.aspxpage allows me to enter my credentials, which then authorize me in the Managerrole.Hitting the Loginbutton causes the browser to redirect me to the appropriate page I am now authenti-cated and authorized for the site!
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 38Figure 17-28
Personalization
Many Web applications have features that allow for personalization of some kind This might be as ple as greeting the users by name or it might deal with more advanced issues such as content placement.Whatever the case, personalization techniques have always had a tricky approach Developers used any-thing from cookies, sessions, or database entries to control the personalization that users placed on theirpages
sim-ASP.NET 2.0 includes a simple to use and configure personalization system It is as simple as makingentries in the web.configfile to get the personalization system started Like the membership and rolemanagement systems, the personalization system also uses an underlying data store In our example, wewill continue to work with the SQL Server Express Edition mdb file
For our example, we are going to create two properties —FirstNameand LastName, both of typeString For this, we will need to alter the web.configfile The changed web.configfile is shown here:
<add name=”FirstName” type=”System.String” />
<add name=”LastName” type=”System.String” />
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 39“<br>Last name: “ & Profile.LastNameEnd Sub
Configuring ASP.NET
Configuring ASP.NET is something that has been greatly enhanced in this release of ASP.NET Instead
of purely working with various XML configuration files to manage how ASP.NET works and performs,you can now use an MMC ASP.NET Snap-In To get at this new ASP.NET configuration tool, open up IIS
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 40(5.0 or 6.0) and expand the Web Sites folder This folder shows a list of all the Web sites configured towork with IIS Remember that not all of your Web sites are configured to work in this manner It is alsopossible that you have built your Web application so that it is making use of the new ASP.NET built-inWeb server.
After you find the application you are looking for in the Web Sites folder, right-click that application andselect Properties from the list
Selecting the Properties option brings up the MMC console The far-right tab is the ASP.NET tab Clickthis tab to get the results shown here in Figure 17-29
Figure 17-29
You should also note that selecting one of the application folders lets you edit the web.configfile from the MMC snap-in; selecting Properties for the default Web site (the root node) lets you edit themachine.configfile as well
In addition to being able to edit the ASP.NET features that are shown in Figure 17-29, the ASP.NET tabalso includes an Edit Configuration button that provides a tremendous amount of modification capabili-ties to use in the web.configfile When you click this button, you will then be provided with a multi-tabbed GUI titled ASP.NET Configuration Settings (shown here in Figure 17-30)
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com