Odata services in Portable class library

Motivation:

Today I’m working in a sample for consuming services in Windows 8 Store Apps. For this sample I will use:

Northwind Service – Read-Only

This service exposes the famous Northwind sample database in read-only mode via OData.

browse…

When I started I thought of using Portable Class Library for after to add this project as a reference in a Windows 8 and Windows Phone project.

Problem

After I created the project, as a Portable Class Library, I tried to add the service reference:

http://services.odata.org/Northwind/Northwind.svc/

But I had problems, here is the message:

2.4

 

I went to the link reference: WCF Data Services Tools for Visual Studio  but this contains only reference for

and I need for Portable Class Libraries.

After some search I read this:

Conclusion:

I conclude the OData Service is not supported in Portable Class Libraries., yet!

Related References:

Open Data Protocol – .NET/Silverlight/WP7 Libraries and Frameworks

 

Export to CSV [Windows 8 Store Apps]

Introduction

In this sample i will show a sample for  export data, that is showed in ListView, to a csv file.

You can get this here:
Export To CSV or in My MSDN Samples in GitHub

Building the Sample

You only need Visual Studio 2012 and Windows 8, both the RTM version.

Description

This sample could be called “Export to Excel”, but it is not supported, the only way is to write the data in a CSV file that can be opened in Excel.

 

Here is the class diagram:

 

 

Here is the class that is used to convert the data into a CSV file:

public class CsvExport<T> where T : class 
    { 
        public IList<T> Objects; 

        public CsvExport(IList<T> objects) 
        { 
            Objects = objects; 
        } 

        public string Export() 
        { 
            return Export(true); 
        } 

        public string Export(bool includeHeaderLine) 
        { 

            var sb = new StringBuilder(); 

            //Get properties using reflection. 
           var propertyInfos = typeof(T).GetTypeInfo(); 

            if (includeHeaderLine) 
            { 
                //add header line. 
                foreach (var propertyInfo in propertyInfos.DeclaredProperties) 
                { 
                    sb.Append(propertyInfo.Name).Append(";"); 
                } 
                sb.Remove(sb.Length - 1, 1).AppendLine(); 
            } 

            //add value for each property. 
            foreach (T obj in Objects) 
            { 
                foreach (var propertyInfo in propertyInfos.DeclaredProperties) 
                { 
                    sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(";"); 
                } 
                sb.Remove(sb.Length - 1, 1).AppendLine(); 
            } 

            return sb.ToString(); 
        } 

        //export to a file. 
        public async void ExportToFile(string path) 
        { 
           var storageFolder = KnownFolders.DocumentsLibrary; 
           var file = await storageFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); 
           await FileIO.WriteTextAsync(file, Export()); 
        } 

        //export as binary data. 
        public byte[] ExportToBytes() 
        { 
            return Encoding.UTF8.GetBytes(Export()); 
        } 

        //get the csv value for field. 
        private string MakeValueCsvFriendly(object value) 
        { 
            if (value == null) return ""; 

            if (value is DateTime) 
            { 
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0) 
                    return ((DateTime)value).ToString("yyyy-MM-dd"); 
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"); 
            } 
            string output = value.ToString(); 

            if (output.Contains(",") || output.Contains("\"")) 
                output = '"' + output.Replace("\"", "\"\"") + '"'; 

            return output; 

        } 
    }

Source Code Files

  • BoardItem is my item that has Name, Value and Count properties
  • ConvertingToCSVFileViewModel: is my view model to connect data with the view (i use binding)
  • CsvExport is the class that convert the data into csv file.

Result

In the Windows 8 App:

 

The myexportresult.csv file opened in Excel:


Build the Sample

  1. Start Visual Studio Express 2012 for Windows 8 and select File > Open > Project/Solution.
  2. Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio Express 2012 for Windows 8 Solution (.sln) file.
  3. Press F7 or use Build > Build Solution to build the sample.

 Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without   debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

More Information

Ask me on twitter @saramgsilva

Rad Cartesian Chart Sample for Windows Phone [Telerik]

In my last article, Rad Cartesian Chart Sample [Telerik] I showed a sample with Rad Cartesian Chart for Windows 8. Today I want to show it but for Windows Phone.

Main goals:

  • Use the RadControls for Windows Phone
  • Create a Windows Phone 7.1 Project
  • Create a Windows Phone 8 Project;
  • Reuse the Telerik.RadCartesianChartSample.Common project;

Let’s start! First I will create the Windows Phoine 8.0 project:

image

I will use the RadControls Windows Phone Application, why?

Because, next I will show a wizard, that Telerik provide, that show which dlls I want to add, see the following image:

image

Next I will choose some features like: about page, application bar, diagnostics, message for rate, see the following image:image

When you create a lot of project, with this features, this is fantastic,, isn´t? I Like it! Smile

Here is the result:

image

Note: I changed the namespace for Telerik.RadCartesianChartSample, because is more simple if I need it later for share code between projects.

Now I will add the reference for Telerik.RadCartesianChartSample.Common

image

And after this we will create the RadCartesianChart.,..

Oh wait! I will created the same code that I did in my Windows 8 App?? Oh is so boring…. It could be more easy, hummm ok let’s try to copy and paste that I did? Open-mouthed smile

First I will add the View Model to the page, here is:

public MainPage()
{
    InitializeComponent();
    DataContext = new DashboardViewModel();			
}

The same code I did in Windows 8! Just copy and paste…

After this I found some errors, that I fixed:

  • Related with LineStyle vs LineStroke

In Windows 8 Sample I do:

   <chart:CategoricalAxis.LineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke"  Value="{StaticResource ChartColorKey}" />
                        </Style>
                    </chart:CategoricalAxis.LineStyle>

and in Windows Phone I need to do:

LineStroke="{StaticResource ChartColorKey}
  • Related with PaletteName vs. Palette

In Windows 8 I did:

PaletteName="DefaultDark"

In Windows Phone I need to do:

Palette="DefaultDark"

I don´t have more errors, let’s run… will it works??? hummmmm ….. Select the Telerik.RadCartesianChartSample(WP8) as a startup poject and then  F5, wait a little for the simulator.

Here is the result:

wpresult

With the same XAML (only fixed two little details), I have the same result as in Windows 8!!! This is great and in this way is very simple to have the same features in both platforms!

Are you thinking, what about Windows Phone 7.1? Don´t worry, repeat the steps for Windows Phone 8 and it works!

Fantastic, I like it! Smile

Conclusion:

With this sample I conclude my initial thought, with Portable Class Library and RadControls for Windows Phone and Windows 8 I can reuse code and little adjust (that can be not required) I have the same solution in my 3 apps.

You can get the Telerik.RadCartesianChartSample from here:

Telerik RadCartesianChart Samples

Some important references that I recommend:

Rad Cartesian Chart Sample for Windows 8 [Telerik]

In this article I have three main goals:

Motivation:

In the last days I have been working in my My Snake App ( and more I have to do…. Smile  the last version is now in certification process, soon will be out!)

I decide to create a chart for show at the end some results about the game.

Here is the screen:

4

My goal was to show: the score and how many flowers by color the snake got.

Now, I’m writing this article to share that I did for get this!

Let’s start!

First, I recommend to get the trial version here, and after install it in your pc.

Now I hope you are ready, let’s create the following projects:

  1. Telerik.RadCartesianChartSample.Common : this is a portable class library that contains the model and view model.  I want to reuse code between Windows 8 and Windows Phone, reason because I decide to do this!
  2. Telerik.RadCartesianChartSample(WinRT): this is the main project that represent the Windows 8 Sample.

Note: PCL is not always  the best solution, but for this propose is. For example in my My Snake App I did not used PCL because I have dependences from UI that I can not separate and for this reason I decide to use directives (#if WP …. #else  … #endif or  #if Win8 …. #else  … #endif ) and add files that I do “As Linked”.

For the Telerik.RadCartesianChartSample(WinRT) I created a Blank Project:

createproject

Note: I changed the namespace for Telerik.RadCartesianChartSample because if I need to share code between other platform is more easy to manage the namespaces.

Then I created the Telerik.RadCartesianChartSample.Common

image

Now in the Telerik.RadCartesianChartSample(WinRT) project add the reference. Click in Reference Manager > Windows >Extensions > Select RadControls for Windows 8

image

 

Now in Telerik.RadCartesianChartSample.Common project, create the

  • BoardItem : represent one item in dashboard. This class has name, value and count ( in My Snake App I have one boarditem by flower that I have in the game).
  • DashboardViewModel: this is my view model that will connect the model to the view.

Here is the class diagram that is the best thing to understand my model and view model.

ClassDiagram

In the DashboardViewModel constructor I will call a Init method, that will create my list of the DashboardItems, in my sample only 3. Because this is a sample, for generate data I will use a random values for the Count property in each BoardItem.

Here is:

 DashBoardItems = new ObservableCollection<BoardItem>    
 {                   
  new BoardItem{    
                   Name = "Blue", 
                   Value = 1,  
                   Count = _random.Next(0,50) 
               },
  new BoardItem {  
                   Name = "Pink",  
                   Value = 2,  
                   Count = _random.Next(20,100)  
                },              
 new BoardItem {    
                  Name = "Yellow", 
                  Value = 3,  
                  Count =  _random.Next(0,100)
                }          
};

Note: My class implement the NotifyPropertyChanged class the is the implementation of the INotifyPropertyChanged interface. This is important for update the UI when some property is changed.

______

In the Telerik.RadCartesianChartSample(WinRT) we have the MainPage.xaml.cs where you will add the view model, here is:

 public MainPage()   
 {      
    InitializeComponent();  
    DataContext = new DashboardViewModel();  
 }

And inside the MainPage.xaml create a grid layout that represent the root element in the page (If you want you can create columns and rows for define the header with the title, you choose!)

Inside the grid create the RadCartesianChart, something like:

 <chart:RadCartesianChart PaletteName="DefaultDark">    
 </chart:RadCartesianChart>

Here you add the PaletteName that is a property that gets or sets the PaletteName value used to apply a predefined pallete to the chart.

There are 4 points that we need to define:

  • RadCartesianChart.Grid : Gets or sets the CartesianChartGrid used to decorate the chart plot area with major/minor grid and strip lines.
  • RadCartesianChart.VerticalAxis : Gets or sets the visual Axis instance that will be used to plot points along the vertical (Y) axis.
  • RadCartesianChart.HorizontalAxis: Gets or sets the visual Axis instance that will be used to plot points along the horizontal (X) axis.
  • BarSeries : is the value that will add to the RadCartesianChart.Series: Gets the collection containing all the series presented by this instance.

Defining the RadCartesianChart.Grid

 <chart:RadCartesianChart.Grid>
                <chart:CartesianChartGrid MajorLinesVisibility="Y">
                    <chart:CartesianChartGrid.MajorYLineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke" Value="{StaticResource ChartColorKey}" />
                            <Setter Property="StrokeDashArray" Value="4, 2" />
                        </Style>
                    </chart:CartesianChartGrid.MajorYLineStyle>
                </chart:CartesianChartGrid>
            </chart:RadCartesianChart.Grid>

Defining the RadCartesianChart.VerticalAxis

 <chart:RadCartesianChart.VerticalAxis>
                <chart:LinearAxis Title="Number of flowers" FontSize="18" MajorStep="{Binding MajorStep}">
                    <chart:LinearAxis.TitleTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}" FontSize="18" Foreground="Black" Margin="0,0,0,20"/>
                        </DataTemplate>
                    </chart:LinearAxis.TitleTemplate>
                    <chart:LinearAxis.LineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke"  
                           Value="{StaticResource ChartColorKey}" />
                        </Style>
                    </chart:LinearAxis.LineStyle>
                    <chart:LinearAxis.LabelStyle>
                        <Style TargetType="TextBlock">
                          <Setter Property="Foreground"  
                             Value="{StaticResource ChartColorKey}" />
                          <Setter Property="FontSize"
                               Value="14"></Setter>
                        </Style>
                    </chart:LinearAxis.LabelStyle>
                    <chart:LinearAxis.MajorTickStyle>
                        <Style TargetType="Rectangle">
                            <Setter Property="Stroke" 
                            Value="{StaticResource ChartColorKey}" />
                        </Style>
                    </chart:LinearAxis.MajorTickStyle>
                </chart:LinearAxis>
            </chart:RadCartesianChart.VerticalAxis>

Here there is a point that I want to referer:

MajorStep="{Binding MajorStep}"

In my viewmodel I have a MajorStep Property:

  public int MajorStep
        {
            get
            {
                if (DashBoardItems.Any(item => item.Count < 10))
                {
                    return 1;
                }

                if (DashBoardItems.Any(item => item.Count > 50))
                {
                    return 5;
                }

                return 2;
            }
        }

I did this because I want to define dinamically the step for the chart, because in My Snake App the user can get a lot of flowers or not and when I have values like 100 I don´t have step with value 1 or in values like 8 I don´t have steps with value 5.

Defining the RadCartesianChart.HorizontalAxis

    <chart:RadCartesianChart.HorizontalAxis>
                <chart:CategoricalAxis Title="Flowers" FontSize="18">
                    <chart:CategoricalAxis.TitleTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}" 
                              FontSize="18" Foreground="Black" />
                        </DataTemplate>
                    </chart:CategoricalAxis.TitleTemplate>
                    <chart:CategoricalAxis.LineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke"  
                            Value="{StaticResource ChartColorKey}" />
                        </Style>
                    </chart:CategoricalAxis.LineStyle>
                    <chart:CategoricalAxis.LabelStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="Foreground" 
                             Value="{StaticResource ChartColorKey}" />
                            <Setter Property="FontSize" 
                                Value="14"></Setter>
                        </Style>
                    </chart:CategoricalAxis.LabelStyle>
                    <chart:CategoricalAxis.MajorTickStyle>
                        <Style TargetType="Rectangle">
                            <Setter Property="Stroke"  
                            Value="{StaticResource ChartColorKey}"  />
                        </Style>
                    </chart:CategoricalAxis.MajorTickStyle>
                </chart:CategoricalAxis>
            </chart:RadCartesianChart.HorizontalAxis>

Defining BarSeries:

<chart:BarSeries ItemsSource="{Binding DashBoardItems}">
                <chart:BarSeries.PointTemplates>
                    <DataTemplate>
                        <Rectangle  Fill="LightBlue"/>
                    </DataTemplate>
                    <DataTemplate>
                        <Rectangle   Fill="Pink"/>
                    </DataTemplate>
                    <DataTemplate>
                        <Rectangle  Fill="Yellow"/>
                    </DataTemplate>
                </chart:BarSeries.PointTemplates>
                <chart:BarSeries.CategoryBinding>
                    <chart:PropertyNameDataPointBinding 
                              PropertyName="Name"  />
                </chart:BarSeries.CategoryBinding>
                <chart:BarSeries.ValueBinding>
                    <chart:PropertyNameDataPointBinding 
                              PropertyName="Count" />
                </chart:BarSeries.ValueBinding>
            </chart:BarSeries>

Here, in BarSeries, I defined the ItemsSource that is the DashBoardItems that I defined in View Model:

ItemsSource="{Binding DashBoardItems}"

Is this that make the chart to be filled ( but don´t forget the others configuration!!).

For define which properties will used (from BoardItem) I defined the:

<chart:PropertyNameDataPointBinding PropertyName="Name"  />

and

<chart:PropertyNameDataPointBinding PropertyName="Count" />

Oh, another little thing, for each i choosed: CategoricalAxis and Linear Axis.

Because I want each board item with different colors I defined

      <chart:BarSeries.PointTemplates>
                    <DataTemplate>
                        <Rectangle  Fill="LightBlue"/>
                    </DataTemplate>
                    <DataTemplate>
                        <Rectangle   Fill="Pink"/>
                    </DataTemplate>
                    <DataTemplate>
                        <Rectangle  Fill="Yellow"/>
                    </DataTemplate>
                </chart:BarSeries.PointTemplates>

And the result of the this is:

 

image

Conclusion:

There are many ways to show a chart, this is only one way, a simple sample that was my experience with RadCartesianChart from Telerik RadControls From Windows 8.

You can get the Telerik.RadCartesianChartSample from here:

Telerik RadCartesianChart Samples

Some important references that I recommend:

Girl Geek Dinners App for Windows 8 and Windows Phone 8

In the last days i submitted two applications for Girl Geek Dinners Community, they run in Windows 8 and Windows Phone 8.

The references are:

Girl Geek Dinners for Windows Phone
http://www.windowsphone.com/pt-pt/store/app/girl-geek-dinners/d690f648-3692-47e0-8e3c-65ba546625f0

Girl Geek Dinners for Windows 8
http://apps.microsoft.com/webpdp/pt-pt/app/girl-geek-dinners/5b80a5ea-2c3a-42a3-9b6d-f32d37b15e8a

Features:
Allow to see the last articles from Portugal and Brazil;
Allow to add article to favorite list;
Allow share an article;
Save feeds in device;

My main idea is to have news from all countries and have more things like: photos, presentations, events….

I did not all my idea because:

  • I read feeds;
  • I have some certification requirements that don´t allow different languages displayed in the same time in the app, this is the reason i have only Portugal and Brazil;

I have some features that i will implement and i want to share the code for all girl geek can see/help.

This is not my app, this the girl geek community app!

Vote in Playing with Math [Windows Phone 8 & Nokia]

I submitted my Windows Phone 8 Application in Lumia Geek 8 – Week Challenge

The link for vote is:
http://www.windowsphonegeek.com/lumia-geek-8-week-challenge/playing-with-math

 
See the image for clarify how to vote: