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:

SQL Server 2012 RC Installation Step by Step


SQL Server 2012 RC(Release Candidate) published on November 17th, 2011 as official product from Microsoft. The Release candidate has several bug fixes for BI (Business Intelligence) , Data Synchronization & High Availability.

  • Compared to CTP3 Denali is more compact in release mode & available in five different forms (both x86 & x64):
  • Express
  • Express with Tools
  • SQL Server 2012 Management Studio
  • Express DB (Local DB only)
  • Express with Advance Series(With SSRS, Full Text Search).

Download Today: http://www.microsoft.com/download/en/details.aspx?id=28151&WT.mc_id=aff-n-in-loc–pd

Next the Step by Step installation guide:

Extract the Express with Advanced Series SQL Server 2012 .exe as start installation as new instance:

Check the box : I accept the licence terms.

Next put you Features installation after verifying setup rules with Windows Domain settings.

Next , put the Installation Rules with Instance name that will re required to identify your SQL Server 2012 instance in your system.

Next , after calculating  Disk Space Requirements, it will start to check Server Configuration. Put your choice to set the instance of your SQL Server with Windows  domain a/c Login or Mixed Mode(Windows + SQL Server ) with sa account mode.

Next , if you would like to provide FILESTREAM configuration with SQL Server 2012 , you can configure it here.

Similar to User Instance Configuration ,

Next , Check out the box if you would like to install SQL Server Reporting Services 2012 with SQL Server Instance with Sharepoint integration.

Next , Start your Installation process of SQL Server 2012 & Check out the progress bar.

Next , you are done with your installation , so next explore the latest updates of SQL Server 2012 denali in developer preview.

 

Explore the latest SQL Server 2012 book in evaluation mode which will be in release on Spring 2012.

Download from here: https://skydrive.live.com/?cid=7f185b0e5a1ba82e#!/?cid=7f185b0e5a1ba82e&sc=documents&uc=1&nl=1&id=7F185B0E5A1BA82E%21142!cid=7F185B0E5A1BA82E&id=7F185B0E5A1BA82E%21142

So, now Work & explore your favourite database SQL Server 2012 & provide feedback.

%d bloggers like this: