Home arrow ASP.NET arrow Page 4 - Creating Dynamic ASP.NET Server Controls Using XML
ASP.NET

Creating Dynamic ASP.NET Server Controls Using XML


A common way of using XML in ASP websites is to format dynamic information. In this article Eric shows us how to create a survey application using ASP.Net and XML.

Author Info:
By: Wrox Team
Rating: 5 stars5 stars5 stars5 stars5 stars / 205
December 12, 2002
TABLE OF CONTENTS:
  1. · Creating Dynamic ASP.NET Server Controls Using XML
  2. · Generation of Server Controls From Text
  3. · Custom Survey System Example
  4. · XML Namespaces
  5. · Conclusion

print this article
SEARCH DEVARTICLES

Creating Dynamic ASP.NET Server Controls Using XML - XML Namespaces
(Page 4 of 5 )

You might notice in the XSLT that a prefix is defined for the XSL namespace. This is so that plain HTML can be generated, and not be interpreted as XSLT commands. HTML is not XML, so it cannot have a prefix if it is to work as HTML, so the HTML element must reside in the default namespace. The XSLT can be directed to omit namespace prefixes, but they are needed for the server controls, which require an asp prefix.

Looking at a page's source in the WebForm designer, it appears that the ASP.NET page's source code is XML. While the code is similar to XML, in both format and intent, it is not XML. The main effect of this code format for this article is that a namespace declaration is not allowed in ASP.NET server control declarations. However, the namespace prefix is required, which is why it is defined in the XSLT as xmlns:asp="remove". After the XSLT is applied to the XML, the server controls have a format like <asp:TextBox ... xmlns:asp="remove"/>, which is not legal. But, if the namespace declaration is removed, then the result is valid ASP.NET source code.

Instantiate Controls
Once the XSLT has been applied to the XML and the appropriate namespace declarations have been removed, all that is left is to instantiate the controls and add them to the page. Calling the Page.ParseControl method and capturing the returned control, which is actually a collection of controls, is the way to do this. This control collection is then added to the survey control's control collection and the process is complete. The survey control is a PlaceHolder control, which allows placement of the survey to be done as a single unit on a larger page and allows for management of the visibility of the survey as a whole.

For this system, all these steps are wrapped into one method, CreateSurvey, which loads the XSLT, transforms the XML, and removes the namespace references for the server controls. The method is called from the page's init event handler, as this ensures that the state and all events for the controls are processed correctly. For the full code of the init event handler, please see the code download available at the end of the article.

// called from Page's Init event handler
private void CreateSurvey() {
// Load the data source
XPathDocument surveyDoc = new
XPathDocument(Server.MapPath("ExSurvey.xml"));

// Load the xslt to do the transformations
XslTransform transform = new XslTransform();
transform.Load(Server.MapPath("MakeControls.xslt"));

// Get the transformed result
StringWriter sw = new StringWriter();
transform.Transform(surveyDoc, null, sw);
string result = sw.ToString();

// remove the namespace attribute
result = result.Replace("xmlns:asp=\"remove\"", "");

// parse the control(s) and add it to the page
Control ctrl = Page.ParseControl(result);
survey.Controls.Add(ctrl);
}


Process Results
In a full custom survey system, the results from a submitted survey could be saved to a database, via some sort of data access objects. However, for this example, the results will simply be sent via email. The XML document that defines the question is used here again, but this time by iterating over the questions to get the answers to each one by use of the Page.FindControl method.

private void ProcessSurveyResults () {
// Load the data source
XPathDocument surveyDoc = new XPathDocument(Server.MapPath("ExSurvey.xml"));
// create an iterator for each question
XPathNodeIterator itr =
surveyDoc.CreateNavigator().Select("//question");
// string builder for survey body
System.Text.StringBuilder sb;
sb = new System.Text.StringBuilder();
// submission information
sb.Append("Survey submitted on " + DateTime.Now + Environment.NewLine);
// foreach question
while (itr.MoveNext()) {
// get the control name
string controlName = itr.Current.GetAttribute("name", "");
// append question information
sb.Append(controlName);
sb.Append(" : ");
// get the control
object ctrl = FindControl(controlName);
// append the correct filled out information
if (ctrl is TextBox) {
sb.Append(((TextBox)ctrl).Text);
}
if (ctrl is RadioButtonList) {
// the selected item might be null
if (((RadioButtonList)ctrl).SelectedItem != null) {
sb.Append(((RadioButtonList)ctrl).SelectedItem.Value);
}
}
sb.Append(Environment.NewLine);
}
string body = sb.ToString();
// send the results
// NOTE In a full application, these settings should be stored
// in a configuration file, so that the email addresses and server
// address can be changed without editing the code
System.Web.Mail.SmtpMail.SmtpServer = "your.smtp.server";
System.Web.Mail.SmtpMail.Send("survey@somewhere.com", "your@address.com",
"Survey result", body);
}


Other Details
The only other item needed for the sample application is a label thanking the user for his/her input, which is made visible when the form is submitted (to prevent double responses). You know when the page is submitted by looking at the IsPostBack member variable, which is set to true when the page has been submitted. Be aware that the IsPostBack variable can also true when a server event is raised, so in a full system you would want to check which control caused the postback before processing the survey results. Assuming that the postback is caused by user submitting the survey, the label thanking the user is made visible and the survey control is made invisible. This all occurs in the page's load event handler, along with any other code needed for the rest of the page.

if (IsPostBack) {
ProcessSurveyResults();
survey.Visible = false;
ThankYouLabel.Visible = true;
} else {
survey.Visible = true;
ThankYouLabel.Visible = false;
}


Successful submission

Example Setup
All the code discussed here is included in a zip file, which can be downloaded via the link at the end of this article. It is in the form of a Visual Studio.NET Web Application project, but it does not require Visual Studio.NET. To install the custom survey example, extract the files to a directory, and then share that directory in IIS. If you want to use the email notification for survey results, change the SMTP server and email addresses in the ProcessSurveyResults method in WebForm1.aspx.cs to appropriate values for your network.

Received email

Enhancements
The number of possibilities for the XML/XSLT/server control combination is enormous. Web Services return data in an XML format (SOAP), and so this technique can be leveraged as part of a Web Services system. For example, you could create a custom Web Services browser, where the application queries the server, and then allows the execution of methods exposed by the Web Service via a dynamically generated form. This could look similar to the Microsoft Web Service interface, which uses the SOAP information generated when a method is marked with the WebMethod attribute. The Microsoft interface is visible by loading a web service URL in a browser. By using server controls and XSLT, a new interface can be created and be completely customized. Other ideas leverage SQL Server, which can return SQL data, so a data entry interface could be dynamically generated, thus eliminating the need to write administrative webform code, as well as ensuring business rules are enforced via the rich functionality that server controls provide.
blog comments powered by Disqus
ASP.NET ARTICLES

- How Caching Means More Ca-ching, Part 2
- How Caching Means More Ca-ching, Part 1
- Reading a Delimited File Using ASP.Net and V...
- What is .Net and Where is ASP.NET?
- An Object Driven Interface with .Net
- Create Your Own Guestbook In ASP.NET
- HTTP File Download Without User Interaction ...
- Dynamically Using Methods in ASP.NET
- Changing the Page Size Interactively in a Da...
- XML Serialization in ASP.NET
- Using Objects in ASP.NET: Part 1/2
- IE Web Controls in VB.NET
- Class Frameworks in VB .NET
- Cryptographic Objects in C#: Part 1
- Sample Chapter: Pure ASP.Net

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials