Develop online RSS reader Based on ASP. NET Ajax technology

Source: Internet
Author: User
Document directory

Abstract: This article aims to explore the development process of an online RSS reader based on Microsoft ASP. net Ajax framework (especially client technology) for a new generation of ASP. NET 2.0 development involves typical issues. This article consists of two parts: the data layer and description layer of the software. In the next article, we will transfer the focus of the entire development process to the logic layer design.

[Note] test environment: Windows XP Professional Edition + Visual Studio 2005 + complete ASP. NET Ajax framework + ASP. net rss toolkit + SQL Server 2005.

1. RSS Technology Overview

RSS is an XML format used to describe and synchronize website content. It has become a popular website content subscription technology. Through this technology, the website can greatly improve the data interaction between the majority of website users and website data.

RSS reading software can be divided into two categories: offline desktop and online. With this tool, users only need to add the RSS URLs they are interested in. Later, the system will automatically update the relevant content. Users only need to wait for the news they are interested in.

There are multiple versions of RSS file formats, including 0.90, 0.91, 0.92, 0.93, 0.94, 1.0, and 2.0. Among them, version 2.0 is the most popular. The following shows the basic format of the simplest 2.0 RSS file:

<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Example Channel</title>
<link>http://example.com/</link>
<description>My example channel </description>
<item>
<title>News for September the Second</title>
<link>http://example.com/2002/09/01</link>
<description>other things happened today</description>
</item>
<item>
<title>News for September the First</title>
<link>http://example.com/2002/09/02</link>
</item>
</channel>
</rss>

The main nodes of the RSS File Include RSS, channels, and items. The RSS node indicates the standard RSS namespace for execution. The channel node indicates a category in a blog or newsgroup, which is usually translated into a channel. The item node is the main information you want to view, it includes the title of the information, the link address of the information content, and the Publishing Time of the information. For details about the complete RSS file node, visit http://cyber.lay.harvard.edu/blogs/gems/tech/rss2sample.xml.

About robsman's ASP. net rss Toolkit

Obviously, it is time and effort-consuming to manually Parse XML files because there are many versions of RSS files and there are some gaps. Fortunately, we can use the open-source RSS toolkit developed by Microsoft (download URL: http://blogs.msdn.com/dmitryr/) to simplify it.

This toolkit has the following features:

1) RSS data source control-similar to the data source control built in ASP. NET, it also supports binding and supporting templated data binding, and provides it with the required data display;

2) The contents of the remote RSS feed can be cached in the memory or disk;

3) RSS-based URLs generate strong types of objects that are easy to develop and debug for RSS feeds;

4) encapsulate the typical operations of the RSS feed generated in the program.

Next, we will use a specific example to explore how to use this toolkit and develop a simple RSS news reader based on the Microsoft ASP. NET Ajax framework.

Ii. Analysis of Main functions and key technologies of the system

Before the official start of the project, let's take a look at the main functions of the system and the main technologies involved in the development of the system.

(1) Main Functions

An online RSS reader can store your favorite RSS subscriptions in a server-side database so that they can be accessed at any location with an Internet connection. Typically, we can use 1 to roughly describe the engineering process of an RSS reader.

Figure 1: typical Engineering Process of an RSS reader

According to the above, dajaxrssreader will mainly achieve the following objectives:

◆ Add an RSS feed

You can save the newly entered RSS channel and related URL Information to the ASP. NET Ajax client data source control. And of course, they can store all this information in the SQL Server database of the remote server.

◆ Display all RSS feeds

This mainly includes two situations: 1. When an application is started, all the channel information stored in the server database should be listed on the browser; 2. When a user Refreshes an RSS feed, all data associated with the feed can be read back from the server and displayed on the client.

◆ Display the details of the selected RSS Feed

When you select a channel, the application should be able to display the corresponding webpage content linked to the channel.

(2) Key Technologies

First, we should follow the well-known three-tier structure principle whenever possible during the development of any typical web application. Figure 2 shows the three-tier architecture of the RSS reader program in this article.

Figure 2: overall architecture of the RSS reader program in this article

Next, let's take a quick look at the snapshots on the home page of the sample program before we officially discuss the key technologies involved, as shown in Figure 3 below.

Figure 3: The sample RSS reader is a snapshot of the design time.

Based on the graph shown above and the functional analysis above, we need to develop the application in this article based on the following key technologies:

1. In the description layer, we need to use ASP. net Ajax client listview control to store and display all RSS channel information, there is also a server-side updatepanel control to encapsulate ASP. net Ajax Control Toolkit control accordion to display the website content associated with the items you selected from the listview. In addition, we also need some CSS skills to modify all related controls. Finally, we introduced the ASP. NET Ajax client validator (validator) to verify the RSS name and URL entered by the user.

2. In the example program in this article, we will mix JavaScript with XML-script Declarative Programming. On the one hand, in the actual development environment, based on ASP. the web applications of the net Ajax framework are usually quite complex; on the other hand, Asp. the net Ajax framework itself is not yet fully mature, so that our building objectives are fully developed based on the XML-script Declarative Programming Method. Although the implementation of some programming is more complex than the XML-script declarative method by using JavaScript (because ASP. net Ajax client provides a very similar to ASP. net), but the advantage of JavaScript is that it can control every aspect of the development process from the server to the client.

3. For data layer Development Based on ASP. NET Ajax applications, a typical implementation mode has been provided in online data. This mode will be used in this example.

[Note] When debugging the sample program in this article, I was introduced to ASP. net Ajax Control Toolkit control combined with Dmitry robsman ASP.. Net RSS toolkit issues client-to-server communication problems. According to my analysis, we usually cannot implement the rssdatasource (RSS) on the server inside a web service. net Toolkit) is dynamically bound to the accordion control (actually an ASP.. Net Ajax server Extender ). Therefore, in order to overcome this problem, I have to resort to the _ dopostback function to create a connection between the client and the server. This will obviously lead to a problem of refreshing the whole page-this is similar to ASP. net Ajax rules are fundamentally conflicted. Therefore, I have to introduce the ASP. NET Ajax Server Control updatepanel to "enclose" the accordion control to achieve partial update. Of course, the other thing that makes things more complicated is the ASP. NET Ajax client control-listview. From the analysis of the underlying layer, the listview control is far from mature!

Next, let's gradually explore the development process of the entire sample project from the data layer design and development.

Iii. Data Layer Design

(1) Database Design

Start Visual Studio 2005, select "File> New website ...", Select the "ASP. NET Ajax-enabled web site" template, name the project "ajaxrss", select C # As the built-in support language, and click OK. Note that the system will automatically add references to the Assembly Microsoft. Web. Preview. dll and System. Web. Extensions. dll. Of course, you will also notice that scriptmanager, the server control of ASP. NET Ajax command, is automatically added to the default webpage default. aspx.

Right-click the project and select "Add new project ...", Select the template "SQL database" to create an empty database named rssreader. MDF. In this article, we only add a table rssstore in this library (all its fields are shown in table 1 below ). After that, we will create four stored procedures: deleterecord, getallrecords, insertrecord, and UpdateRecord. These four stored procedures correspond to typical database crud operations (ASP. NET Ajax client data binding technology provides a good support solution, as shown in this article ). We will not repeat all this here.

Table 1: Structure of table rssstore

Field name

Type
Description

Rss_id
Int
Table Primary Key

Rss_name
Nchar (32)
RSS channel name

Rss_url
Nchar (64)
RSS feed uri (or URL)

(2) web service design

Next, we will compile a web service that will be called in Ajax mode from the client. In this example, let the service return an array of rssinfo objects (used as the OOP wrapper recorded in the database table rssstore.

Right-click the project and select "Add new project ..." Create a new Web Service mydataservice. asmx. Then open the file bookdataservice. CS and write all the web methods we require-deleterecord, getallrecords, insertrecord, and UpdateRecord. These four methods are basically the same as what I used in my previous articles on 51cto. I will not repeat them here. Interested readers can also refer to the corresponding source code for analysis.

Next, we will enter the user interface design stage.

Iv. User Interface Layer Design

Based on the general framework described above, we can divide the entire user interface into three parts:

1) Add new RSS feed information;

2) display the RSS feed list;

3) display the content of the specified RSS feed (that is, the content of the website associated with it ).

Figure 3 above shows the user interface for the application design in this article.

In Figure 3 above, an ASP. NET Ajax client control-listview is located in the upper left corner. It is used to store and display the RSS channel list. The lower-end. gif animation (Note: it corresponds to the emptytemplate part of the control listview) is only used to produce a more friendly user experience. The large rectangle area of the animation page (it contains several simple ASP. net Ajax client control) the field corresponds to an HTML Div tag (named "buttonarea"), providing users with New RSS channel information. The right part of the entire web page is an accordion control in ASP. NET Ajax Control Toolkit, which is used to display details of a specified RSS channel. There are several other "mysterious" dots on the page, the ASP. NET Ajax Server Control updatepanel that is surrounded by the accordion control, and the associated updateprogress control, which will be detailed later. Now, you must have noticed the RSS toolkit control-rssdatasource control in the lower-left corner of the page, which is used to provide data sources for the accordion control on the server side (generally, we can only use it from the server at runtime, because it is a server-side data source control. For details about this control, we will introduce it later ). Finally, all controls are surrounded by an HTML table element.

So far, we have finished introducing the data layer and description layer in this software. In the next article, let's move to the logic layer design, the focus of the entire development process.

V. logic layer design

(1) Add an RSS feed

Before developing a true logical layer design, let's simply browse sketch 4 under idea. Figure 4 shows my understanding of the two important ASP. NET Ajax client controls-listview and datasource, and the client data binding architecture recommended in MS Ajax official documents.

498) This. style. width = 498; ">

Figure 4: typical client data binding architecture recommended in the ASP. NET Ajax framework

In this example, we can draw the following conclusion: when a new RSS channel is added, we do not need to store the data to the SQL Server database on the server immediately, but temporarily store the data source control associated with the client control listview. Therefore, you can guess that the datasource control supports batch update operations-supports temporary storage of client-side data modification and finally updates the server-side database in batches. The two important methods in the preceding Sketch-"save" and "LOAD" play an important role in the implementation logic.

In this section, we only need to temporarily store the user's New RSS channel information on the client. Here, I encountered the first problem during operations on the listview control. Next let's take a look at the corresponding source code.

List 1

<script language="javascript" type="text/javascript">

var g_RSSNameList;

function pageLoad(sender, args) {

g_RSSNameList=$find('RSSNameList');

…………

}

function Add_onclick() {

g_RSSNameList.addItem();

var  index=datatable.get_length()-1;

datatable.getItem(index).setProperty('Rss_ID', index);

datatable.getItem(index).setProperty('Rss_Name', $find('txtRssName').get_text());

datatable.getItem(index).setProperty('Rss_URL', $find('txtRssUrl').get_text());

}

When you click the HTML input button "add the RSS Info" on the client, the above JavaScript function add_onclick (the Click Event processor) is called ). Here, g_rssnamelist is a global JavaScript variable that references listview "rssnamelist" (controls responsible for storing and displaying RSS channel information ). In this function, we first call the additem method of listview. This method can add an empty record to the end of the datatable control associated with the datasource control, it can also make the dataset dirty (this is important for the "save" operation we will discuss later ). Then, we get the record number of this empty record. Then, we call the getitem method (which is exactly the same as the getrow method) to retrieve the null record and call the setproperty method to fill in the corresponding database table fields. Note: here, we must use the global client method $ find instead of $ get. For the differences, see online framework documentation. In the end, a record is inserted ('add') in the client data source.

Note: Here I use the simplest ASP. Net Ajax client checker component-requiredfieldvalidator to prevent users from entering content in the text box. The following is the XML-script code declaration.

List 2

            

<textBox id="txtRssName">

<validators>

<requiredFieldValidator errorMessage="You must name the RSS!" />

</validators>

</textBox>

<validationErrorLabel id="validator1" associatedControl="txtRssName" />

<textBox id="txtRssUrl">

<validators>

<requiredFieldValidator errorMessage="You must name the Url of the RSS!" />

</validators>

</textBox>

<validationErrorLabel id="validator2" associatedControl="txtRssUrl" />

In the verification of the second text framework control, you can use regexvalidator (which can use regular expressions to verify the format of the URL here ). If you leave the two controls empty (for example, enter only a few space characters), the system will display a red "*"-indicating that you should enter some data. When debugging this program, the system does not seem to reflect when I keep the two text boxes empty (without entering any content. This is suspected to be a small bug in the validator client. Interested readers can further analyze it.

[Note] in this demonstration program, I have not implemented the "Delete" and "modify" functions. Here, I strongly recommend that you try to add these two features. Through these operations, your ASP. NET Ajax client programming skills will be greatly improved.

Next, let's discuss how to display the RSS tunnel stored on the server.

(2) display RSS Channels

In this section, there are at least two situations for displaying RSS channels:

1) when the page is loaded for the first time, all RSS channels stored in the SQL Server database on the server will be displayed in the client control listview we mentioned earlier;
2) When you click "refresh", the RSS channel information stored in the SQL Server database on the server is displayed in the client control listview.

Now, let's analyze the first situation. The following list shows the declared XML-script code.

List 3

            

<script type="text/xml-script">

<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">

<components>

<dataSource id="RSSInfoDataSource" serviceURL="MyDataService.asmx" >

</dataSource>

<button id="Save">

<click>

<invokeMethodAction target="RSSInfoDataSource" method="save" />

</click>

<bindings>

<binding dataContext="RSSInfoDataSource" dataPath="isDirtyAndReady"

property="element" propertyKey="disabled" transform="Invert" />

</bindings>

</button>

<button id="Refresh">

<click>

<invokeMethodAction target="RSSInfoDataSource" method="load" />

</click>

<bindings>

<binding dataContext="RSSInfoDataSource" dataPath="isReady" 

property="element" propertyKey="disabled" transform="Invert" />

</bindings>

</button>

<application>

<load>

<invokeMethodAction target="RSSInfoDataSource" method="load"/>

</load>

</application>

</components>

</page>

</script>

Here, we first specify the datasource control "rssinfodatasource ". This control will be asynchronously bound to the dataservice "mydataservice" on the server side by the ASP. NET Ajax framework ". Second, in the last <Application> section, when the web application starts, its load event method is called. Then, in the subsection <invokemethodaction>, the load method of the data source "rssinfodatasource" is called, which triggers an asynchronous return-call the data service "mydataservice" web method getallrecords. The following list shows the implementation code of this method.

List 4

[WebMethod]

[DataObjectMethod(DataObjectMethodType.Select)]

public List<RssInfo> GetAllRecords()

{

return new SqlTaskProvider().GetAllRecords();

}

For more information about modifying attributes before this method, see ASP. NET Ajax online documentation. Now, once this method is executed, the client listview control "rssnamelist" is filled in with records stored in the server SQL Server database table rssstore.

Note: here we have implemented some tips: to achieve a better user experience, we have hidden two fields rss_id and rss_url (the content in these two fields does not need to be displayed ). The following shows the corresponding HTML code snippet.

List 5

<div id="searchResults_itemTemplate" >

<span id="searchResults_Rss_ID" style="display: none; visibility: hidden;"></span>

<span id="searchResults_Rss_Name"></span>

<span id="searchResults_Rss_URL" style="display: none; visibility: hidden;"></span>

</div>

There is no need to worry that the ASP. Net Ajax framework will automatically differentiate this situation and can still fill the listview control with database record data, but only hide the display of the two fields.

Now let's analyze the second scenario-when the user clicks "refresh. Although literally, we use "refresh", this button is used to load the database data on the server to the current listview control. This process is directly related to the Data Control datasource of the client. The following XML-script code shows you the corresponding programming.

LIST 6

            
<button id="Refresh">

<click>

<invokeMethodAction target="RSSInfoDataSource" method="load" />

</click>

<bindings>

<binding dataContext="RSSInfoDataSource" dataPath="isReady" 
     property="element" propertyKey="disabled" transform="Invert" />

</bindings>

</button>

The code above shows that when you click "refresh", the load method of the client datasource control "rssinfodatasource" is called. Then, the web method getallrecords will be called asynchronously, and the data returned by the web method will be filled in the listview control.

For the sake of completeness, in this example, we also introduce a "save" button, which is opposite to the "refresh" button. When you click "save", all the newest RSS channel data in the listview control will be Ajax (that is, "Asynchronous) permanently stored in the SQL Server database on the server. To further explore the function of this button, please refer to another article "" I published on 51cto. In this article, I have comprehensively analyzed ASP.. Net Ajax client listview and itemlist controls interact with the server SQL Server database packaged in Web Services.

(3) display the corresponding content of the specified RSS Channel

Now the problem is getting more and more interesting. To display the content of an RSS feed, just click an item in the listview control and then let the accordion control on the right display the corresponding details? Yes, but this is only the conclusion from the user's perspective. But as a developer, it took me a lot of time to find an implementation solution to solve this problem. Next, let me introduce you one by one.

Obtain RSS feed content through the network

1. About the listview Control

For the "advanced" client listview control provided by the ASP. NET Ajax framework, I would like to briefly discuss a few words. Previewscript from the source code file of the Research Framework. JS, we found that the descriptor block definition in this control (Note: Only content in this block can be used in XML-script Declarative Programming) only a small number of objective attributes, methods, and event definitions are provided. The following describes the definition of the descriptor block of the control.

List 7

Sys.Preview.UI.Data.ListView.descriptor = {

properties: [ { name: 'alternatingItemCssClass', type: String },

{ name: 'layoutTemplate', type: Sys.Preview.UI.ITemplate },

{ name: 'itemCssClass', type: String },

{ name: 'itemTemplate', type: Sys.Preview.UI.ITemplate },

{ name: 'itemTemplateParentElementId', type: String },

{ name: 'selectedItemCssClass', type: String },

{ name: 'separatorCssClass', type: String },

{ name: 'separatorTemplate', type: Sys.Preview.UI.ITemplate },

{ name: 'emptyTemplate', type: Sys.Preview.UI.ITemplate } ],

events: [ {name: 'renderComplete'} ]

}

In the preceding descriptor block definition, there are only a few limited attributes and an event. The method we will use later will also turn to the control's parent class datacontrol. Therefore, to control each item (corresponding to a record data) in the user-clicked listview Control, we have to further study the prototype block in the listview control definition and turn to JavaScript programming.

2. Add events for listview through JavaScript programming

First, let's list all the corresponding source code.

List 8

            

<Script language = "JavaScript" type = "text/JavaScript">

VaR g_rssnamelist;

Function pageload (sender, argS ){

G_rssnamelist = $ find ('rssnamelist ');

$ Addhandler ($ get ('rssnamelist'), 'click', clickrowhandler );

}

Function clickrowhandler (EV)

{

VaR S = ev.tar get;

While (S & (typeof (S. dataindex) === 'undefined ')){

S = S. parentnode;

}

If (s ){

VaR idx = S. dataindex;

// Call the server method corresponding to dummysrvbtn of the "dummy element" Control

VaR BTN = '<% = dummysrvbtn. clientid %> ';

VaR TXT = '<% = txtrssurl2.clientid %> ';

Document. getelementbyid (txt). value = "/S. lastchild. innertext ;"

_ Dopostback (BTN ,'');

}

}

...... (Omitted)

Function pageunload (){

// Release the event Processor

If (clickrowhandler)

$ Removehandler ($ get ('rssnamelist'), "click", clickrowhandler );

Clickrowhandler = NULL;

}

Here, we first use the global method $ addhandler to turn the event processor clickrowhandler off and smell the Click Event of the listview control rssnamelist. Next, we will analyze the programming of this event processor function. At the beginning, ev.tar get points to listview rssnamelist. When the program executes the if Condition Statement, the variable s points to searchresults_itemtemplate (where the database records are displayed ). Now, we can use the idx variable to retrieve the current value of the record index and obtain any field values we want to retrieve (here, we are only interested in the last field rss_url ).

The situation has become increasingly complex-how can we dynamically specify RSS URLs for the rssdatasource control (note that this is a third-party server-side Data Control? Here, my solution is to turn to the method "_ dopostback ". According to the analysis in this article, we generally cannot dynamically bind rssdatasource to the acccordion control in a web service method. In this way, we can only find another way-codefile file ajaxrssreader. aspx. CS. Experiments show that in this background file, we can achieve the above goal-dynamically bind rssdatasource to acccordion (note that we cannot implement this binding in the client Javascript script, because this is a server-side data source control ). This is exactly why we resort to the _ dopostback method. With this method, we can indirectly implement communication between client controls and server controls.

To achieve the above goal, we need to create two "dummy ASP. NET controls (this is just my idea)-one button control and one Textbox Control. Since they must not be displayed at runtime, we set their dimensions to the minimum value (the width and height are all 1 pixel X ), set the background to light gray (which corresponds to the background color of "buttonarea" in the button area ).

[Note] in the experiment, I found that we could not set the visible attribute of the two "Dummy" controls to false; otherwise, a runtime error would occur.

Next, through the call method "_ dopostback", we indirectly call the server-side Click Event processor-dummysrvbtn_click (Object sender, eventargs E) (this function is located in the codefile file ajaxrssreader. aspx. in CS ). The following is the source code of the function.

List 9

protected void dummySrvBtn_Click(object sender, EventArgs e)

{

RssDataSource1.Url = txtRssUrl2.Text.Trim();

Accordion1.DataSourceID = "RssDataSource1";

Accordion1.DataBind();

}

Now, let's skip the analysis of this Code.

Then, the value of the field rss_url is assigned to the associated HTML input element txtrssurl2.clientid (corresponding to ASP. net server-side Id-txtRssUrl2) attribute value (corresponding to the corresponding server-side text attribute), we have successfully achieved the data from the client to the server side.

Finally, calling the method "_ dopostback" will inevitably lead to a refresh of the entire page-which is fundamentally contrary to the basic idea of Ajax. This is why we introduced the ASP. NET Ajax Server Control updatepanel, which surrounded the corresponding zone of the accordion control. Note: here we use the asyncpostbacktrigger trigger of updatepanel to trigger the updatepanel refresh operation by making the Click Event of the "dummysrvbtn" button. The following section describes the relevant HTML code.

List 10

<Asp: updatepanel id = "updatepanel1" runat = "server">

<Triggers>

<Asp: asyncpostbacktrigger controlid = "dummysrvbtn" eventname = "click"/>

</Triggers>

<Contenttemplate>

<Ajaxtoolkit: accordion id = "accordion1" cssclass = "myaccordion" headercssclass = "Header"

............ (Omitted)

Therefore, we introduced the Server Control updateprogress to work with the updatepanel control for a more friendly user experience.

Maybe the above solution is too ugly. Therefore, I hope that readers can further improve it.

Show Channel content

So far, this step has become quite simple. In fact, we have achieved this goal in source code 9 above. By dynamically assigning values to the property URL of the control rssdatasource1, binding it to the control accordion1, and then calling the method databind of accordion1, we finally display the webpage content of the channel based on the channel title information clicked by the user.

[Note] First, I did not find any examples to realize the dynamic assignment of the rssdatasource control through Google searching the Internet. Second, because some RSS contents may not contain the author field, I simply comment out this field in the <contenttemplate> block of the accordion control.

Finally, let's take a look at our final results, as shown in Figure 5.

498) This. style. width = 498; ">

Figure 5: Sample runtime snapshot after the user clicks "Scott Guthrie" on the RSS Channel

Vi. Summary

In this article, we developed a simple RSS reader program using the Microsoft ASP. NET Ajax framework. As a demo program, we only want to explore the basic usage of this framework; therefore, there are still many areas to be improved:

1) only use ASP. NET Ajax Client technology for development
2) Further explore other methods for communication between the client and the server
3) use the terminal tview control to replace the ASP. NET Ajax Control Toolkit control accordion used in this article to display the RSS channel content.
4) use the client control validator-regexvalidator to verify the RSS feed address entered by the user more strictly.
5) further supports deletion/modification of RSS channel information at runtime
6) add additional types of RSS and provide users with classification management
.........

If you are interested, you can follow these tips to further improve the example in this article.
Address: http://developer.51cto.com/art/200708/53158_3.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.