在asp.net中使用异步同步rss
| 有的时候我们需要在网页里读取论坛的信息,在传统ASP的时候我们使用的是JS或者是IFRAME,这两种方式都不是很方便,而且对搜索引擎不友好。现在有了.Net,我们有了另一种方式。 要求:论坛需要提供RSS支持。 代码如下: | 
 1    task class#region task class
  1    task class#region task class 2    //这是一个任务类,执行具体的任务
  2    //这是一个任务类,执行具体的任务 3    public class RssAsyncTask
  3    public class RssAsyncTask 4    {
  4    { 5        private String _rssContent;
  5        private String _rssContent; 6        private AsyncTaskDelegate _dlgt;
  6        private AsyncTaskDelegate _dlgt; 7        private string rssUrl;
  7        private string rssUrl; 8        private bool _success;
  8        private bool _success; 9
  9 10        public bool IsSuccess
 10        public bool IsSuccess 11        {
 11        { 12            get
 12            get 13            {
 13            { 14                return _success;
 14                return _success; 15            }
 15            } 16        }
 16        } 17
 17 18        public RssAsyncTask(string rssUrl)
 18        public RssAsyncTask(string rssUrl) 19        {
 19        { 20            this.rssUrl = rssUrl;
 20            this.rssUrl = rssUrl; 21        }
 21        } 22
 22 23        // Create delegate.
 23        // Create delegate. 24        protected delegate void AsyncTaskDelegate();
 24        protected delegate void AsyncTaskDelegate(); 25
 25 26        public String GetRssContent()
 26        public String GetRssContent() 27        {
 27        { 28            return _rssContent;
 28            return _rssContent; 29        }
 29        } 30        public void DoTheAsyncTask()
 30        public void DoTheAsyncTask() 31        {
 31        { 32            // Introduce an artificial delay to simulate a delayed
 32            // Introduce an artificial delay to simulate a delayed  33            // asynchronous task. Make this greater than the
 33            // asynchronous task. Make this greater than the  34            // AsyncTimeout property.
 34            // AsyncTimeout property. 35            WebClient wc = new WebClient();
 35            WebClient wc = new WebClient(); 36            try
 36            try 37            {
 37            { 38                _rssContent = wc.DownloadString(rssUrl);
 38                _rssContent = wc.DownloadString(rssUrl); 39                _success = true;
 39                _success = true; 40            }
 40            } 41            catch (Exception e)
 41            catch (Exception e) 42            {
 42            { 43                _rssContent = e.Message;
 43                _rssContent = e.Message; 44            }
 44            } 45            finally
 45            finally 46            {
 46            { 47                wc.Dispose();
 47                wc.Dispose(); 48            }
 48            } 49            //Thread.Sleep(TimeSpan.FromSeconds(5.0));
 49            //Thread.Sleep(TimeSpan.FromSeconds(5.0)); 50        }
 50        } 51
 51 52        // Define the method that will get called to
 52        // Define the method that will get called to 53        // start the asynchronous task.
 53        // start the asynchronous task. 54        public IAsyncResult OnBegin(object sender, EventArgs e,
 54        public IAsyncResult OnBegin(object sender, EventArgs e, 55            AsyncCallback cb, object extraData)
 55            AsyncCallback cb, object extraData) 56        {
 56        { 57            //_rssContent = "Beginning async task.";
 57            //_rssContent = "Beginning async task."; 58
 58 59            _dlgt = new AsyncTaskDelegate(DoTheAsyncTask);
 59            _dlgt = new AsyncTaskDelegate(DoTheAsyncTask); 60            IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);
 60            IAsyncResult result = _dlgt.BeginInvoke(cb, extraData); 61
 61 62            return result;
 62            return result; 63        }
 63        } 64
 64 65        // Define the method that will get called when
 65        // Define the method that will get called when 66        // the asynchronous task is ended.
 66        // the asynchronous task is ended. 67        public void OnEnd(IAsyncResult ar)
 67        public void OnEnd(IAsyncResult ar) 68        {
 68        { 69            //_rssContent = "Asynchronous task completed.";
 69            //_rssContent = "Asynchronous task completed."; 70            _dlgt.EndInvoke(ar);
 70            _dlgt.EndInvoke(ar); 71        }
 71        } 72
 72 73        // Define the method that will get called if the task
 73        // Define the method that will get called if the task 74        // is not completed within the asynchronous timeout interval.
 74        // is not completed within the asynchronous timeout interval. 75        public void OnTimeout(IAsyncResult ar)
 75        public void OnTimeout(IAsyncResult ar) 76        {
 76        { 77            _rssContent = "Ansynchronous task failed to complete " +
 77            _rssContent = "Ansynchronous task failed to complete " + 78                "because it exceeded the AsyncTimeout parameter.";
 78                "because it exceeded the AsyncTimeout parameter."; 79        }
 79        } 80    }
 80    } 81    #endregion
 81    #endregion 82
 82 83    //一个自定义的控件,继承自另一个自定义控件。
 83    //一个自定义的控件,继承自另一个自定义控件。 84    public class RArticle
 84    public class RArticle 85        : LPanel
 85        : LPanel 86    {
 86    { 87        propertiesproperties
 87        propertiesproperties 104
104 105        RssAsyncTask task;
105        RssAsyncTask task; 106        protected override void OnInit(EventArgs e)
106        protected override void OnInit(EventArgs e) 107        {
107        { 108            base.OnInit(e);
108            base.OnInit(e); 109            task = new RssAsyncTask(this.rssUrl);
109            task = new RssAsyncTask(this.rssUrl); 110            PageAsyncTask asyncTask = new PageAsyncTask(task.OnBegin, task.OnEnd, task.OnTimeout, null);
110            PageAsyncTask asyncTask = new PageAsyncTask(task.OnBegin, task.OnEnd, task.OnTimeout, null); 111
111 112            Page.RegisterAsyncTask(asyncTask);
112            Page.RegisterAsyncTask(asyncTask); 113            Page.ExecuteRegisteredAsyncTasks();
113            Page.ExecuteRegisteredAsyncTasks(); 114        }
114        } 115
115 116        static Random r = new Random();
116        static Random r = new Random(); 117        protected override void Render(System.Web.UI.HtmlTextWriter writer)
117        protected override void Render(System.Web.UI.HtmlTextWriter writer) 118        {
118        { 119            string rssContent = task.GetRssContent();
119            string rssContent = task.GetRssContent(); 120            XmlDocument doc = null;
120            XmlDocument doc = null; 121            if (task.IsSuccess)
121            if (task.IsSuccess) 122            {
122            { 123                doc = new XmlDocument();
123                doc = new XmlDocument(); 124                doc.LoadXml(rssContent);
124                doc.LoadXml(rssContent); 125
125 126                this.Title = doc.SelectSingleNode("rss/channel/title").InnerText;
126                this.Title = doc.SelectSingleNode("rss/channel/title").InnerText; 127                this.TitleNavigateUrl = doc.SelectSingleNode("rss/channel/link").InnerText;
127                this.TitleNavigateUrl = doc.SelectSingleNode("rss/channel/link").InnerText; 128                this.ShowTitle = true;
128                this.ShowTitle = true; 129            }
129            } 130            base.RenderBegin(writer);
130            base.RenderBegin(writer); 131
131 132            writer.WriteBeginTag("div");
132            writer.WriteBeginTag("div"); 133            writer.WriteAttribute("class", "child2");
133            writer.WriteAttribute("class", "child2"); 134            Right(writer);
134            Right(writer); 135            writer.WriteBeginTag("ul");
135            writer.WriteBeginTag("ul"); 136            Right(writer);
136            Right(writer); 137
137 138            if (doc != null)
138            if (doc != null) 139            {
139            { 140                success#region success
140                success#region success 141
141 142                XmlNodeList items = doc.SelectNodes("rss/channel/item");
142                XmlNodeList items = doc.SelectNodes("rss/channel/item"); 143                List<XmlNode> nodes = new List<XmlNode>();
143                List<XmlNode> nodes = new List<XmlNode>(); 144                foreach (XmlNode node in items)
144                foreach (XmlNode node in items) 145                    nodes.Add(node);
145                    nodes.Add(node); 146
146 147                //使用范型进行日期的倒序排列
147                //使用范型进行日期的倒序排列 148                nodes.Sort(new Comparison<XmlNode>(delegate(XmlNode n1, XmlNode n2)
148                nodes.Sort(new Comparison<XmlNode>(delegate(XmlNode n1, XmlNode n2) 149                {
149                { 150                    DateTime d1 = DateTime.Parse(n1.SelectSingleNode("pubDate").InnerText);
150                    DateTime d1 = DateTime.Parse(n1.SelectSingleNode("pubDate").InnerText); 151                    DateTime d2 = DateTime.Parse(n2.SelectSingleNode("pubDate").InnerText);
151                    DateTime d2 = DateTime.Parse(n2.SelectSingleNode("pubDate").InnerText); 152                    TimeSpan ts = d2 - d1;
152                    TimeSpan ts = d2 - d1; 153                    return (int)ts.TotalSeconds;
153                    return (int)ts.TotalSeconds; 154                }));
154                })); 155
155 156                for (int i = 0; i < maxRecordNumber; i++)
156                for (int i = 0; i < maxRecordNumber; i++) 157                {
157                { 158                    XmlNode node = nodes[i];
158                    XmlNode node = nodes[i]; 159                    writer.WriteBeginTag("li");
159                    writer.WriteBeginTag("li"); 160                    Right(writer);
160                    Right(writer); 161                    writer.WriteBeginTag("a");
161                    writer.WriteBeginTag("a"); 162                    writer.WriteAttribute("target", "_blank");
162                    writer.WriteAttribute("target", "_blank"); 163                    writer.WriteAttribute("href", node.SelectSingleNode("link").InnerText);
163                    writer.WriteAttribute("href", node.SelectSingleNode("link").InnerText); 164                    Right(writer);
164                    Right(writer); 165                    writer.Write(node.SelectSingleNode("title").InnerText);
165                    writer.Write(node.SelectSingleNode("title").InnerText); 166                    writer.WriteEndTag("a");
166                    writer.WriteEndTag("a"); 167                    writer.WriteEndTag("li");
167                    writer.WriteEndTag("li"); 168                }
168                } 169
169 170                #endregion
170                #endregion 171            }
171            } 172            else
172            else 173            {
173            { 174                writer.WriteBeginTag("pre");
174                writer.WriteBeginTag("pre"); 175                Right(writer);
175                Right(writer); 176                writer.Write(task.GetRssContent());
176                writer.Write(task.GetRssContent()); 177                writer.WriteEndTag("pre");
177                writer.WriteEndTag("pre"); 178            }
178            } 179
179 180            writer.WriteEndTag("ul");
180            writer.WriteEndTag("ul"); 181            writer.WriteEndTag("div");
181            writer.WriteEndTag("div"); 182
182 183            RenderChildren(writer);
183            RenderChildren(writer); 184
184 185            base.RenderEnd(writer);
185            base.RenderEnd(writer); 186        }
186        } 187    }
187    } 188
188
使用方法:
一、注册控件
CODE:
<%@ Register Assembly="Controls" Namespace="Limited.Controls" TagPrefix="lm" %>
二、调用CODE:
<lm:RArticle ID="RArticle1" runat="server" MaxRecordNumber="10" RssUrl="http://bbs.5inet.net/rss.aspx" />
为了简便起见,本程序就没有使用缓存之类的技术了,如有必要,请自行添加。 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号