410 likes | 514 Views
BCIS 4650 Visual Programming for Business Applications. Data Binding #3. RSS (& Atom) Feeds. RSS and Atom Web Syndicators. Used for web feeds / feeds / channels Employ XML tags, such as …. Feed as Displayed in a Browser datafeeds.rouxacademy.com/ rss /artists.xml.
E N D
BCIS 4650 Visual Programming for Business Applications Data Binding #3 The University of North Texas, ITDS Dept., Dr. Vedder
RSS and Atom Web Syndicators • Used for web feeds / feeds / channels • Employ XML tags, such as … The University of North Texas, ITDS Dept., Dr. Vedder
Feed as Displayed in a Browserdatafeeds.rouxacademy.com/rss/artists.xml The University of North Texas, ITDS Dept., Dr. Vedder
RSS Feeds Use XML-Formatted Datasaving page as XML data gives you this; note jpg did not show The University of North Texas, ITDS Dept., Dr. Vedder
System.Web.Syndication Namespace • Contains classes for using feeds in RSS 2.0 format or Atom format, ex., • SyndicationClient: gets async URI feeds • SyndicationFeed: encapsulates data in elements /rss/channel or atom:feed • SyndicationItem: reps. an item in the feed • Contains enumerations, ex., SyndicationFormat(ex., rss20) • Contains other members The University of North Texas, ITDS Dept., Dr. Vedder
How to Add a Namespace • Add with the using statement • Type it in the top section of the code, or … • Type name of a member class where you want it; VS IDE will flag it; press CTRL + period; select from menu The University of North Texas, ITDS Dept., Dr. Vedder
Mapping SyndicationItem Properties to XML Tags Used by RSS and Atom The University of North Texas, ITDS Dept., Dr. Vedder
Synchronous Programming • Synchronous: send request; thread does nothing until response received • Bad in Win 8.x, since • Store apps are usually single-threaded (one process of execution) • Long-running tasks (ex., lartge text retrieval) block further activity (“freeze”) • Freezing the app would also freeze the UI (no response to user gestures, animations freeze, etc.) The University of North Texas, ITDS Dept., Dr. Vedder
Asynchronous Programming • Basic operation: • App thread (ex., a method) sends request; • Thread continues to work (ex., ‘waiting’) • Request-dependent processing resumes only when data received • Good for Win 8.x; UI stays fully alive • Required for any code creating or reading files or with web services The University of North Texas, ITDS Dept., Dr. Vedder
Synchronous vs. Asynchronous The University of North Texas, ITDS Dept., Dr. Vedder
C#: The async Modifier Keyword and await Operator Keyword • Must use in WinStore apps • Both appear in method (verb) code • Method name should have “Async” at its end • One async modifier can be associated with multiple await expressions inside the same method The University of North Texas, ITDS Dept., Dr. Vedder
What is “a Task”? • A task is a “unit of work” • When finished, a task either • Returns nothing (“is silent”), or • Returns a value • The Task<> Class acts as a “wrapper” or container for the simple variable or object variable within the < > The University of North Texas, ITDS Dept., Dr. Vedder
C#: async and Task Class • If silent (no return statement), use the simple TaskClass (Taskw/o the <>) • If the associated method uses a returnstatement, use Task<TResult> (also a class); exs. -- • Task<string> • Task<int> • Task<byte[ ]> • Task<some-object-variable> The University of North Texas, ITDS Dept., Dr. Vedder
Example: async and await • Method declaration: MakeWebRequestAsync marked async with the returned data going to Task<result> • Declare (instantiate) and initialize an HttpClient object • Declare getStringTask of type Task<string> & initialize • Create result of type string and await returning data • Return result to caller of MakeWebRequestAsync The University of North Texas, ITDS Dept., Dr. Vedder
Retrieving RSS Data: Steps • Study RSS site’s folder structure & the XML data to learn their organization • Decide what data values you want • Inside your project, Add | New Item | C# Class (which will become part of your project’s namespace) • Create a custom class to represent the retrieved data -- You will need to build more custom classes if you have multiple data sources The University of North Texas, ITDS Dept., Dr. Vedder
How is This File Organized?Note element names might not describe values! • Channel element top enclosure • Title and Description (= subtitle) of the page • Individual item elements • Title = artist’s name • Link = photo of artist • Description = short biography of artist The University of North Texas, ITDS Dept., Dr. Vedder
Sample Custom Class • Namespace is the project • Class (ArtistItem) scoped public • All 4 public, string fields have automatic getters and setters (routines for retrieving and assigning values) The University of North Texas, ITDS Dept., Dr. Vedder
Retrieving RSS Data: Steps, 2 • Assuming multiple sources, again Add | New Item | C# Class; create a higher-level class to represent all the retrieved data from multiple sources • Consider using List<T> as it is efficient and dynamically resizes to fit the data • Write the code to retrieve and load into the runtime objects from these classes • Write the code to bind the retrieved data to the XAML elements The University of North Texas, ITDS Dept., Dr. Vedder
C#: List<T> Class • Use to build collections • Dynamically resizes, unlike an array • Ideal for collections not accessed by keys (but offers zero-based indexing) • Has many members (research!) • Values stored in order added; can sort The University of North Texas, ITDS Dept., Dr. Vedder
A Higher-Level Custom Class • Namespace is the project • Class (ArtistData) scoped public – NOTE use of encapsulation here • Two public properties (Title, SubTitle) typed string • A private List<T> (T = ArtistItem) collection (i.e., a type) named _Items (Note underscore syntax for private property name) • Public List<T> (i.e., a type) called Items includes (note location of semicolon) a get method returning the current object (= this)ArtistData’s_Items The University of North Texas, ITDS Dept., Dr. Vedder
C#: Actual Data Retrieval • Namespace is the project • Public class ArtistDataSource will hold the action • PrivateBaseUriString declared and set to RSS source • Private instance of ArtistData declared; called _Data (no value yet) • Publicinstance of ArtistData declared and called Data • Associated get will return the current object’s XML data The University of North Texas, ITDS Dept., Dr. Vedder
C#: Actual Data Retrieval, 2 • Public method GetFeedAsync() returns a Task containing ArtistData • Declare and initialize client as a new instance of SyndicationClient • Build string for data location at website • Declare and initialize a new URI object • Try / Catch block for error (exception) handling • Declare SyndicationFeedobject to await returned data • _Data associated with a new (and empty) instance of ArtistData custom class • Title and Subtitle textual values fed to _Data (SyndicationFeed class already knows how to translate the XML tags) The University of North Texas, ITDS Dept., Dr. Vedder
C#: Actual Data Retrieval, 3 • Use foreach to cycle through the item elements in the feed’s Items collection • Declare and initialize rssItem as a new instance of ArtistItemcustom class • Retrieve ArtistName from the Title element • Check that the SourceFormat of the feed is indeed RSS 2.0; if so then… • Retrieve Biography (exposed as Summary by SindicationItem class) • In the feed, Links is an array that has only one node; NodeValue returns that node’s .JPG file strings for both the ArtistPhoto and ArtworkPhoto; RSS folder research will tell you where to find these resources • Add the completed rssItem to the Items collection of _Data; return to foreachto process next record; when no more records, then … • Return the now-loaded _Data object variable
C#: Actual Data Retrieval, 4 • Use a Try / Catch block to intercept errors (exceptions) • Catching an instance of the Exception Class is the broadest net you can have; it intercepts any recognizable error from whatever cause • If an exception is caught, return nothing. The University of North Texas, ITDS Dept., Dr. Vedder
The Reality of Try / Catch This T/C is OK for a demo, but practically useless for real life, where you would probably write a series of catch statements to intercept different errors, starting with the smallest net and progressing up the relevant exception hierarchy to the largest . The University of North Texas, ITDS Dept., Dr. Vedder
C#: Start the Process in MainPage.cs • Place RSS retrieval request in this file • Any code appearing inside the OnNavigatedTo method executes when the app loads and stays resident as long as the page is cached • Must preface entire statement with async, or the retrieval will not work The University of North Texas, ITDS Dept., Dr. Vedder
C#: Code for Starting the Process • Add async to OnNavigatedTomethod signature statement • Instantiate ArtistDataSource as an object variable called DataSource and initialize it • Call GetFeedAsync, prefaced by await The University of North Texas, ITDS Dept., Dr. Vedder
C#: Now Quick ‘n’ Dirty Test • Retrieve Title and write it to the Output Window (= Debug) • Retrieve and write the Subtitle to the Output Window • Using foreach, cycle through each artist object in the Items collection and write each ArtistName to the Output Window • Save work; Debug > Start Debugging to send results to Output Window • Once app runs, switch to Visual Studio • If pass, comment-out these lines The University of North Texas, ITDS Dept., Dr. Vedder
Visual Studio Output Window • Often accessible from a tab at the bottom left of IDE • View > Output The University of North Texas, ITDS Dept., Dr. Vedder
Now Set the DataContext • Go to MainPage.cs • Associate the data of the DataSource to the DataContext instance associated with this Page • DataContextClass exposes the data for use by XAML controls; it makes {Binding …} work; every visual control in XAML can have a DataContext • Because association is at the Page level, and because the Page is a container, all of the visual controls on the Page inherit the DataContext abilities The University of North Texas, ITDS Dept., Dr. Vedder
Binding Retrieved Data to XAML • Any public property that has a get can be used in a Binding expression • Having designed and built your XAML pages using static data (ex., text strings), now start replacing those static strings with bindings • Ex.: <TextBlock Text=“Title”/> vs. <TextBlock Text=“{Binding Title}” • Binding prop. names MUST match exactly the definition names for DataContext to do its work The University of North Texas, ITDS Dept., Dr. Vedder
Simple Binding to a TextBlock • Vertical StackPanel • Binding to Title • Binding to SubTitle • Do not forget pair of double quotes The University of North Texas, ITDS Dept., Dr. Vedder
Binding the List of Artist Objects • Set the ListView’sItemsSource property to a “binding expression” that links with the Items collection object • Custom class ArtistData exposed Items property as a List • Custom class ArtistItem defined the list’s contents • There will be one displayed row for each item in the list, configured as…. • ListView’sItemTemplate gets (or sets) a DataTemplate • DataTemplate holds the visual structure that will replicate for each item in the list; and that structure is….. • Horizontal StackPanelcontaining an Image bound to ArtistPhoto and a TextBlock bound to ArtistName The University of North Texas, ITDS Dept., Dr. Vedder
Add Functionality With Binding Goal: User clicks on an artist (i.e., a ListView row) to see details • Add an identifier (x:Name=“ ”) to the ListViewso that it can be referenced elsewhere • Add a DataContextproperty to the second StackPanel; ElementNamepoints to the identified ListView, Path takes the value of the artist selected by the user • Bind TextBlockto a different value (ArtistName, Biography) • Bind Image to ArtworkPhoto; let Image determine width to keep aspect ratio The University of North Texas, ITDS Dept., Dr. Vedder
What the App Will Look Like The University of North Texas, ITDS Dept., Dr. Vedder
ITDS Logo / Mood Slide The University of North Texas, ITDS Dept., Dr. Vedder
RGB Color Guide 252 183 44 • Rust 183, 65, 14 ; set lighter • Light blue 102 255 255 • Slightly gray-blue 153, 204, 255 • Ice blue 155 183 217 • Bright green 0 255 0 • Bright yellow 255 255 0 • Tan 241 218 218 • Light lavender 201 153 255 • Darker lavender 204 102 255 The University of North Texas, ITDS Dept., Dr. Vedder