windows8 AtomPub协议

AtomPub协议示例
这个示例演示了如何获取、创建、更新和删除从网站上使用窗口运行时执行AtomPub标准。这个样品中所提供的c#编程语言,需要一些经验与网络编程。

 

   partial  class MainPage
    {
         //  The default values for the WordPress site
         private  const  string DefaultBaseUri =  " http://<Your Wordpress Site>.wordpress.com/ ";
         private  const  string DefaultUser =  "";
         private  const  string DefaultPassword =  "";

         //  The default Service Document and Edit 'URIs' for WordPress
         private  const  string DefaultEditUri =  " ./wp-app.php/posts ";
         private  const  string DefaultServiceDocUri =  " ./wp-app.php/service ";
         private  const  string DefaultFeedUri =  " ./?feed=atom ";

         private AtomPubClient client;
         private SyndicationFeed currentFeed;
         private  int currentItemIndex;

         private Action displayCurrentItem;

         private SyndicationItem CurrentItem
        {
             get
            {
                 if (currentFeed !=  null && currentItemIndex >=  0
                    && currentItemIndex < currentFeed.Items.Count)
                {
                     return currentFeed.Items[currentItemIndex];
                }
                 return  null;
            }
        }

         public MainPage()
        {
            InitializeComponent();

            ScenarioList.SelectionChanged +=  new SelectionChangedEventHandler(ScenarioList_SelectionChanged);

             //  Starting scenario is the first or based upon a previous selection
            ListBoxItem startingScenario =  null;
             if (SuspensionManager.SessionState.ContainsKey( " SelectedScenario "))
            {
                String selectedScenarioName = SuspensionManager.SessionState[ " SelectedScenario "as  string;
                startingScenario =  this.FindName(selectedScenarioName)  as ListBoxItem;
            }

            ScenarioList.SelectedItem = startingScenario !=  null ? startingScenario : Scenario1;

            Scenario1Init();
            Scenario2Init();
            Scenario3Init();
            Scenario4Init();

            ServiceAddressField.Text = DefaultBaseUri;
            UserNameField.Text = DefaultUser;
            PasswordField.Password = DefaultPassword;

            ApplicationView.GetForCurrentView().ViewStateChanged
                +=  new TypedEventHandler<ApplicationView, ApplicationViewStateChangedEventArgs>(MainPage_ViewStateChanged);
        }

         void DisplayProperties_OrientationChanged( object sender)
        {
             if (DisplayProperties.CurrentOrientation == DisplayOrientations.Portrait
                || DisplayProperties.CurrentOrientation == DisplayOrientations.PortraitFlipped)
            {
                VisualStateManager.GoToState( this" Portrait "false);
            }
        }

         void MainPage_ViewStateChanged(ApplicationView sender, ApplicationViewStateChangedEventArgs args)
        {
             switch (args.ViewState)
            {
                 case ApplicationViewState.Filled:
                    VisualStateManager.GoToState( this" Filled "false);
                     break;
                 case ApplicationViewState.FullScreenLandscape:
                    VisualStateManager.GoToState( this" FullScreenLandscape "false);
                     break;
                 case ApplicationViewState.Snapped:
                    VisualStateManager.GoToState( this" Snapped "false);
                     break;
                 case ApplicationViewState.FullScreenPortrait:
                    VisualStateManager.GoToState( this" FullScreenPortrait "false);
                     break;
                 default:
                     break;
            }
        }


         #region Scenario Specific Code

         void Scenario1Init()
        {
        }

         private async  void Scenario1Start_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();

                 //  Note that this feed is public by default and will not require authentication.
                
//  We will only get back a limited use feed, without information about editing.
                Uri resourceUri =  new Uri(ServiceAddressField.Text.Trim() + DefaultFeedUri);

                Scenario1OutputField.Text +=  " Fetching resource:  " + resourceUri +  " \r\n ";

                currentFeed = await client.RetrieveFeedAsync(resourceUri);
                currentItemIndex =  0;

                Scenario1OutputField.Text +=  " Complete\r\n ";

                Scenario1DisplayCurrentItem();
            }
             catch (Exception ex)  //  For Debugging
            {
                Scenario1OutputField.Text += ex +  " \r\n ";
            }
        }

         void Scenario1DisplayCurrentItem()
        {
             if (CurrentItem !=  null)
            {
                ISyndicationText title = CurrentItem.Title;
                Scenario1TitleField.Text = title !=  null ?  //  WebUtility.HtmlDecode  //  TODO: Not in the current build
                 (title.Text) :  " (no title) ";
                ISyndicationText value = CurrentItem.Content ?? CurrentItem.Summary;
                Scenario1WebView.NavigateToString(value !=  null ? value.Text :  " (no value) ");
            }
        }

         void Scenario1Reset()
        {
            currentFeed =  null;
            Scenario1OutputField.Text =  string.Empty;
            Scenario1TitleField.Text =  string.Empty;
            Scenario1WebView.NavigateToString( " <HTML></HTML> ");
        }

         void Scenario2Init()
        {
        }

         private async  void Scenario2Start_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();
                Uri serviceUri =  new Uri(ServiceAddressField.Text.Trim() + DefaultServiceDocUri);

                Scenario2OutputField.Text +=  " Fetching Service document:  " + serviceUri +  " \r\n ";

                Uri resourceUri = await FindEditUri(serviceUri);
                 //  The result here is usually the same as:
                
//  Uri resourceUri = new Uri(ServiceAddressField.Text.Trim() + DefaultEditUri);

                Scenario2OutputField.Text +=  " Uploading Post:  " + resourceUri +  " \r\n ";

                SyndicationItem item =  new SyndicationItem();
                item.Title =  new SyndicationText(Scenario2TitleField.Text, SyndicationTextType.Text);
                item.Content =  new SyndicationContent(Scenario2BodyField.Text, SyndicationTextType.Html);

                SyndicationItem result = await client.CreateResourceAsync(resourceUri, item.Title.Text, item);

                Scenario2OutputField.Text +=  " Posted at  " + result.ItemUri +  " \r\n ";

                Scenario2OutputField.Text +=  " Complete\r\n ";
            }
             catch (Exception ex)  //  For debugging
            {
                Scenario2OutputField.Text += ex +  " \r\n ";
            }
        }

         //  Read the service document to find the URI we're suposed to use when uploading content.
         private async Task<Uri> FindEditUri(Uri serviceUri)
        {
            ServiceDocument serviceDocument = await client.RetrieveServiceDocumentAsync(serviceUri);

             foreach (Workspace workspace  in serviceDocument.Workspaces)
            {
                 foreach (ResourceCollection collection  in workspace.Collections)
                {
                     if ( string.Join( " ; ", collection.Accepts) ==  " application/atom+xml;type=entry ")
                    {
                         return collection.Uri;
                    }
                }
            }

             throw  new ArgumentException( " Edit Uri not found in service document ");
        }

         void Scenario2Reset()
        {
            Scenario2OutputField.Text =  string.Empty;
        }

         void Scenario3Init()
        {
        }

         //  Download a feed
         private async  void Scenario3Start_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();

                 //  If we retrieve the feed via the Edit uri then we will be logged in and will be
                
//  able to modify/delete the resource.
                Uri resourceUri =  new Uri(ServiceAddressField.Text.Trim() + DefaultEditUri);

                Scenario3OutputField.Text +=  " Fetching feed:  " + resourceUri +  " \r\n ";

                currentFeed = await client.RetrieveFeedAsync(resourceUri);
                currentItemIndex =  0;

                Scenario3OutputField.Text +=  " Got feed\r\n ";

                Scenario3OutputField.Text +=  " Title:  " + currentFeed.Title.Text +  " \r\n ";

                 if (CurrentItem !=  null)
                {
                    Scenario3DisplayCurrentItem();

                    Scenario3OutputField.Text +=  " EditUri:  " + CurrentItem.EditUri +  " \r\n ";
                }

                Scenario3OutputField.Text +=  " Complete\r\n ";
            }
             catch (Exception ex)  //  For Debugging
            {
                Scenario3OutputField.Text += ex +  " \r\n ";
            }
        }

         //  Delete the current entry
         private async  void Scenario3Delete_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();

                 if (CurrentItem ==  null)
                {
                    Scenario3OutputField.Text +=  " No item currently displayed, please download a feed first.\r\n ";
                     return;
                }

                Scenario3OutputField.Text +=  " Deleting item:  " + CurrentItem.EditUri +  " \r\n ";

                await client.DeleteResourceItemAsync(CurrentItem);

                Scenario3OutputField.Text +=  " Complete\r\n ";

                 //  Our feed is now out of date.  Re-fetch the feed before deleting something else.
                currentFeed =  null;
                Scenario3TitleField.Text =  string.Empty;
                Scenario3WebView.NavigateToString( " <HTML></HTML> ");
            }
             catch (Exception ex)  //  For Debugging
            {
                Scenario3OutputField.Text += ex +  " \r\n ";
            }
        }

         void Scenario3DisplayCurrentItem()
        {
             if (CurrentItem !=  null)
            {
                ISyndicationText title = CurrentItem.Title;
                Scenario3TitleField.Text = title !=  null ?  //  WebUtility.HtmlDecode  //  TODO: Not in the current build
                 (title.Text) :  " (no title) ";

                ISyndicationText value = CurrentItem.Content ?? CurrentItem.Summary;
                Scenario3WebView.NavigateToString(value !=  null ? value.Text :  " (no value) ");
            }
        }

         void Scenario3Reset()
        {
            currentFeed =  null;
            Scenario3OutputField.Text =  string.Empty;
            Scenario3TitleField.Text =  string.Empty;
            Scenario3WebView.NavigateToString( " <HTML></HTML> ");
        }

         void Scenario4Init()
        {
        }

         private async  void Scenario4Start_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();

                 //  If we retrieve the feed via the Edit uri then we will be logged in and be
                
//  able to modify/delete the resource.
                Uri resourceUri =  new Uri(ServiceAddressField.Text.Trim() + DefaultEditUri);

                Scenario4OutputField.Text +=  " Fetching feed:  " + resourceUri +  " \r\n ";

                currentFeed = await client.RetrieveFeedAsync(resourceUri);
                currentItemIndex =  0;

                Scenario4OutputField.Text +=  " Got feed\r\n ";

                Scenario4OutputField.Text +=  " Title:  " + currentFeed.Title.Text +  " \r\n ";

                 if (CurrentItem !=  null)
                {
                    Scenario4DisplayCurrentItem();

                    Scenario4OutputField.Text +=  " EditUri:  " + CurrentItem.EditUri +  " \r\n ";
                }

                Scenario4OutputField.Text +=  " Complete\r\n ";
            }
             catch (Exception ex)  //  For Debugging
            {
                Scenario4OutputField.Text += ex +  " \r\n ";
            }
        }

         //  Update the current entry
         private async  void Scenario4Save_Click( object sender, RoutedEventArgs e)
        {
             try
            {
                UpdateClient();

                 if (CurrentItem ==  null)
                {
                    Scenario4OutputField.Text +=  " No item currently displayed, please download a feed first.\r\n ";
                     return;
                }

                Scenario4OutputField.Text +=  " Updating item:  " + CurrentItem.EditUri +  " \r\n ";

                 //  Update the item
                SyndicationItem updatedItem =  new SyndicationItem();
                updatedItem.Title =  new SyndicationText(Scenario4TitleField.Text, SyndicationTextType.Text);
                updatedItem.Content =  new SyndicationContent(Scenario4BodyField.Text, SyndicationTextType.Html);

                await client.UpdateResourceAsync(CurrentItem.EditUri, updatedItem);

                Scenario4OutputField.Text +=  " Complete\r\n ";
            }
             catch (Exception ex)  //  For Debugging
            {
                Scenario4OutputField.Text += ex +  " \r\n ";
            }
        }

         void Scenario4DisplayCurrentItem()
        {
             if (CurrentItem !=  null)
            {
                ISyndicationText title = CurrentItem.Title;
                Scenario4TitleField.Text = title !=  null ?  //  WebUtility.HtmlDecode  //  TODO: Not in the current build
                  (title.Text) :  " (no title) ";

                ISyndicationText value = CurrentItem.Content ?? CurrentItem.Summary;
                Scenario4BodyField.Text = value !=  null ? value.Text :  " (no value) ";
            }
        }

         void Scenario4Reset()
        {
            currentFeed =  null;
            Scenario4OutputField.Text =  string.Empty;
            Scenario4TitleField.Text =  string.Empty;
            Scenario4BodyField.Text =  string.Empty;
        }

         #endregion

         private  void UpdateClient()
        {
            client =  new AtomPubClient();
            client.BypassCacheOnRetrieve =  true;
             //  Assume the credentials have changed
            client.ServerCredential =  new PasswordCredential()
            {
                UserName = UserNameField.Text,
                Password = PasswordField.Password
            };
        }

         private  void PreviousItemButton_Click( object sender, RoutedEventArgs e)
        {
             if (currentFeed !=  null && currentItemIndex >  0)
            {
                currentItemIndex--;
                displayCurrentItem();
            }
        }

         private  void NextItemButton_Click( object sender, RoutedEventArgs e)
        {
             if (currentFeed !=  null && currentItemIndex < currentFeed.Items.Count -  1)
            {
                currentItemIndex++;
                displayCurrentItem();
            }
        }

         void ScenarioList_SelectionChanged( object sender, SelectionChangedEventArgs e)
        {
            ResetAll();
             if (ScenarioList.SelectedItem == Scenario1)
            {
                Scenario1Input.Visibility = Visibility.Visible;
                Scenario1Output.Visibility = Visibility.Visible;
                displayCurrentItem = Scenario1DisplayCurrentItem;
            }
             else  if (ScenarioList.SelectedItem == Scenario2)
            {
                Scenario2Input.Visibility = Visibility.Visible;
                Scenario2Output.Visibility = Visibility.Visible;
                displayCurrentItem =  null;
            }
             else  if (ScenarioList.SelectedItem == Scenario3)
            {
                Scenario3Input.Visibility = Visibility.Visible;
                Scenario3Output.Visibility = Visibility.Visible;
                displayCurrentItem = Scenario3DisplayCurrentItem;
            }
             else  if (ScenarioList.SelectedItem == Scenario4)
            {
                Scenario4Input.Visibility = Visibility.Visible;
                Scenario4Output.Visibility = Visibility.Visible;
                displayCurrentItem = Scenario4DisplayCurrentItem;
            }

             if (ScenarioList.SelectedItem !=  null)
            {
                ListBoxItem selectedListBoxItem = ScenarioList.SelectedItem  as ListBoxItem;
                SuspensionManager.SessionState[ " SelectedScenario "] = selectedListBoxItem.Name;
            }
        }

         public  void ResetAll()
        {
            displayCurrentItem =  null;

            Scenario1Input.Visibility = Visibility.Collapsed;
            Scenario1Output.Visibility = Visibility.Collapsed;
            Scenario1Reset();
            Scenario2Input.Visibility = Visibility.Collapsed;
            Scenario2Output.Visibility = Visibility.Collapsed;
            Scenario2Reset();
            Scenario3Input.Visibility = Visibility.Collapsed;
            Scenario3Output.Visibility = Visibility.Collapsed;
            Scenario3Reset();
            Scenario4Input.Visibility = Visibility.Collapsed;
            Scenario4Output.Visibility = Visibility.Collapsed;
            Scenario4Reset();
        }

        async  void Footer_Click( object sender, RoutedEventArgs e)
        {
            await Windows.System.Launcher.LaunchUriAsync( new Uri(((HyperlinkButton)sender).Tag.ToString()));
        }


完整示例

/Files/risk/windows8/AtomPub协议sample.rar 

你可能感兴趣的:(windows)