Use Windows 8 to develop Metro style application 3

Source: Internet
Author: User

Next, let's start the development of our Metro-style applications.

----------------------------------- I am a gorgeous split line -----------------------------------------

9. Get the data to the application
A) since the application we created can download data from the Internet, we can write code to place the blog information feed in it.
My blog displays the complete text of the article with RSS. The blog data we want to display in the reader application is
The title, author, date, and content of each latest blog article. First, we need to download the data of each article.
Fortunately, Windows runtime contains a group of classes that can process a lot of information feed data for us.
You can find these classes in the windows. Web. syndication namespace. You can directly use these classes to display data in the UI.
However, in my blog reader, I will create my own data class.
B) Add a new class file to the project.
Select "project"> "add class ". The "add project" dialog box is displayed.
Enter the name of the class file feeddata.
Click Add ".
C) the code is as follows:

/// <Summary> /// the feeddata class contains information about RSS or atom feeds. // </Summary> public class feeddata {Public String title {Get; set ;} public String description {Get; set;} public datetime pubdate {Get; set;} private list <feeditem> items = new list <feeditem> (); public list <feeditem> items {get {return items ;}}}

 

The feeddata class contains the feeditem class, And the feeditem class contains information about a single blog article contained in the information feed,
The feeditem class code is as follows:

/// <Summary> /// the feeditem class holds the information of a single blog article contained in the information abstract. /// </Summary> public class feeditem {Public String title {Get; set;} Public String author {Get; set;} Public String content {Get; set;} public datetime pubdate {Get; set;} public URI link {Get; set ;}}

 

With the above two basic data classes, we can prepare the RSS data source and create a new class: feeddatasource. The Code is as follows:

/// <Summary> /// the opportunity of the feeddatasource class containing the information feed and the method for retrieving the information feed from the network /// </Summary> public class feeddatasource {private observablecollection <feeddata> feeds = new observablecollection <feeddata> (); public observablecollection <feeddata> feeds {get {return feeds;} public async task getfeedsasync () {task <feeddata> feed = getfeedasync ("http://feed.cnblogs.com/blog/u/118198/rss "); // if you use Use the await keyword, // The code for retrieving the information feed asynchronously is similar to the code used for retrieving the information feed synchronously. // you can only use the await keyword in the method defined as async. feeds. add (await feed);} private async task <feeddata> getfeedasync (string feedurl) {syndicationclient client = new syndicationclient (); Uri feeduri = new uri (feedurl ); try {// The await keyword here will tell the compiler to automatically execute multiple types of processing for us in the background. // The Compiler counts the rest of the method after this call as the callback to be executed after this call is returned. // It then returns the control to the call SESSION (usually the UI session) to keep the application responding. // At this time, the task (A feeddata object) that indicates the final output of this method will be returned to the caller. // When retrievefeedasync returns the syndicationfeed containing the data we need, // The remaining code in our method will be executed. It is important that the system executes the code in the same session context from which we made the original call // (ui session, therefore, you do not have to worry about using the scheduler when updating the UI in this Code. // After the syndicationfeed is retrieved, copy the required parts to the feeddata and feeditem data classes. Syndicationfeed = await client. retrievefeedasync (feeduri); // This code is executed after retrievefeedasync returns the syndicationfeed. // process it and copy the data we want into our feeddata and feeditem classes. feeddata = new feeddata (); feeddata. title = feed. title. text; If (feed. subtitle. text! = NULL) {feeddata. description = feed. subtitle. text;} feeddata. pubdate = feed. items [0]. publisheddate. datetime; foreach (VAR item in feed. items) {feeditem = new feeditem (); feeditem. title = item. title. text; feeditem. pubdate = item. publisheddate. datetime; feeditem. author = item. authors [0]. name. tostring (); If (feed. sourceformat = syndicationformat. atom10) {feeditem. content = item. content. tex T;} else if (feed. sourceformat = syndicationformat. rss20) {feeditem. content = item. content. text; feeditem. link = item. links [0]. uri;} feeddata. items. add (feeditem) ;}// when we execute the return statement, we do not actually return the feeddata object. // Remember, when the method is immediately followed by the await statement returned to the calling program, a task indicating the final output result of the method is returned. // Now, we have finally obtained the desired result. // Return feeddata; provide the feeddata object as the method result to the task waiting for the object. // Feeds. Add (await feed) in the getfeedsasync method is waiting for the task. // When the task obtains the waiting feeddata result, the code execution continues. // feeddata is added to the feeddatasource. Feeds collection. Return feeddata;} catch (exception) {return NULL ;}}}

 

The feeddatasource class applies a new class task of. net4. C #5.0 adds the async and await keywords. For detailed usage, see msdn.

10. Retrieve Information Summary Data
After preparing the data class for storing our data, let's go back and download these blog feeds.
The windows. Web. syndication. syndicationclient class can retrieve completely parsed RSS or atom information feeds,
Therefore, we don't have to worry about parsing XML, but we can continue to build more interesting parts of the application.
The syndicationclient class provides only one method for retrieving information feeds, and is asynchronous.
Asynchronous programming models are often used in Windows runtime to help applications maintain responses.
Fortunately, the program has handled many complicated problems that may occur when using asynchronous methods for us.
11. Use Data in the Application
To use the data in our application, we created a static instance of the data source in APP. XAML. CS/VB.
We name the instance datasource.
The Code is as follows:

  /// <summary>    /// Provides application-specific behavior to supplement the default Application class.    /// </summary>    sealed partial class App : Application    {        public static FeedDataSource DataSource;        /// <summary>        /// Initializes the singleton application object.  This is the first line of authored code        /// executed, and as such is the logical equivalent of main() or WinMain().        /// </summary>        public App()        {            this.InitializeComponent();            this.Suspending += OnSuspending;            DataSource = new FeedDataSource();        }        /// <summary>        /// Invoked when the application is launched normally by the end user.  Other entry points        /// will be used when the application is launched to open a specific file, to display        /// search results, and so forth.        /// </summary>        /// <param name="args">Details about the launch request and process.</param>        protected override void OnLaunched(LaunchActivatedEventArgs args)        {            // Do not repeat app initialization when already running, just ensure that            // the window is active            if (args.PreviousExecutionState == ApplicationExecutionState.Running)            {                Window.Current.Activate();                return;            }            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)            {                //TODO: Load state from previously suspended application            }            // Create a Frame to act navigation context and navigate to the first page            var rootFrame = new Frame();            if (!rootFrame.Navigate(typeof(MainPage)))            {                throw new Exception("Failed to create initial page");            }            // Place the frame in the current Window and ensure that it is active            Window.Current.Content = rootFrame;            Window.Current.Activate();        }        /// <summary>        /// Invoked when application execution is being suspended.  Application state is saved        /// without knowing whether the application will be terminated or resumed with the contents        /// of memory still intact.        /// </summary>        /// <param name="sender">The source of the suspend request.</param>        /// <param name="e">Details about the suspend request.</param>        private void OnSuspending(object sender, SuspendingEventArgs e)        {            var deferral = e.SuspendingOperation.GetDeferral();            //TODO: Save application state and stop any background activity            deferral.Complete();        }    }

 

The page template contains an onnavigatedto method alternative in its hidden code file.
We place the code in this method to obtain the feeddatasource instance of the application and obtain the source.
First, we add the async keyword to the method declaration because we use the await keyword in the method.
When you navigate to the page, check to see if the feeddatasource already contains the source. If not,
We call the feeddatasource. getfeedsasync method. Then, set the datacontext of the page to the first source.
The following is the code for mainpage. XAML. CS/vB:

        /// <summary>        /// Invoked when this page is about to be displayed in a Frame.        /// </summary>        /// <param name="e">Event data that describes how this page was reached.  The Parameter        /// property is typically used to configure the page.</param>        protected override async void OnNavigatedTo(NavigationEventArgs e)        {            FeedDataSource feedDataSource = App.DataSource;            if (feedDataSource.Feeds.Count==0)            {               await feedDataSource.GetFeedsAsync();            }            DataContext = (feedDataSource.Feeds).First();        }

 

 

To be continued, please wait ....

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.