Resolution of Error: “This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props.”


Today I faced this issue during compilation of an asp.net 4.5.2  webforms app on Visual Studio 2015 Enterprise which was built few months back using Visual Studio 2013 Update 4  environment from VS online(TFS).

Problem Statement:

The error was highlighted during building of the project.

“This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props.”

Resolution: 

The error comes due to obsolete .nuget packages & wrong path indicated on app.csproj or .vbproj file. So, in order to solve the issue,

  1. First clear all folders under ‘Packages’ directory of project main directory. Packages

2. Restart the solution on VS & click on ‘manage nuget package’ from project solution explorer. Update all .nuget packages to latest version.

nuget-package-manager

 

3. Open the project.csproj / .vbproj file on any text editor & replace the line with the appropriate line of the ‘Microsoft.Net.Compilers.1.1.1’ available in your project directory.

csproj

4. Don’t forget to comment out the following block in the project.csproj/vbproj file like as the screenshot.

<Target Name=”EnsureNuGetPackageBuildImports” BeforeTargets=”PrepareForBuild”>
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition=”!Exists(‘..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props’)” Text=”$([System.String]::Format(‘$(ErrorText)’, ‘..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props’))” />
<Error Condition=”!Exists(‘..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props’)” Text=”$([System.String]::Format(‘$(ErrorText)’, ‘..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props’))” />
<Error Condition=”!Exists(‘..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props’)” Text=”$([System.String]::Format(‘$(ErrorText)’, ‘..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props’))” />
</Target>

comment

~Happy Troubleshooting!!

Building Cross-Platform Mobile apps with Icenium for iOS,Android on Visual Studio 2012


Recently announced, the visual studio ultimate 2012 extension of Icenium (Kendo UI for Mobile) by telerik , a cross- platform mobile app framework based on PhoneGap, jQuery Mobile for iOS & Android. The Visual Studio 2012 ultimate extension can be downloaded from here.

Lets start , what’s new in this version of Icenium template. So, open Visual Studio 2012 ultimate & select Icenium template from Project templates.

Kendo

The latest release contains the following updates :

  • Icenium extension for Visual Studio (Beta): .NET developers can fully leverage Icenium mobile development platform directly from Visual Studio! This allows for quick development of cross-platform apps for both iOS and Android. In addition Team Foundation Server (TFS) and Subversion (SVN), for example, can now be used in addition to Icenium’s default support for GitHub, making it even easier to integrate Icenium into existing development workflows.
  • Apache Cordova 3.0 update: In Apache Cordova 3.0, every core API is taken apart into a plugin on its own-and Icenium can now take advantage of this new architecture. Users will be able to selectively turn on or off any core plugin. The same option will be available for all out-of-the-box advanced custom plugins such as the Barcode Scanner, PushPlugin, and SQLite.
  • Icenium Mist enhancements: Icenium Mist continues to mature with the inclusion of code analysis, code completion, and its new integrated version control plugin, CodeMirror.

 

  • Run the project by selecting the tab ‘ICENIUM‘ from Visual Studio 2012 & select the option ‘Run Project(Specified in Project Name) in simulator‘.

Run

 

  • The device simulator launches with iPhone,iPhone 5S, iPad, Android Phone & Android Tablet simulators.

PieChart

  • The simulator even specifies the geolocation & network connection feasibility options(viz. wifi, cell2G, cell3G,cell4G, limited) connectivity options.

geolocation

  • The Icenium DataViz project template contains default JSON data for populating charts, gauges along with ‘Cordova‘ framework support for iOS & Android.
  • The source code for these controls looks fairly simple by using jQuery Mobile & Cordova scripts using native html5 & minimized css3

<!DOCTYPE html>
<html>
<head>
<title>Kendo UI DataViz</title>
<meta charset=”UTF-8″ />

<link href=”kendo/styles/kendo.dataviz.mobile.min.css” rel=”stylesheet” />

<!–Once the final theme is chosen the redundant css reference should removed–>
<link href=”kendo/styles/kendo.dataviz.flat.min.css” rel=”stylesheet” />
<link href=”kendo/styles/kendo.dataviz.silver.min.css” rel=”stylesheet” />

<link href=”styles/main.css” rel=”stylesheet” />

<script src=”cordova.js”></script>
<script src=”kendo/js/jquery.min.js”></script>
<script src=”kendo/js/kendo.dataviz.mobile.min.js”></script>

<script src=”scripts/app.js”></script>
<script src=”scripts/pie-chart.js”></script>
<script src=”scripts/gauge.js”></script>
<script src=”scripts/qr-code.js”></script>
<script src=”scripts/stock-chart.js”></script>
</head>

<body>
<!–Pie chart–>
<div id=”tabstrip-pie-chart”
data-role=”view”
data-title=”Pie Chart”
data-show=”app.pieChart.createPieChart”
data-hide=”app.pieChart.unbindResizeEvent”
data-stretch=”true”>

<div data-role=”content” class=”view-content”>
<div id=”pie-chart”></div>
</div>

</div>

<!–Gauge–>
<div id=”tabstrip-gauge”
data-role=”view”
data-title=”Gauge”
data-show=”app.gauge.createGauge”
data-hide=”app.gauge.unbindResizeEvent”
data-stretch=”true”>

<div id=”gauge-wrap” data-role=”content” class=”view-content”>
<div id=”gauge”></div>
<div class=”input-content”>
<input id=”gauge-value” type=”range”>
</div>
</div>

</div>

<!–QR code–>
<div id=”tabstrip-qrcode”
data-role=”view”
data-title=”QR Code”
data-show=”app.qrcode.createQRCode”>

<div data-role=”content” class=”view-content”>
<div id=”qrcode”></div>
<div class=”input-content”>
<input type=”text” id=”qrcode-value” value=”http://www.icenium.com/”&gt;
<a data-role=”button” id=”qrcode-generate”>Update QR</a>
</div>
</div>

</div>

<!–Stock chart–>
<div id=”tabstrip-stock-chart”
data-role=”view”
data-title=”Stock Chart”
data-show=”app.stockChart.createStockChart”
data-hide=”app.stockChart.unbindResizeEvent”
data-stretch=”true”>

<div data-role=”content” class=”view-content”>
<div id=”stock-chart”></div>
</div>

</div>

<!–Layout–>
<div data-role=”layout”
data-id=”mobile-tabstrip”>

<!–Header–>
<div data-role=”header”>
<div data-role=”navbar”>
<a data-align=”right” data-role=”button” data-click=”app.changeSkin”>Flat</a>
<span data-role=”view-title”></span>
</div>
</div>

<!–Footer–>
<div data-role=”footer”>
<div data-role=”tabstrip”>
<a href=”#tabstrip-pie-chart” data-icon=”globe”>Pie Chart</a>
<a href=”#tabstrip-gauge” data-icon=”recents”>Gauge</a>
<a href=”#tabstrip-qrcode” data-icon=”camera”>QR Code</a>
<a href=”#tabstrip-stock-chart” data-icon=”featured”>Stock Chart</a>
</div>
</div>

</div>
</body>
</html>

Android chart

In next article, we will cover the PhoneGap / Cordova  3.0 framework to built native apps on HTML5, CSS3 & jQuery for Windows Store & Windows Phone apps using Windows Azure Mobile Services(WAMS).

 

Consuming Live OData feed in Silverlight WCF RIA Services hosted on Windows Azure, Windows Phone 8 & Windows Store app


Windows Azure supports Silverlight Business Applications(WCF RIA Services) as web role application. In order to work with WCF RIA services , enterprise business apps have rich support with OData endpoints, WCF Data Services, WCF Domain services(ADO.NET Entity Frameworks) , LINQ to SQL in order to connect with backend on-premise SQL Server or SQL Azure database. So, in current article, implemented a simple Silverlight enterprise business app running on Windows azure executing via live WCF OData endpoints while the same service can be consumed on Windows Phone 8 & Windows Store app without changing any major coding implementations.

Lets check the application architecture first which consists of a Windows Azure app running on dev fabric , Silverlight WCF RIA service app, Windows Phone 8 app & Windows Store app developed in VS 2012 ultimate platform.

architecture

  • Next , lets check about the architecture viewpoint of the Silverlight Business app running on Windows Azure. For consuming live OData feed , we have used the MSTeched 2010 Live feed which can be accessed @ http://odata.msteched.com/sessions.svc/
  • Consume the OData feed as Service Reference & configure with LINQ query to specify the modules from the feed.

LINQ Query Sample:

 

from  g in Speakers

where

g.SpeakerID > 1620

orderby

g.SpeakerFirstName

select  g

 

Linq

  • Lets check the Silverlight client to consume the OData feed with asynchronous task library.

var ctx = newODataTENA10Entities(newUri(http://odata.msteched.com/sessions.svc&#8221;, UriKind.Absolute));

var qry = from g in ctx.Speakers

where g.SpeakerID > 1620

orderby g.SpeakerFirstName

select g;

var coll = newDataServiceCollection<Speaker>();

coll.LoadCompleted += newEventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);

coll.LoadAsync(qry);

DataContext = coll;

  • Lets check the silverlight web business app consuming live OData feed using WCF Data services & LINQ displaying MS Tech 2010 speakers list.

 

SLWCFRIA

  • Similarly migrate the Silverlight Business app into Windows Azure platform & host as web role application.
  • OData feed can be consumed to any standard windows client like Windows Phone, Sharepoint , Windows Store, Azure Appfabric Service Bus.
  • Next, Lets add a new Windows Phone 8 Panorama application with our existing solution & add few code to consume the live OData feed & add service reference to work with WCF data services. For VS 2010, Windows Phone 7.1/ Windows Phone 8 apps, we need to work withSystem.Data.Services.Client.dll which can be obtained from here .
  • Add the following code to MainPage.xaml.cs in order to consume the live service from OData endpoint to Windows Phone.

 

private void MainPage_Loaded(object sender, RoutedEventArgs e)

{

var ctx = newODataTENA10Entities(newUri(http://odata.msteched.com/sessions.svc/&#8221;));

var coll = newDataServiceCollection<Speaker>(ctx);

lst.ItemsSource = coll;

coll.LoadCompleted += new  EventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);

    var qry = “/Speakers”;

coll.LoadAsync(new Uri(qry, UriKind.Relative));

}

void coll_LoadCompleted(object sender, LoadCompletedEventArgs e)

{

if (e.Error != null)

{

MessageBox.Show(e.Error.Message);

}

}

WPScreen

  • Lets add one more project to consume the live OData feed on Windows Store Metro Style app to display Teched 2010 speakers list.
  • Since , Windows Phone 8 & Windows Store shares the same kernel structure , so same code can be applied for Windows Phone 8 & Windows Store apps developed as per as developed same class library, same UI structure & same architecture pattern (MVVM Model).
  • In Windows Store apps, the same code for Windows Phone 8 app can be applied in order to get live OData services feed on surface.
  • The OData Client library for Windows Store app can be downloaded from here

WinStore

REST Services for Mobile ASP.NET MVC 4 with Code-First Entity Framework & Web API with SQL Azure on Visual Studio 2012 Ultimate


REST based services are quite easier to access via ASP.NET MVC 4 Mobile Web applications with Web API framework. With REST , each object can be uniquely identified & accessed via Code Access URL with its own Routing logic & behaviour. To implement a REST services for Mobile ASP.NET MVC 4 application with Web API & entity framework , lets start by creating a new ASP.NET MVC 4 web applivation from VS 2012 Ultimate.

  • Select the Project type as Internet Application by default.

  • Delete the default Model  folders file & create a new class & name it as Contacts.cs. Add the following code into it.

using  System;

using  System.Collections.Generic;

using  System.Linq;

using System.Web;

using System.Globalization;

namespace  ContactsApp.Models

{

public class Contact

{

public int ContactId { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public string City { get; set; }

public string State { get; set; }

public string Zip { get; set; }

public string Email { get; set; }

public string Twitter { get; set; }

public string Self

{

get

{

returnstring.Format(CultureInfo.CurrentCulture,“api/contacts/{0}”, this.ContactId);

}

set { }

}

}

}

  • Delete the default controllers & Build thee solution & create a new Controller by selecting the Contact Model class.

  • Now select Tools -> Library Extension Manager -> Package Manager Console & paste the following commands.

enable-migrations

 add-migration Initial

Now , select the Configuration.cs file from Migrations folder & paste the following code.

namespace

ContactsApp.Migrations

{

using System;

using System.Data.Entity;

using System.Data.Entity.Migrations;

using System.Linq;

using ContactsApp.Models;

internalsealedclassConfiguration : DbMigrationsConfiguration<ContactsApp.Models.ContactsAppContext>

{

public Configuration()

{

AutomaticMigrationsEnabled = false;

}

protected override void Seed(ContactsApp.Models.ContactsAppContext context)

{

context.Contacts.AddOrUpdate(p => p.Name, new Contact

{

Name = “Debra Johnson”,

Address = “1234 Main St”,

City = “Redmond”,

State = “WA”,

Zip = “10999”,

Email = “debra@example.com”,

Twitter = “debra_example”

},

new Contact

{

Name = “Thorsten Weinrich”,

Address = “5678 1st Avenew W”,

City = “Redmond”,

State = “WA”,

Zip = “10999”,

Email = “thorsten@example.com”,

Twitter = “thorsten_example”

},

new Contact

{

Name = “Yuhong Li”,

Address = “9012 State St”,

City = “Redmond”,

State = “WA”,

Zip = “10999”,

Email = “yuhong@example.com”,

Twitter = “yuhong_example”

},

new Contact { Name = “Jon Orton”, Address = “3456 Maple St”, City = “Redmond”, State = “WA”, Zip = “10999”, Email = “jon@example.com”, Twitter = “jon_example” },

newContact { Name = “Diliana Alexieva-Bosseva”, Address = “7890 2nd Street E”, City = “Redmond”, State = “WA”, Zip = “10999”, Email = “diliana@example.com”, Twitter = “diliana_example” }

);

}

}

}

  • In the package-Manager console , enter the following code :

update-database

Build the solution & add the following code in index.cshtml :

@model IEnumerable<ContactsApp.Models.Contact>

@{

ViewBag.Title = “Home”;

}

@section Scripts {

@ Scripts.Render(“~/bundles/knockout”)

<script type=”text/javascript”>

function ContactsViewModel() {

var self = this;

self.contacts = ko.observableArray([]);

self.addContact =

function () {

$.post(“api/contacts”,

$( “#addContact”).serialize(),

function (value) {

self.contacts.push(value);

},

“json”);

}

self.removeContact = function (contact) {

$.ajax({

type: “DELETE”,

url: contact.self,

success:

function () {

self.contacts.remove(contact);

}

});

}

$.getJSON( “api/contacts”, function (data) {

self.contacts(data);

});

}

ko.applyBindings(new ContactsViewModel());

</script>

}

<ul id=”contacts”data-bind=”foreach:contacts”>

<li class=”ui-widget-content ui-corner-all”>

<h1 data-bind=”text:Name”class=”ui-widget-header”></h1>

<div><spandata-bind=”text:$data.Address ||      ‘Address?'”></span></div>

<div>

<span data-bind=”text:$data.City || ‘City?'”></span>

<span data-bind=”text:$data.State || ‘State?'”></span>

<span data-bind=”text:$data.Zip || ‘Zip'”></span>

</div>

<div data-bind=”if:$data.Email”><adata-bind=”attr:{href:  ‘mailto:’+Email},text:Email”></a></div>

<div data-bind=”ifnot:$data.Email”><span>Email?</span></div>

<div data-bind=”if:$data.Twitter”><adata-bind=”attr:{href:     ‘http://twitter.com/&#8217; +Twitter},text:’@@’+Twitter”></a></div>

<div data-bind=”ifnot:$data.Twitter”><span>Twitter?</span></div>

<p><a data-bind=”attr:{href:Self},click:$root.removeContact”

class=”removeContact ui-state-default ui-corner-all”>Remove</a></p>

</li>

</

ul>

<form id=”addContact”data-bind=”submit:addContact”>

<fieldset>

<legend>Add New Contact</legend>

<ol>

<li>

<label for=”Name”>Name</label>

<input type=”text”name=”Name”/>

</li>

<li>

<label for=”Address”>Address</label>

<input type=”text”  name=”Address”/>

</li>

<li>

<label for=”City”>City</label>

<input type=”text”name=”City”/>

</li>

<li>

<label for=”State”>State</label>

<input type=”text”name=”State”/>

</li>

<li>

<label for=”Zip”>Zip</label>

<input type=”text”name=”Zip”/>

</li>

<li>

<label for=”Email”>E-mail</label>

<input type=”text” name=”Email”/>

</li>

<li>

<label for=”Twitter”>Twitter</label>

<input type=”text”name=”Twitter”/>

</li>

</ol>

<input type=”submit”value=”Add”/>

</fieldset>

</form>

  • Render the View on IE 10 & Check the script & view on iPhone & BlackBerry browsers.

Create, Update & Delete(CUD) Operations of SQL Server / SQL Azure Data through OData WCF Services from Windows Phone 7.1 Mango


In previous posts, I discussed about the consumption of SQL Server/ SQL Azure data in Windows Phone 7.1 Mango device through the use of OData WCF services. OData Services  support not only HTTP GET operations but also supports for HTTP POST, PUT & DELETE by which we can perform CRUD (Create, Read, Update, Delete) operations from SQL Server/SQL Azure/ Oracle / SharePoint 2010 / SSRS 2008 / SAP Netweaver BI data etc.

  • In this post, Let’s discuss how to add new data by HTTP POST through XML ATOMPUB format from Windows Phone 7.1 client to the SQL Server database.
  • Created a new .XAML page called ‘Add.xaml’ which will capture data from Phone UI & save it to the SQL Server / SQL Azure database.

  • Lets check the Source Code for the Create operation:

<phone:PhoneApplicationPage

x:Class=”WP7PanoramaOData.Add”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

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&#8243;

xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”

SupportedOrientations=”PortraitOrLandscape” Orientation=”Portrait”

mc:Ignorable=”d” d:DesignHeight=”768″ d:DesignWidth=”480″

shell:SystemTray.IsVisible=”True”>

<!–LayoutRoot is the root grid where all page content is placed–>

<Grid x:Name=”LayoutRoot”>

<Grid.Background>

<ImageBrush ImageSource=”images/Back.png”/>

</Grid.Background>

<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=”Customer Data” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>

</StackPanel>

<!–ContentPanel – place additional content here–>

<Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,-15,12,0″>

<StackPanel Orientation=”Vertical”>

<TextBlock Text=”First Name:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtFirstName” />

<TextBlock Text=”Last Name:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtLastName”/>

<TextBlock Text=”Address:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtAddress” />

<TextBlock Text=”City:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtCity”/>

<TextBlock Text=”Zip:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtZip” />

<TextBlock Text=”State:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtState”/>

</StackPanel>

</Grid>

</Grid>

<!–Sample code showing usage of ApplicationBar–>

<phone:PhoneApplicationPage.ApplicationBar>

<shell:ApplicationBar IsVisible=”True” IsMenuEnabled=”True” Opacity=”.2″>

<shell:ApplicationBarIconButton x:Name=”btnSave” IconUri=”images/Save.png” Text=”Save” Click=”btnSave_Click”/>

<shell:ApplicationBarIconButton x:Name=”btnCancel” IconUri=”images/Cancel.png” Text=”Cancel” Click=”btnCancel_Click”/>

</shell:ApplicationBar>

</phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>

  • Paste the code in Add.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 WP7PanoramaOData.CustomersModel;

using System.Data.Services.Client;

namespace WP7PanoramaOData

{

public partial class Add : PhoneApplicationPage

{

public  CustomersEntities ctx = newCustomersEntities(new Uri(http://10.12.1.223/ODataSQLWP7/CustomerService.svc/&#8221;, UriKind.Absolute));

     public Add()

{

InitializeComponent();

}

//   Load data for the ViewModel Items

 private void btnSave_Click(object sender, EventArgs e)

{

// Instantiate the Client

var newCustomer = newCustomerInfo();

newCustomer.FirstName = this.txtFirstName.Text.Trim();

newCustomer.LastName = this.txtLastName.Text.Trim();

newCustomer.Address = this.txtAddress.Text.Trim();

newCustomer.City = this.txtCity.Text.Trim();

newCustomer.Zip = this.txtZip.Text.Trim();

newCustomer.State = this.txtState.Text.Trim();

ctx.AddObject(“CustomerInfoes”, newCustomer);

ctx.BeginSaveChanges(insertUserInDB_Completed, ctx);

}

   private void insertUserInDB_Completed(IAsyncResult result)

{

ctx.EndSaveChanges(result);

}

   private  void btnCancel_Click(object sender, EventArgs e)

{

     this.NavigationService.Navigate(newUri(“/MainPage.xaml”, UriKind.Relative));

}

}

}

  • Lets check after addition of new data , the Windows Phone 7.1 UI:

  • Lets check the steps of updating the existing data :

  • Lets update the list with new data & perform HTTP PUT operation for updating data of Astoria services.

  •  After updating existing data, you can refresh the Main list to get updated data. Same update happens in database too.

  • Source code to perform Update Operation with OData WCF Services for SQL Server / SQL Azure database for Windows Phone 7.1 Mango:

<phone:PhoneApplicationPage

x:Class=”WP7PanoramaOData.Edit”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

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&#8243;

xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”

SupportedOrientations=”Portrait” Orientation=”Portrait”

mc:Ignorable=”d” d:DesignHeight=”768″ d:DesignWidth=”480″

shell:SystemTray.IsVisible=”True”>

<!–LayoutRoot is the root grid where all page content is placed–>

<Grid x:Name=”LayoutRoot”>

<Grid.Background>

<ImageBrush ImageSource=”images/Back.png”/>

</Grid.Background>

<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=”Edit Data” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>

</StackPanel>

<!–ContentPanel – place additional content here–>

<Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,-15,12,0″>

<StackPanel Orientation=”Vertical”>

<TextBlock Text=”First Name:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtFirstName” />

<TextBlock Text=”Last Name:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtLastName”/>

<TextBlock Text=”Address:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtAddress” />

<TextBlock Text=”City:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtCity”/>

<TextBlock Text=”Zip:” FontSize=”16″ Margin=”5″/>

<TextBox Name=”txtZip” />

<TextBlock Text=”State:” FontSize=”16″ Margin=”5″ />

<TextBox Name=”txtState”/>

</StackPanel>

</Grid>

</Grid>

<!–Sample code showing usage of ApplicationBar–>

<phone:PhoneApplicationPage.ApplicationBar>

<shell:ApplicationBar IsVisible=”True” IsMenuEnabled=”True” Opacity=”.2″>

<shell:ApplicationBarIconButton x:Name=”btnSave” IconUri=”images/Save.png” Text=”Save” Click=”btnSave_Click”/>

<shell:ApplicationBarIconButton x:Name=”btnCancel” IconUri=”images/Cancel.png” Text=”Cancel” Click=”btnCancel_Click”/>

</shell:ApplicationBar>

</phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>

  • Edit.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 WP7PanoramaOData.CustomersModel;

using System.Data.Services.Client;

namespace WP7PanoramaOData

{

public partialclassEdit : PhoneApplicationPage

{

public CustomersEntities ctx = newCustomersEntities(newUri(http://10.12.1.223/ODataSQLWP7/CustomerService.svc/&#8221;, UriKind.Absolute));

public Edit()

{

InitializeComponent();

}

privatevoid btnSave_Click(object sender, EventArgs e)

{

var qry = ctx.CreateQuery<CustomerInfo>(“CustomerInfoes”).AddQueryOption(“$filter”, “FirstName eq” + “\'” + “Maria” + “\'”);

qry.BeginExecute(r =>

{

var query = r.AsyncState asDataServiceQuery<CustomerInfo>;

               try

{

            Deployment.Current.Dispatcher.BeginInvoke(() =>

{

                var result = query.EndExecute(r).First();

result.FirstName = this.txtFirstName.Text;

result.LastName = this.txtLastName.Text.Trim();

result.Address =  this.txtAddress.Text.Trim();

result.City = this.txtCity.Text.Trim();

result.Zip = this.txtZip.Text.Trim();

result.State = this.txtState.Text.Trim();

ctx.UpdateObject(result);

ctx.BeginSaveChanges(changeUserInDB_Completed, ctx);

});

}

      catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

}, qry);

}

private void changeUserInDB_Completed(IAsyncResult result)

{

ctx.EndSaveChanges(result);

}

private void btnCancel_Click(object sender, EventArgs e)

{

this.NavigationService.Navigate(newUri(“/MainPage.xaml”, UriKind.Relative));

}

}

}

 

Consuming SQL Server/SQL Azure Data in Windows Phone 7.1 & Android through OData WCF Data Services & Entity Frameworks


Consuming data from SQL Server or SQL Azure database in Client Smart Devices like Windows Phone 7.1 , Android , iPhone or iPad is quite easy through the use of OData WCF Services. In previous posts , I already described how to consume data from live OData AtomPub feed showed in XML format. But, in this article I want to show how to consume SQL Server / SQL Azure data in Windows Phone & Android devices with the help of OData WCF services & entity frameworks where the service will be hosted in remote IIS & deployed SQL Server/SQL Azure database instance.

  • For creating solutions, let’s first start by creating an empty asp.net web application from Visual Studio.

  • Start by connecting with your SQL Server / SQL Azure database with Visual Studio .

  • Next, add data in the tables of SQL Server / SQL Azure database.

  • Next, Add an ADO.NET Entity Framework Model from Visual Studio to connect with SQL Server / SQL Azure database & save the connection string in web.config.

  • Connect with your database with proper credentials

  • Click on Next to select Tables, Views , Stored Procedures to select data.

  •  Now Add a WCF Service in the project & modify the code as like this:

using System;

using System.Collections.Generic;

using System.Data.Services;

using System.Data.Services.Common;

using System.Linq;

using System.ServiceModel.Web;

using System.Web;

namespace ODataSQLWP7

{

public class CustomerService : DataService<CustomersEntities>

{

// This method is called only once to initialize service-wide policies.

public static void InitializeService(DataServiceConfiguration config)

{

// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

// Examples:

// config.SetEntitySetAccessRule(“MyEntityset”, EntitySetRights.AllRead);

// config.SetServiceOperationAccessRule(“MyServiceOperation”, ServiceOperationRights.All);

config.SetEntitySetAccessRule( “CustomerInfoes”, EntitySetRights.All);

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

}

  •  Now check the service in browser & it looks like this:

  • Reason of the error: It’s due to the permission set not configured for IIS to deploy the SQL Server/SQL Azure database data. For SQL Azure database while creating the database in Windows Azure portal , you need to set the firewall settings definitely to 0.0.0.0 to 255.255.255.255 in order to deploy the SQL Azure database in IIS.
  • Now Right-Click on the project , select Property -> Package/Publish Web tab: 

  • Remember to check the settings: Include all databases in  Package/Publish SQL tab.
  •  Next , Click on Package/Publish SQL options: Click on Import from Web.config to generate your SQL Server/SQL Azure database connection strings.
  • Click on Connection String for destination database & add your destination database which will be hosted in IIS.
  • Click on the checkbox under Source database information: Pull data/or schema from existing database.
  • Under database scripting options select Schema only (if you would like generate schema only) or Schema & Data for generating schema & data deployement both.

  • Now , add user to login to the deployed database from SQL Server Management Studio by right clicking on Security -> New Login 

  • Add user for login as ODataUser from Windows Add Users – Groups utility , alternatively , you can add user from right-clicking My Computer -> Manage-> Users & Groups -> User -> Add User.

  • Now under the User Mapping tab add the database that you would like to deploy & click on db_datareader & db_datawriter. Click OK.

  • Deploy the Web Service in IIS from Web Deploy wizard in Visual Studio.

  • Next, open the Application Pool in IIS manager which holds the deployed service & click on advanced settings : Select Process Model as Application Pool Idenity -> Under Custom account Set the account credentials which you have set under the SQL Server logins section.

  • After this settings, now access the Customer Info  with the Service URL settings & it will show the entire RSS feed in AtomPub/ JSON format from the SQL Server / SQL Azure database.

  • It means OData WCF service now able to access the SQL Server/ SQL Azure data in AtomPub format hosted in remote IIS. Next , It’s time to create the Client applications:
  • First take a Windows Phone Panorama Project & modify the MainPage.XAML as like this:

<controls:PanoramaItem Header=”first item”>

<!–Double line list with text wrapping–>

<ListBox x:Name=”lst” Margin=”0,0,-12,0″ ItemsSource=”{Binding}”>

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Margin=”0,0,0,17″ Width=”432″>

<TextBlock Text=”{Binding FirstName}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

<TextBlock Text=”{Binding LastName}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

<TextBlock Text=”{Binding Address}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextSubtleStyle}” />

<TextBlock Text=”{Binding City}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextSubtleStyle}” />

<TextBlock Text=”{Binding State}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextSubtleStyle}” />

<TextBlock Text=”{Binding Zip}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextSubtleStyle}” />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</controls:PanoramaItem>

  • Modify 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 WP7PanoramaOData.CustomersModel;

using System.Data.Services.Client;


namespace WP7PanoramaOData

{

public partial classMainPage : PhoneApplicationPage

{

// Constructor

public MainPage()

{

InitializeComponent();

// Set the data context of the listbox control to the sample data

DataContext = App.ViewModel;

this.Loaded += newRoutedEventHandler(MainPage_Loaded);

}

//   Load data for the ViewModel Items

private void MainPage_Loaded(object sender, RoutedEventArgs e)

{

var ctx = newCustomersEntities(newUri(http://10.12.1.223/ODataSQLWP7/CustomerService.svc/&#8221;));

var coll = new System.Data.Services.Client.DataServiceCollection<CustomerInfo>(ctx);

lst.ItemsSource = coll;

coll.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);

var qry = “/CustomerInfoes”;

coll.LoadAsync(new Uri(qry, UriKind.Relative));

}

void coll_LoadCompleted(object sender, LoadCompletedEventArgs e)

{

if (e.Error != null)

{

MessageBox.Show(e.Error.Message);

}

}

  • Remember to add Service Reference to your Windows Phone application by referencing the service hosted in IIS:

  • Check the View in Windows Phone 7 :

  • Adding View for Android SmartPhones consuming data from SQL Server / SQL Azure database through OData WCF Data Services:

package com.example.ODataAndroid;

import java.util.ArrayList;

import java.util.List;

import android.app.Activity;

import android.os.Bundle;

import org.odata4j.consumer.ODataConsumer;

import org.odata4j.core.OEntity;

import android.app.ListActivity;

import android.widget.ArrayAdapter;

public class ODataSQLAndroidActivity extends ListActivity {

/** Called when the activity is first created. */

@Override

public void  onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this,  android.R.layout.simple_list_item_1, GetExpenseReports()));

        getListView().setTextFilterEnabled(true);

    }

    ArrayList<String> GetExpenseReports()

    {

    ArrayList<String> listUI =new ArrayList<String>();

    ODataConsumer c = ODataConsumer.create( http://10.12.1.223/ODataSQLWP7/CustomerService.svc/);

    List<OEntity> listExpenses = c.getEntities( “CustomerInfoes”).execute().toList();

for(OEntity expense:listExpenses) {

    listUI.add(expense.getProperty( “ID”).getValue().toString()

    + “:” + expense.getProperty(“FirstName”).getValue().toString()

    + expense.getProperty(“LastName”).getValue().toString()

    + “\n”+ expense.getProperty(“Address”).getValue().toString()

    + “\n” + expense.getProperty(“City”).getValue().toString()

    + “\n”+ expense.getProperty(“State”).getValue().toString()

    );

    }

return  listUI;

    }

    }

  • Check out the SQL Server / SQL Azure database data in Android device:

Consuming OData WCF REST Service from Android Client Device


As in my previous blog , already mentioned to create about OData Service feed in ATOM format which can be consumed in Windows Phone 7, Android, iPhone/iPAD , Silverlight,PHP, Windows Azure Table Storage clients.

  • Lets check , how to consume the OData WCF REST service in Android client. To work with OData Android client lets download Odata4j Android client library from RESTlet: http://www.restlet.org/downloads/ & select the OData4j-Bundle.jar in Java Build Path of your Android project.
  • Next, to consume OData service from android device, we need to host the service in IIS. In my demo, i have hosted it in IIS 7.5.
  • Now, Start develop an android client application which can consume OData feed.
  • Modify AndroidManifest.xml as it can consume feed from internet from native application:

<uses-permissionandroid:name=“android.permission.INTERNET”>

</uses-permission>

   Write code for  Activity.java :

package com.example.android.OData;

import java.util.ArrayList;

import java.util.List;

import org.odata4j.consumer.ODataConsumer;

import org.odata4j.core.OEntity;

import android.app.ListActivity;

import android.os.Bundle;

import android.widget.ArrayAdapter;

public class JsonGrabbingConsumerExampleActivity  extends  ListActivity {

/** Called when the activity is first created. */

@Override

public void  onCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this,   android.R.layout.simple_list_item_1, GetExpenseReports()));

        getListView().setTextFilterEnabled(true);

    }

// read expenses odata feed

    ArrayList<String> GetExpenseReports()

    {

// build a simple array list of strings to test things out

        ArrayList<String> listUI = new ArrayList<String>();

// use odata4j consumer

        ODataConsumer c = ODataConsumer.create(http://10.12.1.223/ODataSample1/Service.svc);

// run a query just for Pending states

        List<OEntity> listExpenses = c.getEntities(“SampleCustomerData”).execute().toList();

for(OEntity expense : listExpenses) {

    listUI.add(expense.getProperty(

“CustomerID”).getValue().toString()

    +

“; “ + expense.getProperty(“CustomerName”).getValue().toString()

    +

“; “ + expense.getProperty(“CustomerNotes”).getValue().toString()

    );

        }

return  listUI;   

    }

}

  • Checkout the output in Android 2.3:

Consuming OData WCF REST service from Windows Phone 7 Panorama Application


Consuming an OData (Open Data Protocol) in Client devices , Client services are quite easy. Open Data protocol , is a web protocol for querying and updating data and it was born of the need to break down data silos and increase their shared value. This allows data silos to interoperate between producers such as SQL Server, SharePoint servers, Cloud Storage Services, and consumers, for example Java, PHP, Silverlight, IIS, ASP.NET, AJAX.

OData incorporates with JSON, AtomPub, RSS to provide access to the  information from a range of applications, services, relational databases, file systems, content management systems (CMS), traditional websites.

Supported Platforms for OData Services:

  1. Microsoft Visual Studio 2008 SP1
  2. Microsoft Visual Studio 2010
  3. Microsoft SQL Server 2008 R2
  4. Microsoft Sharepoint 2010
  5. Microsoft Windows Azure Storage(Blobs, Tables, Queues)
  6. Microsoft SQL Azure
  7. Microsoft Office Excel 2010 PowerPivot
  • Lets create an OData WCF REST Service that for this purpose lets create an empty web application from Visual Studio

  • Lets add a new WCF Service in the application & named it as Service.SVC

  • Next , add the following Code to the service & check the resulting feed in browser.

using System;

using System.Collections.Generic;

using System.Data.Services;

using System.Data.Services.Common;

using System.Linq;

using System.ServiceModel.Web;

using System.Web;


namespace ODataSample1

{

public class Service : DataService<SampleDataSource>

{

// This method is called only once to initialize service-wide policies.

public static void InitializeService(DataServiceConfiguration config)

{

// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

// Examples:

// config.SetEntitySetAccessRule(“MyEntityset”, EntitySetRights.AllRead);

// config.SetServiceOperationAccessRule(“MyServiceOperation”, ServiceOperationRights.All);

config.SetEntitySetAccessRule(“*”, EntitySetRights.All);

config.SetServiceOperationAccessRule(“*”, ServiceOperationRights.All);

config.MaxResultsPerCollection = 100;

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

EntityPropertyMappingAttribute(“CustomerName”, SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, true)]

[DataServiceKey(“CustomerID”)]

public class CustomerRecord

{

public int CustomerID { get; set; }

public string CustomerName { get; set; }

public string CustomerEmail { get; set; }

public string CustomerNotes { get; set; }

public DateTime CustomerLastContact { get; set; }

}

public class SampleDataSource

{

private readonly List<CustomerRecord> _sampleCustomerRecordList;

public SampleDataSource()

{

_sampleCustomerRecordList = newList<CustomerRecord>();

for (int i = 0; i < 100; i++)

{

CustomerRecord CR = newCustomerRecord();

CR.CustomerID = i;

CR.CustomerName =string.Format(“FirstName{0} LastName{1}”, i.ToString(), i.ToString());

CR.CustomerEmail =string.Format(“Email{0}@{1}.com”, i.ToString(), i.ToString());

CR.CustomerNotes =string.Format(“Notes{0}.Notes{1}”, i.ToString(), i.ToString());

CR.CustomerLastContact =DateTime.Now.AddDays(-10000).AddHours(i);

_sampleCustomerRecordList.Add(CR);

}

}

public IQueryable<CustomerRecord> SampleCustomerData

{

get

{

return _sampleCustomerRecordList.AsQueryable();

}

}

}

}

  • Now check the Service status in Linqpad (http://www.linqpad.com) by adding the WCF service endpoint to the database/service endpoint connection.

  • Lets check the status of the feed by entering query (<atom:title>)(e.g : SampleCustomerData  for this demo)in the browser

  •  Check after entering query in the URL of the feed

  • Service endpoint shows successful OData feed , next add a Windows Phone Panorama Application with the solution to implement a smartClient to the OData REST application.

datasvcutil /uri:http://localhost:8554/Service.svc/ /out:.\ServiceModel.cs /Version:2.0 /DataServiceCollection

<!–Panorama item one–>

<controls:PanoramaItem Header=”first item”>

<ListBox x:Name=”lst” Margin=”0,0,-12,0″ ItemsSource=”{Binding}”>

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Margin=”0,0,0,17″ Width=”432″>

<TextBlock Text=”{Binding CustomerID}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

<TextBlock Text=”{Binding CustomerName}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

<TextBlock Text=”{Binding CustomerEmail}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

<TextBlock Text=”{Binding CustomerNotes}” TextWrapping=”Wrap” Margin=”12,-6,12,0″ Style=”{StaticResource PhoneTextExtraLargeStyle}” />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</controls:PanoramaItem>

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 ODataWP7Panorama.CustomersModel;

using System.Data.Services.Client;

namespace ODataWP7Panorama

{

public partial classMainPage : PhoneApplicationPage

{

public  SampleDataSource ctx = new SampleDataSource(new Uri(http://localhost:8554/Service.svc/&#8221;, UriKind.Absolute));

// Constructor

public MainPage()

{

InitializeComponent();

this.Loaded += newRoutedEventHandler(MainPage_Loaded);

// Set the data context of the listbox control to the sample data

}

// Load data for the ViewModel Items

private void MainPage_Loaded(object sender, RoutedEventArgs e)

{

var ctx = newSampleDataSource(newUri(http://localhost:8554/Service.svc/));

var coll = new  DataServiceCollection<CustomerRecord>(ctx);

lst.ItemsSource = coll;

coll.LoadCompleted +=newEventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);

var qry = “/SampleCustomerData”;

coll.LoadAsync(newUri(qry, UriKind.Relative));

}

void coll_LoadCompleted(object sender, LoadCompletedEventArgs e)

{

if (e.Error != null)

{

MessageBox.Show(e.Error.Message);

}

}

}

}

  • Now , lets the OData REST Service in Windows Phone 7.1 Client :