Wednesday, February 27, 2013

Windows Phone Youtube search app

make a project with the name YouTubeApp and have a main layout at main.xaml as follows


<phone:PhoneApplicationPage 
    x:Class="YouTubeApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Height="72" HorizontalAlignment="Left" Margin="-12,6,0,0" Name="textBox1" Text="Musetheplace" VerticalAlignment="Top" Width="460" />
            <Button x:Name="SearchButton" Content="Search" HorizontalAlignment="Right" VerticalAlignment="Top" Click="SearchButton_Click" Margin="0,66,164,0" />
            <ListBox SelectionChanged="VideoListSelectionChanged" x:Name="ResultsList" Margin="10,144,0,0">
<ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Title}" VerticalAlignment="Top" 
         HorizontalAlignment="Left" Width="355" Margin="100,0,0,0" TextWrapping="Wrap"/>
            <Image Source="{Binding VideoImageUrl}" HorizontalAlignment="Left" Width="100"   
         Height="100" Stretch="UniformToFill"/>
                        </StackPanel>
                    </DataTemplate>
                    </ListBox.ItemTemplate>
            </ListBox>


        </Grid>
    </Grid>

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>


have a code at main.xaml.cs as follows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Xml.Linq;

namespace YouTubeApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            var wc = new WebClient();
            wc.DownloadStringCompleted += DownloadStringCompleted;
            var searchUri = string.Format(
              "http://gdata.youtube.com/feeds/api/videos?q={0}&format=6",
              HttpUtility.UrlEncode(textBox1.Text));
            wc.DownloadStringAsync(new Uri(searchUri));
        }
        void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var atomns = XNamespace.Get("http://www.w3.org/2005/Atom");
            var medians = XNamespace.Get("http://search.yahoo.com/mrss/");
            var xml = XElement.Parse(e.Result);
            var videos = (
              from entry in xml.Descendants(atomns.GetName("entry"))
              select new YouTubeVideo
              {
                  VideoId = entry.Element(atomns.GetName("id")).Value,
                  VideoImageUrl = (
                    from thumbnail in entry.Descendants(medians.GetName("thumbnail"))
                    where thumbnail.Attribute("height").Value == "240"
                    select thumbnail.Attribute("url").Value).FirstOrDefault(),
                  Title = entry.Element(atomns.GetName("title")).Value
              }).ToArray();
            ResultsList.ItemsSource = videos;
        }
        private void VideoListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var video = ResultsList.SelectedItem as YouTubeVideo;
            if (video != null)
            {
                var parsed = video.VideoId.Split('/');
                var id = parsed[parsed.Length - 1];
                var playbackUrl = "vnd.youtube:" + id;

                var task = new WebBrowserTask { URL = playbackUrl };
                task.Show();
            }
        }
    }
    public class YouTubeVideo
    {
        public string Title { get; set; }
        public string VideoImageUrl { get; set; }
        public string VideoId { get; set; }
    }
}


just run the app and have fun with this app.




Monday, February 25, 2013

Windows Phone 7TabControl

By default, the Windows Phone 7 SDK doesn't have a TabControl. It is a quite useful component already available in Silverlight . In order to use this control a complete re-write is not necessary. All that needs to be done is adding a reference to System.Windows.Controls - a standard Silverlight library that is located at:   C:\Program Files \Microsoft SDKs\Silverlight\v4.0\Libraries\Client  Next step is adding the assembly reference as a namespace pointer in the work XAML


xmlns:cc="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

To add the control to the workspace:

<cc:TabControl>
    <cc:TabItem Height="80" Width="80" Header="Tab 1" Foreground="Black"></cc:TabItem>
    <cc:TabItem Height="80" Width="80" Header="Tab 2" Foreground="Black"></cc:TabItem>
    <cc:TabItem Height="80" Width="80" Header="Tab 3" Foreground="Black"></cc:TabItem>
    <cc:TabItem Height="80" Width="80" Header="Tab 4" Foreground="Black"></cc:TabItem>
    <cc:TabItem Height="80" Width="80" Header="Tab 5" Foreground="Black"></cc:TabItem>
</cc:TabControl>

tha main.xaml is having following layout

<phone:PhoneApplicationPage 
    x:Class="HelloWorldAdvanced.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:cc="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Tab Demo" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="First Page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            
            <cc:TabControl>
                <cc:TabItem Height="80" Width="80" Header="Tab 1" Foreground="Black"></cc:TabItem>
                <cc:TabItem Height="80" Width="80" Header="Tab 2" Foreground="Black"></cc:TabItem>
                <cc:TabItem Height="80" Width="80" Header="Tab 3" Foreground="Black"></cc:TabItem>
                <cc:TabItem Height="80" Width="80" Header="Tab 4" Foreground="Black"></cc:TabItem>
                <cc:TabItem Height="80" Width="80" Header="Tab 5" Foreground="Black"></cc:TabItem>
            </cc:TabControl>

        </Grid>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

the screen shot demo is given below


Monday, February 11, 2013

Windows phone RSS FEED READER


This sample shows you how to create a basic RSS reader that downloads an RSS feed, and then displays the feed items in a ListBox.
This sample shows you how to create a basic RSS reader that downloads the http://www.nydailynews.com/gossip/gatecrasher/index_rss.xml RSS feed, and then displays the feed items in a ListBox. Although the sample is set up to download a specific RSS feed, you could choose to extend the sample to use in your app by adding functionality to dynamically download other RSS feeds.

Create project and have a MainPage.xaml layout as follows

<phone:PhoneApplicationPage 
    x:Class="Recipe1_RssReader.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="CH6-Recipes" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="RSS Feeds" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
       

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,52,0,0" Name="textBox1" Text="http://www.nydailynews.com/gossip/gatecrasher/index_rss.xml" VerticalAlignment="Top" Width="460" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="14,32,0,0" Name="textBlock1" Text="RSS Feed Link:" VerticalAlignment="Top" />
            <Button Content="Go" Height="72" HorizontalAlignment="Left" Margin="0,116,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
        </Grid>
        <Grid x:Name="ContentPanel2" Margin="12,217,12,-13" Grid.Row="1">
            <ListBox x:Name ="lstItems" Margin="0,6,0,0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            
                            <StackPanel VerticalAlignment="Top">
                                <Image Width="200" Height="400" Source="{Binding Path=ImageURL}" />
                                <TextBlock Grid.Row="0" Text="{Binding Title}" FontWeight="Bold" Foreground="OrangeRed"/>
                                <TextBlock Grid.Row="1"  Text="{Binding Content}" />
                                <TextBlock Grid.Row="2"  Text="{Binding DatePosted}" />
                                <HyperlinkButton TargetName="_blank" Grid.Row="3"  Name="DetailLink" Content="Details..." NavigateUri="{Binding URL}" Foreground="Yellow" HorizontalAlignment="Left"/>
                                
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>


    </Grid>

</phone:PhoneApplicationPage>


the MainPage.xaml.cs code is given below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

// reference System.Xml.Linq
using System.Xml.Linq;
namespace Recipe1_RssReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        WebClient remoteXml;
        public MainPage()
        {
            InitializeComponent();

            remoteXml = new WebClient();
            remoteXml.DownloadStringCompleted += new DownloadStringCompletedEventHandler(remoteXml_DownloadStringCompleted);
        }

        //private void remoteXml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    if (e.Error != null)
        //        return;
        //    XDocument xdoc = XDocument.Parse(e.Result);
        //    IEnumerable<RssFeed> feeds;
        //   feeds = from task in xdoc.Descendants("item")
        //            select new RssFeed
        //            {
        //                Title = task.Attribute("title").Value,
        //                //Content = task.Attribute("description").Value,
        //                DatePosted = DateTime.Parse(task.Attribute("pubDate").Value),
        //                URI = task.Attribute("link").Value
        //            };
        //    lstTasks.ItemsSource = feeds;
        //}

        private void remoteXml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            XDocument xdoc = XDocument.Parse(e.Result);
            var rss = XElement.Parse(e.Result);

            XNamespace ns = rss.GetNamespaceOfPrefix("media");
            List<RssFeed> rssFeeds;

            rssFeeds = (from item in xdoc.Descendants("channel").Elements("item")
                        select new RssFeed()
                        {
                            Title = item.Element("title").Value,
                            Content = item.Element("description").Value,
                            DatePosted = item.Element("pubDate").Value, 
                            URL = new Uri(item.Element("link").Value, UriKind.Absolute),
                            ImageURL = item.Element(ns + "content").Attribute("url").Value

                        }).ToList();
            lstItems.ItemsSource = rssFeeds;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string txtUri = textBox1.Text;
            txtUri = Uri.EscapeUriString(txtUri);
            Uri uri = new Uri(txtUri,UriKind.Absolute);
            remoteXml.DownloadStringAsync(uri);
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            
             
           // App.currentURL = new Uri
            NavigationService.Navigate(new Uri("/BrowserPage.xaml", UriKind.Relative));
        }
    }
}

RssFeed.cs is having following getter and setters

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Recipe1_RssReader
{
        public class RssFeed
        {
            public string Title { get; set; }
            public string Content { get; set; }
            public String DatePosted { get; set; }
            public Uri URL { get; set; }
            public String ImageURL { get; set; }
            
        }
   
}

after running the project successfully you can see the output as follows


Download the code from the link RSSFEED 



Wednesday, February 6, 2013

Windows phone Complex XML Parsing

I WAS WORKING WITH XML PARSING AND I FOUND A NICE WAY TO DO IT, Please have a look, for this purpose i used the link http://www.xmlfiles.com/examples/cd_catalog.xml which i found from net .

make a project and have a MainPage.xaml with following layout


<phone:PhoneApplicationPage 
    x:Class="Recipe4_RemoteXml.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Remote Xml" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         
            <Button Content="Go" Height="79" HorizontalAlignment="Left" Margin="12,6,0,0" Name="button1" VerticalAlignment="Top" Width="438" Click="button1_Click" />
        </Grid>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel2" Margin="12,217,12,-13" Grid.Row="1">
            <ListBox x:Name ="lstTasks" Margin="0,-126,0,0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                                <RowDefinition Height="15" />
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="150" />
                                <ColumnDefinition Width="200" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>

                            <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding TITLE}" FontWeight="Bold" Foreground="OrangeRed"/>
                            <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding ARTIST}" />
                            <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding COUNTRY}"  Foreground="Yellow"/>
                            <TextBlock Grid.Row="1" Grid.ColumnSpan="3" Text="{Binding COMPANY}" />
                            <TextBlock Grid.Row="2" Grid.ColumnSpan="3" />
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>


have a MainPage.xaml.cs with following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Linq;

namespace Recipe4_RemoteXml
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        WebClient remoteXml;
        public MainPage()
        {
            InitializeComponent();
            remoteXml = new WebClient();
            remoteXml.DownloadStringCompleted += new DownloadStringCompletedEventHandler(remoteXml_DownloadStringCompleted);
        }

        private void remoteXml_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument xdoc = XDocument.Parse(e.Result);
            IEnumerable<DataClass> iTasks;

            iTasks = from task in xdoc.Descendants("CD")
                     select new DataClass
                     {
                         TITLE = (string)task.Element("TITLE"),
                         ARTIST = (string)task.Element("ARTIST"),
                         COUNTRY = (string)task.Element("COUNTRY"),
                         COMPANY = (string)task.Element("COMPANY"),
                         PRICE = (string)task.Element("PRICE"),
                         YEAR = (string)task.Element("YEAR")

                     };
            lstTasks.ItemsSource = iTasks;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string txtUri = "http://www.xmlfiles.com/examples/cd_catalog.xml";
            txtUri = Uri.EscapeUriString(txtUri);
            Uri uri = new Uri(txtUri);

            remoteXml.DownloadStringAsync(uri);
        }
    }
}

the DataClass.cs code is given below


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Recipe4_RemoteXml
{
    public class DataClass
    {
        public string TITLE { get; set; }
        public string ARTIST { get; set; }
        public string COUNTRY { get; set; }
        public string COMPANY { get; set; }
        public string PRICE { get; set; }
        public string YEAR { get; set; }

    }
}

the screen shot of the output is given below





Tuesday, February 5, 2013

Windows Phone XML Parsing

I n windows phone applications we can parse an xml document easily. we just need to follow few steps for this purpose make a project. and have a MaiPage.xml as follows


<phone:PhoneApplicationPage
    x:Class="Recipe1_LinqToXml.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" Loaded="MainPage_Loaded">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Linq To Xml" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Margin="12,0,12,-13" Grid.Row="1">
            <ListBox x:Name ="lstTasks" Grid.Row="3" Grid.Column ="1">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                                <RowDefinition Height="15" />
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="150" />
                                <ColumnDefinition Width="200" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>

                            <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Name}" FontWeight="Bold" Foreground="OrangeRed"/>
                            <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding DateDue}" />
                            <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Priority}"  Foreground="Yellow"/>
                            <TextBlock Grid.Row="1" Grid.ColumnSpan="3" Text="{Binding Notes}" />
                            <TextBlock Grid.Row="2" Grid.ColumnSpan="3" />
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

now copy the below given code to MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Linq;

namespace Recipe1_LinqToXml
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
          //  parseXMLUsingLinq("MyTasks.xml");
        }


        // Sample showing how to parse the XML using LINQ
        private void parseXMLUsingLinq(string passedXmlFileName)
        {
            XDocument xdoc = XDocument.Load(passedXmlFileName);
            IEnumerable<DataClass> iTasks;

            iTasks = from task in xdoc.Descendants("task")
                     select new DataClass
                     {
                         Name = (string)task.Attribute("name"),
                         Notes = (string)task.Attribute("notes"),
                         Priority = (string)task.Attribute("priority"),
                         DateDue = (DateTime)task.Attribute("datedue"),
                         DateCreated = (DateTime)task.Attribute("datecreated")
                     };
            lstTasks.ItemsSource = iTasks;
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            parseXMLUsingLinq("MyTasks.xml");
        }
    }
}

we need to make an another DataClass.cs with the code


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Runtime.Serialization;


namespace Recipe1_LinqToXml
{
    public class DataClass
    {
        public string Name { get; set; }
        public string Notes { get; set; }
        public string Priority { get; set; }
        public DateTime DateDue { get; set; }
        public DateTime DateCreated { get; set; }
    }
    public class DateFormatter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            string formatString = parameter as string;
            if (!string.IsNullOrEmpty(formatString))
            {
                return string.Format(culture, formatString, value);
            }
            return value.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

also make a MyTasks.xml  with following xml


<?xml version="1.0" encoding="utf-8" ?>
<tasks>
  <task name="name 1" notes="notes 1" priority="Low" datedue="03/01/2011" datecreated="02/01/2011"/>
  <task name="name 2" notes="notes 2" priority="High" datedue="04/01/2011" datecreated="02/01/2011"/>
  <task name="name 3" notes="notes 3" priority="Medium" datedue="05/01/2011" datecreated="02/01/2011"/>
</tasks>

after running the project on emulator you can see the outpust as below