HomeASP.NET Completing an ASP.NET AJAX Client-Centric ...
Completing an ASP.NET AJAX Client-Centric Wiki Application
In this conclusion to a four-part series on building an ASP.NET client-centric wiki application, we will delve deeply into the code, both client side and server side. We will also look at how to add comments to articles.
Contributed by Xianzhong Zhu Rating: / 3 October 16, 2007
Herein I have purposely leveraged all the ASP.NET 2.0 server controls-from the TextBox along with its related RequiredFieldValidator control to the DropDownList, as well as the commonly-used SqlDataSource control which is used to provide data for the DropDownList. Here, there's only a small piece of code worth discussing:
ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID],[CategoryName] FROM [ArticleCategory]">
</asp:SqlDataSource>
Here's the typical ASP.NET 2.0 usage: the SqlDataSource control is bound to the DropDownList to provide data for it. Since Microsoft has provided a good article that dwells on this kind of data binding we will not explain it here.
When the user populates all the necessary fields and clicks the Post button a JavaScript function named SendMsg() will be invoked. Here is its related code:
<script type="text/javascript">
var xmlhttp;
function createHTTP() {
if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
}
function SendMsg(){
document.getElementById("divlist").innerText="Posting the article...";
var msgtitle=document.getElementById("<%= txttitle.ClientID % >").value;
var msgcontent=document.getElementById("<%= txtcontent.ClientID %>").value;
var categoryid=document.getElementById("<%= DropDownList1.ClientID %>").value;
As is clearly seen, in the SendMsg function, we first show to the users the message 'Posting the article...', then get the required values from the three ASP.NET 2.0 server controls using the 'document.getElementById' and <%...%> methods. Next, we create the famous asynchronous XMLHTTP object (only in Internet Explorer; in other browsers it is the XMLHttpRequest object) by calling the createHTTP() method. Next, we attach the above asynchronous object state to a specified callback function, named stateChange, which bears responsibility for judging whether the asynchronous invoking has been completed and succeeded and makes the corresponding arrangements. Next, we call the open method of the asynchronous object to set up the connection with the server side and, at the same time, pass the required parameters (here, the server side page SendMsgServer plays the role of a CGI). At last, we start up the asynchronous request.
Response.Write("Congratulation! You've succeeded in sending the post.");
}
There are four tasks here in total.
Accept the passed parameters.
Add the general article information into the database table.
Put the detailed article content into the corresponding '.xml' file using an XML file template (i.e. file content.xml located at the root folder, which specifies the format of a newly-generated XML file).
Send back to the client side the message about the asynchronous invocation.
Obviously, steps 2 and 3 are of major interest to us. Let's continue to study them.
First, let's check out the code for the AddArticle method:
public void AddArticle(string title, string user, int categoryid)
{
StringBuilder strSQL = new StringBuilder();
SqlParameter[] newsParms = GetParameters();
newsParms[0].Value = title;
newsParms[1].Value = getFilename().ToString();
xmlfilename = getFilename().ToString();
newsParms[2].Value = DateTime.Now;
newsParms[3].Value = 0;
newsParms[4].Value = DateTime.Now;
newsParms[5].Value = user;
newsParms[6].Value = categoryid;
using (SqlConnection conn = new SqlConnection(ConnectionString))
Here, we first get the buffered parameters using the helper method GetParameters; if there are no buffered parameters this method will automatically create a list of parameters and buffer them. Next, we assign values to each parameter. At last, within the 'using' code block we accomplish the task of inserting the current article information into the ArticleInfo table with the help of a helper class named SqlHelper (you can study it in the downloaded source code).
Additionally, it's worth doing some more research into the above private method named getFilename:
private int getFilename(){
int cardrule = 0;
string strsql = "select top 1 InfoID from ArticleInfo order by InfoID desc ";
As you can see above, using the SqlHelper helper class gives us the maximum value for the InfoID field in the current ArticleInfo table, and then adds 1 to it. Finally, we return the integer value as the file name.
Next, let's take a look at the code of the AddXML method:
XmlTextWriter mytw = new XmlTextWriter(path, Encoding.Default);
mydoc.Save(mytw);
mytw.Close();
}
Here, we are performing the typical ASP.NET 2.0 XML data operation-mainly using the XmlDocument class and the XmlTextWriter class together with a ready XML file template to construct an XML file which, due to the reason discussed before, will finally be stored at the root folder of the website. Since there is nothing more peculiar to be emphasized (you can find out much about XML operations in MSDN), we will leave the subject here, but it is highly recommended that you study it together with the ready template file named 'content.xml'-it's a pretty universal module that you can put to use elsewhere.
So much for the 'sending post' module. Next, let's continue to study the last part of this article-adding comments to the current article.
As is pointed out, there are a lot of puzzles and awkwardness to tackle in dealing with the XML typed data using a Microsoft AJAX client-centric scheme. Therefore, here, we still have to resort to the original AJAX mode when adding posts (which will be persisted in the '.xml' file form) to the present article.
Now, when you click the Reply hyperlink at the ContentList.aspx page, you will be redirected to another page named ReplyMsg.aspx. The following Figure 13 corresponds to it as a design-time snapshot.
Figure 13-the design-time snapshot when replying to the current article.
Whether the inner logic or the user interface design, this part is quite similar to the above 'Writing a New Article Using......'. Therefore, we will make a long story short. The above Reply hyperlink corresponds to the following HTML code:
<div >
<a id='btnReply' href="javascript:backdata()" title="Reply the post">
<img src="images/reply.PNG" />
</a>
</div>
Obviously, all the secrets are wrapped in the JavaScript function backdata:
As is seen from above, all the coding here exactly resembles the coding we did for posting a new article.
Next, let's take a look at the server side programming within the 'ReplyMsgServer.aspx.cs' file (the so-called 'CGI'). As usual, we first give the related code snippet, as follows:
Accept the passed parameters and rebuild a file name with full path.
Update the corresponding '.xml' file that holds the detailed article content.
Update the general article information into the database table.
Post back to the client side the message about the asynchronous invocation. All the contents relevant to the UpdateXmlFile() and UpdateDatabase() functions are nearly the same as those in the above AddXML() and AddArticle() functions.
Here, still for the sake of brevity, we omit all of them. However, there turns up a peculiar bug here that I have to mention. If we, as usual, replace the above last sentence with the following:
Response.Write("The asynchronous invocation is successful!");
I will see some messy content (beginning with this above specified hint message) at the bottom of the above Figure 13. To my astonishment, anything else is still OK-we can , as usual, see the recently-posted contents when we again launch the web application! For this reason, I have to post an empty string to the client side. If anyone e is successful in overcoming this bug, I would be very glad to hear about it.
Oh, so much is for this long and mildly awkward application. You can finally press F5 and give it a test!
In this article we've developed a simple article-related wiki application using an ASP.NET AJAX client-centric framework. As hinted at the beginning of this article, there are rather more difficulties in constructing an MS AJAX client-centric application than the server-centric ones-on the one hand, the MS AJAX client-centric architecture has not been fully fledged; on the other hand, practical web applications usually bring forth new and complex business requirements which require the developers take the reins firmly and freely with many respects that are relevant to the web applications.
I've brought this tutorial to you only with the aim that you can balance every technique you know to decide whether to select the server-centric programming mode or the client-centric one in building your next web 2.0 applications.
By the way, as just a demo, the application in this article has only brought you the basic routine in constructing a Microsoft AJAX client-centric application. The following points remain to be improved or added:
Substituting the current page switching solution with more fluid and user-friendly ones.
Finding new ways of dynamically updating the client-side article content after new users add new comments/posts to it.
Adding more convenient article editing function support.
Replacing the current TEXT-format based editing in authoring a new article with the real scenario online HTML-based editing support and therefore storing the HTML content instead of the XML content.
Further optimizing the speed of displaying UI elements since the xml-script resolution greatly tampers with this display speed.
Using the client-side Validator controls to validate the article title and content.
Adding RSS support as achieved by many modern web applications