# Friday, September 4, 2009

SQL Data Services underwent a massive change with the last CTP, eliminating the entity bag container, whatever they called it thingie and moved to a fully cloud-based relational model. Another major change was that it was given a new and more appropriate name: SQL Azure. You can get the CTP and have access to what I call SQL Server lite in the cloud. Since SQL Azure supports the fully relational model along with stored procedures and views, you can connect to SQL Azure with a regular old ADO.NET connection string like the following one, allowing you to code against SQL Azure with .NET the same way you did with plain old SQL Server.

Server=tcp:tpzlfbclx1.ctp.database.windows.net;Database=Northwind_Lite;User ID=Stevef;Password=myPassword;Trusted_Connection=False;

Once you are all signed up for the CTP you can go into the web based admin tools and create a database. I created a database called Northwind and another one called Northwind_Lite for testing.

image

To be honest, I am not sure what else you can do in the web interface. So you have to connect via SQL Management Studio to create your database schema. There is the first problem. SQL Azure does not support the object explorer view that you get in SQL Management Studio, so you will have to hack a little bit.

Connecting to SQL Azure with SQL Server Management Studio

This is not as easy as it sounds. :) Since you can’t connect through the object explorer, you will have to open a new TSQL Query window.

image

In the log in dialog, enter in the server name from the CTP’s connection string and the user name and password that you choose to administer the CTP.

image

SQL Azure does not support the “Use” statement, or the ability to change databases on your connection. So you have to cheat and use some of the advanced options when logging in. You can do this by selecting the “Options >>” button on the log in dialog and then selecting “Connection Properties”. Under the Connect to database option, you have to select the database that you want to work with, since the default will be the Master database and most likely you will not be building any applications using the Master database.

image

After you connect you will get an error about the inability to apply connection settings, which you can ignore.

image

You will notice right away that there is nothing in your database as the following SQL statement will show:

select * from sys.objects

We now have to migrate some database objects from our SQL Server database to SQL Azure.

Migrating Existing SQL Server Objects to a SQL Azure Database

It would be cool if there were some easy way to migrate your databases to SQL Azure in this CTP. There is not. I suspect that in future CTPs this will not be a problem. But for now, you have to get creative. Some hacks and shortcuts are in order.

To get started, let’s just copy over one table. To do this, open your local SQL Server in the object explorer. Drill down to the Northwind database and drill down into the Customers table. Right click and select Script Table as|CREATE To|Clipboard and you will have a nice CREATE TABLE statement on your clipboard.

 

image

Then paste the TSQL into the Query Window that is connected to your SQL Azure database. Here is what my generated TSQL looks like:

   1:  USE [Northwind]
   2:  GO
   3:   
   4:  /****** Object:  Table [dbo].[Customers]    Script Date: 09/04/2009 03:35:38 ******/
   5:  SET ANSI_NULLS ON
   6:  GO
   7:   
   8:  SET QUOTED_IDENTIFIER ON
   9:  GO
  10:   
  11:  CREATE TABLE [dbo].[Customers](
  12:      [CustomerID] [nchar](5) NOT NULL,
  13:      [CompanyName] [nvarchar](40) NOT NULL,
  14:      [ContactName] [nvarchar](30) NULL,
  15:      [ContactTitle] [nvarchar](30) NULL,
  16:      [Address] [nvarchar](60) NULL,
  17:      [City] [nvarchar](15) NULL,
  18:      [Region] [nvarchar](15) NULL,
  19:      [PostalCode] [nvarchar](10) NULL,
  20:      [Country] [nvarchar](15) NULL,
  21:      [Phone] [nvarchar](24) NULL,
  22:      [Fax] [nvarchar](24) NULL,
  23:   CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
  24:  (
  25:      [CustomerID] ASC
  26:  )
  27:  WITH
  28:   (
  29:  PAD_INDEX  = OFF, 
  30:  STATISTICS_NORECOMPUTE  = OFF, 
  31:  IGNORE_DUP_KEY = OFF, 
  32:  ALLOW_ROW_LOCKS  = ON, 
  33:  ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  34:  ) 
  35:  ON [PRIMARY]
  36:   
  37:  GO
  38:   

We already know that SQL Azure does not support USE, so eliminate lines 1&2 and press F5. You will see that line 5 also is not supported, so eliminate that and keep going by pressing F5 again. You will see that ANSI_NULLs, PAD_INDEX, ALLOW_ROW_LOCKS, ALLOW_PAGE_LOCKS, and ON [PRIMARY] are not supported, so you will have to eliminate them as well. Your new trimmed down SQL Azure SQL script looks like this:

   1:  SET QUOTED_IDENTIFIER ON
   2:  GO
   3:  CREATE TABLE [dbo].[Customers](
   4:      [CustomerID] [nchar](5) NOT NULL,
   5:      [CompanyName] [nvarchar](40) NOT NULL,
   6:      [ContactName] [nvarchar](30) NULL,
   7:      [ContactTitle] [nvarchar](30) NULL,
   8:      [Address] [nvarchar](60) NULL,
   9:      [City] [nvarchar](15) NULL,
  10:      [Region] [nvarchar](15) NULL,
  11:      [PostalCode] [nvarchar](10) NULL,
  12:      [Country] [nvarchar](15) NULL,
  13:      [Phone] [nvarchar](24) NULL,
  14:      [Fax] [nvarchar](24) NULL,
  15:   CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
  16:  (
  17:      [CustomerID] ASC
  18:  )WITH 
  19:      (STATISTICS_NORECOMPUTE  = OFF, 
  20:          IGNORE_DUP_KEY = OFF) 
  21:  ) 
  22:  GO
  23:   

Run this and you will have a new Customers table! Unfortunately there is no data in there, but we will get to that soon.

image

If you are moving a lot of tables and foreign key constraints, etc, you should use the SQL Azure Migration Wizard developed by George Huey. This tool,available on codeplex, will assist you in migrating your SQL Server schemas over to SQL Azure. Wade Wegner blogged about it here, including an instructional video.

Unfortunately there is no such tool for migrating data that I know of. Time for the next hack.

Migrating Data from SQL Server to SQL Azure

I thought that maybe I can cheat the same way I altered the connection settings and use SSIS to migrate the data. I choose the ADO.NET option and entered in all of the data, but it bombed. Then I tried my old reliable tool, Red Gate’s SQL Data Compare. No go. But it was worth a try, since it got me thinking. I created a new database locally called “Azure_Staging” and ran the same CREATE TABLE script there, creating a blank Customers table. I then ran SQL Data Compare using the full Customer table in Northwind as my source and my newly created blank Customer table in Azure_Staging as the destination.

Of course SQL Data Compare found 91 missing rows and I launched the Synchronization Wizard.

image

Click through it and on the 3rd page, click on the “View SQL Script…” button and copy and paste the generated SQL.

image

Copy and paste just the 91 INSERT INTO statements into your SQL Azure Query Window and run it. Now we have data in SQL Azure!

image

Unfortunately this is not the best situation, having to manually create some TSQL scripts, but this is an early CTP. I am sure that future CTPs will make this much easier.

posted on Friday, September 4, 2009 4:19:51 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, September 3, 2009

Developers have been using the REST specification for some time. If you are using Microsoft tools, ADO.NET Data Services aka Astoria is a very popular way to work with REST data. What you may not know is that Astoria works on top of WCF and you can write your own REST services outside of the Astoria model using WCF. WCF 3.5 SP1 gives us quite a few hooks to build our own RESTful services, however, it still takes a lot of manual wiring up by the developer. By now you all should know that I hate plumbing code.

Microsoft introduced the WCF REST Starter Kit, a set of WCF extensions and Visual Studio project templates to eliminate the plumbing code when building RESTful service with WCF. The five Visual Studio templates are:

  • REST Singleton Service
  • REST Collection Service
  • ATOM Feed Service
  • ATOMPub Service
  • HTTP Plain XML Service
  •  

    As explained in the developers guide to the WCF REST Starter Kit, the templates do the following:

    REST Singleton Service-Produces a service that defines a sample singleton resource (SampleItem) and the full HTTP interface for interacting with the singleton (GET, POST, PUT, and DELETE) with support for both XML and JSON representations.

    REST Collection Service-Similar to the REST Singleton Service only it also provides support for managing a collection of SampleItem resources.

    Atom Feed Service-Produces a service that exposes a sample Atom feed with dummy data.

    AtomPub Service-Produces a fully functional AtomPub service capable of managing collections of resources as well as media entries.

    HTTP Plain XML Service-Produces a service with simple GET and POST methods that you can build on for plain-old XML (POX) services that don’t fully conform to RESTful design principles, but instead rely only on GET and POST operations.

    While the REST Singleton is interesting, it is only useful if you are exposing one item, so the REST Collection is more suitable for interaction with a database driven dataset. The Atom Feed template is interesting but it is more useful if you are building feeds similar to RSS, so the AtomPub Service is more useful. The POX is a good option if you need to do something custom.

    While the REST WCF Starter Kit also provides some client libraries for easier interaction with your RESTful data, we will focus on the creation of the services.

    You can use Telerik OpenAccess as a data source of your REST Collection service. To do so you have to wire up some code in your svc file. Sound like a lot of work? Enter the OpenAccess WCF Wizard I wrote about before.

     

    If you create a project in Visual Studio to contain your data access layer and another to contain the REST Collection (using the new REST Collection template available from the WCF REST Starter Kit), you can point the Telerik WCF OpenAccess WCF Wizard at the data access layer project and then automatically generate the svc file and the corresponding CS file (shown by the arrow in our Visual Studio solution below.)

    image

    Just for a sanity check, let’s run our service by selecting the svc file and saying “view in browser”. You should see the RESTful XML representation as show below (make sure you turn off feed view in IE):

     image

    Now let’s consume this service from a Silverlight application. The WCF REST Starter Kit provides the developer with two classes, HttpClient and HttpMethodExtensions to help you consume the WCF RESTful service. Unfortunately they are not supported in Silverlight (or at least I can’t figure it out. :) )

    We’ll use plain old HTTPWebRequest instead.  But first I will create a grid in my XAML code like so:

    <data:DataGrid x:Name="dataGridCustomers" AutoGenerateColumns="False" ItemsSource="{Binding}">
        <data:DataGrid.Columns>
            <data:DataGridTextColumn Binding="{Binding Path=CompanyName}" Header="Company Name">
            </data:DataGridTextColumn>
            <data:DataGridTextColumn Binding="{Binding Path=ContactName}" Header="Contact Name">
            </data:DataGridTextColumn>
        </data:DataGrid.Columns>
    </data:DataGrid>

    I will create a LoadData() method to load the data on the page load or a “refresh” button event. Being Silverlight, of course we will use some asynchronous processing.

       1:  private void LoadData()
       2:  {
       3:      //address of your REST Collection service
       4:      string url= "http://localhost:60613/Customers.svc";
       5:      //set up the web resquest
       6:      HttpWebRequest rest = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;
       7:      //HTTP GET (REST uses the standard HTTP requests)
       8:      rest.Method = "GET";
       9:      //async callback
      10:      rest.BeginGetResponse(new AsyncCallback(ReadAsyncCallBack), rest);
      11:  }

     

    First we have to set a reference to our service in lines 4 & 6. Then we tell the HttpWebRequest to use an HTTP GET (line 8), this is the power of REST, it uses the standard HTTP requests (GET, POST, PUT, DELETE). On line 10 is where we begin our asynchronous call to ReadAsyncCallback() shown here.

       1:  private void ReadAsyncCallBack(IAsyncResult iar)
       2:  {
       3:      
       4:      //catch the HttpWebRequest
       5:      HttpWebRequest rest = (HttpWebRequest)iar.AsyncState;
       6:      HttpWebResponse response = rest.EndGetResponse(iar) as HttpWebResponse;
       7:      
       8:      var result = Customer.GetCustomersFromAtom10Stream(response.GetResponseStream());
       9:      //code block to handle the async call
      10:      this.Dispatcher.BeginInvoke( () =>
      11:          {
      12:              //build a collection (customers)
      13:              var customers = 
      14:                new System.Collections.ObjectModel.ObservableCollection<Customer>();
      15:              foreach (var customer in result)
      16:              {
      17:                  customers.Add(customer);
      18:              }
      19:              //bind to the grid when done
      20:              this.dataGridCustomers.DataContext = customers;
      21:          });
      22:  }

    ReadAsyncCallback() is the handler for the asynchronous call we did in LoadData(). We obtain a reference to the HttpWebRequest (lines 5-6) and then get the results back in line 8. Then we use a code block to build an ObservableCollection of Customers and fill them in a loop of the results (lines 15-18) and bind the data to the grid in line 20. The results are data binded to a grid as shown below.

    image

    Since Silverlight doesn’t support HTTP methods that do an update, we can’t do updates without a wrapper on the server. So we will stop the demo with just the read operation. Remember, if you are using a non-Silverlight client such as ASP.NET you can use the HttpClient and HttpMethodExtensions classes for an easier client coding experience.

    Grab the Telerik OpenAccess WCF Wizard here and the sample code from this blog post here.

    posted on Thursday, September 3, 2009 8:59:03 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Wednesday, September 2, 2009

    I have written a white paper for the Microsoft Oslo team that is available on MSDN here. The paper is titled: “Using Oslo to Speed Up Database Development” and shows how you can use the new M language to model databases, browse that model in Quadrant, and tap into the power of the Oslo Repository.

    The paper shows how the model you make is mapped to TSQL and to SQL Server objects, including Tables and Views. It is pretty cool to see the following M type and its M values and how they will map to a TSQL script to create a People table and INSERT INTO statements for the Steve and Mike rows.

       1:  //Types
       2:  type Person
       3:  {
       4:      Id : Integer32;
       5:      Name : Text#50;
       6:      Age : Integer32;
       7:  }
       8:  //Values
       9:  People:Person*;
      10:  People
      11:  {
      12:      { Id=>1, Name=>"Steve", Age=>36},
      13:      { Id=>2, Name=>"Mike", Age=>29}
      14:  }

     

    The corresponding TSQL will look like this:

       1:  create table [OsloDemo].[People]
       2:  (
       3:    [Age] int not null,
       4:    [Id] int not null,
       5:    [Name] nvarchar(50) not null
       6:  );
       7:  go
       8:   
       9:  insert into [OsloDemo].[People] ([Id], [Name], [Age])
      10:   values (1, N'Steve', 36)
      11:  ;
      12:   
      13:  insert into [OsloDemo].[People] ([Id], [Name], [Age])
      14:   values (2, N'Mike', 29)
      15:  ;
      16:  go

     

    Developers will like to model in M since it will abstract them from the ins and outs of the database.

    In addition the paper shows how to use the repository and how modeled types will benefit from using the repository. In addition I discuss a little abut the DSL capabilities of Oslo using M Languages. What is cool is that I also talk about Telerik’s LINQ to M at the end, and how to use it with the DSL and M languages with Visual Studio and C#.

    You can get the paper here.

    posted on Wednesday, September 2, 2009 9:19:14 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Friday, August 28, 2009

    Apparently iPhones explode. There is a report today of a 15 year old in Belgium who’s iPhone exploded. In addition there was a report about two weeks ago of an iPhone in France and there have been other reports in the UK and across the US. Luckily only minor injuries have been reported.

    The European Commission is starting to investigate. Apparently Apple has not issued a warning and it could be a fluke.

    posted on Friday, August 28, 2009 10:39:59 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Wednesday, August 26, 2009

    The following video shows how to use the Telerik OpenAccess WCF Wizard with ADO.NET Data Services. The video is done by .NET Ninja in training Peter Bahaa and uses more or less the same code I showed yesterday on my blog. Enjoy!

     

    Telerik OpenAccess WCF Wizard Part II- Astoria from Stephen Forte on Vimeo.

    posted on Wednesday, August 26, 2009 9:20:33 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Tuesday, August 25, 2009

    I have been a big fan of using the RESTful ADO.NET Data Services (aka Astoria). If you want to use Astoria out of the box without any modifications you really have to use the Entity Framework. But as long as you are using a data access library that supports IEnumerable and IQueryable (and IUpdateable to be useful for CRUD) you can use Astoria with just a little bit of extra work. 

    Telerik OpenAccess supports LINQ and IUpdateable and can be used in Astoria as shown here. In a nutshell you have to first create your data access layer, then a web site to host your ADO .NET Data Service and then a client (in our case a Silverlight app.) You would have a solution that will look like this:

    image

    The problem is that if you use anything other than the Entity Framework, you need to do a little extra plumbing. In our case using OpenAccess, you have to create the IQueryable interfaces for all of your entities manually. You would need something like this:

       1:  public IQueryable<Customer> Customers
       2:  {
       3:      get
       4:      {
       5:          return this.scope.Extent<Customer>();
       6:      }
       7:  }

     

    The scope variable you see on line # 5 is an instance of IObjectScope. IObjectScope is how OpenAcces implements the actual data context. According to the OpenAccess team, you have to add a few extra lines of code with these IQueryable interfaces into an “OADataContext” class. To be honest, I don’t want to do that, too much plumbing code.

    Enter the OpenAccess WCF Wizard I wrote about before.

    You can use the Wizard to generate the OADataContext file as well as the Astoria service file. Just point the wizard to the DAL layer file and select Astoria from the menu and generate the files and add them to the project (it is ok to overwrite the original CS file supporting the SVC file, just make sure you have the correct namespaces).

    image

    Now your Astoria service will look like this:

       1:      [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
       2:      public class WebDataService : DataService<AstoriaDataContext>
       3:      {
       4:          protected override void HandleException(HandleExceptionArgs args)
       5:          {
       6:              base.HandleException(args);
       7:          }
       8:   
       9:          // This method is called only once to initialize service-wide policies.
      10:          public static void InitializeService(IDataServiceConfiguration config)
      11:          {
      12:              //let all the entities be full access (CRUD)
      13:              config.SetEntitySetAccessRule("*", EntitySetRights.All);
      14:          }
      15:      }
      16:  }

    This is pretty standard Astoria stuff, line #13 does all of the Astoria magic.

    Now let’s look at our Silverlight client.  First let’s create some XAML, I will just show you the DataGrid code here:

       1:  <data:DataGrid Grid.ColumnSpan="2" x:Name="dataGridCustomers" AutoGenerateColumns="False" ItemsSource="{Binding}">
       2:      <data:DataGrid.Columns>
       3:         <data:DataGridTextColumn Binding="{Binding Path=CompanyName}" Header="Company Name"></data:DataGridTextColumn>
       4:         <data:DataGridTextColumn Binding="{Binding Path=ContactName}" Header="Contact Name"></data:DataGridTextColumn>
       5:      </data:DataGrid.Columns>
       6:  </data:DataGrid>

     

    As I wrote the other day, you still have to use a service and call the service asynchronously. In our Silverlight application we will then set a service reference to our Astoria Service, allowing us to write LINQ statements against the RESTful Astoria service.

    image

    Just like before we will have a LoadData() private method that our page load and “refresh” buttons will call. This will use LINQ to talk to the Astoria service and fetch all of the Customers. First we set up a LINQ data context (lines 4-5) and then a LINQ query (lines 8-9). Then we will use a code block (lines 13-14) to catch the async code (instead of a separate event handler) and perform the actual binding to the grid.

       1:  private void LoadData()
       2:  {
       3:      //this uses the LINQ to REST proxy (WebDataService)
       4:      AstoriaDataContext dat = new AstoriaDataContext(
       5:          new Uri("WebDataService.svc", UriKind.Relative));
       6:      
       7:      //link statement to get the data, can use WHERE, Orderby, etc
       8:      var customers = 
       9:          (from c in dat.Customers select c) as DataServiceQuery<WebDataService.Customer>;
      10:   
      11:      //use code block to perform the binding at the end of the async call
      12:      //casting the Customers to a LIST
      13:      customers.BeginExecute(
      14:          (ar) => dataGridCustomers.DataContext = customers.EndExecute(ar).ToList(), null);
      15:  }

    When we run our code, we will get data right away:

    image

    We can also perform an update. We have a global collection called editedCustomers and we trap the BeginEdit method of the Silverlight grid and put an instance of each row (a Customer) that was edited into this collection. Then we provide an update button that will call UpdateData() shown below. UpdateData() will loop through each dirty customer in the editedCustomers collection (lines 8-11) and update them using the Astoria LINQ services (lines 10-11). Inside of our loop we are doing another code block (lines 12-25) to catch the async update. We use a counter to figure out when we are done (lines 16-22), since in an async model, your 3rd update out of 5 can be the last one to finish!

     

       1:  private void UpdateData()
       2:  {
       3:      //this uses the LINQ to REST proxy (WebDataService)
       4:      AstoriaDataContext dat = new AstoriaDataContext(
       5:          new Uri("WebDataService.svc", UriKind.Relative));
       6:   
       7:      //editedCustomers is a local collection containing only the dirty records
       8:      foreach (WebDataService.Customer customer in editedCustomers)
       9:      {
      10:          dat.AttachTo("Customers", customer);
      11:          dat.UpdateObject(customer);
      12:          //code block to handle the async call to updates
      13:          dat.BeginSaveChanges(
      14:              (ar) =>
      15:              {
      16:                  updatedCounter++;
      17:                  //once we are finished with all items in the collection, we are done
      18:                  if (updatedCounter == this.editedCustomers.Count)
      19:                  {
      20:                      MessageBox.Show("Customers have been changed successfull!", "Saving Changes", MessageBoxButton.OK);
      21:                      this.editedCustomers.Clear();
      22:                  }
      23:   
      24:                  dat.EndSaveChanges(ar);
      25:              }
      26:              , null);
      27:      }
      28:  }

     

    That is it to build an Astoria based Silverlight application using OpenAccess. The OpenAccess WCF Wizard takes care of building the OpenAccess specific plumbing DataContext class for you as well as the Astoria service. Soon I will post another video by .NET Ninja in training Peter Bahaa on this demo as well as some more code examples using the WCF REST Toolkit and the OpenAccess WCF Wizard.

    The code is available here. Enjoy!

    posted on Tuesday, August 25, 2009 11:31:37 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Sunday, August 23, 2009

    Last week I showed how to use the Telerik OpenAccess WCF Wizard on this blog. The wizard creates some of the boring WCF code for you automatically. You can create endpoints for WCF, Astoria, REST collection and ATOM Pub services. Our first demo used WCF, later we will show you the other services. This is what we did:

    • Created a data access layer automatically using OpenAccess
    • Created a WCF Service automatically using the wizard
    • Created a Silverlight 3.0 application that used WCF to databind the Customers table to a datagrid, enabling editing automatically

    Here is a video by Peter Bahaa (aka Pedro), .NET ninja in training, using the wizard with the above scenario. You can get the code here. Enjoy!

    Telerik OpenAccess WCF Wizard Part I from Stephen Forte on Vimeo.

    posted on Sunday, August 23, 2009 7:34:48 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Wednesday, August 19, 2009

    Microsoft’s Silverlight 3.0 is a great new platform for building line of business applications. With every new technology advancement, we always seem to lose something. With Silverlight we lose the dirt simple data access since Silverlight does not support System.Data.SQLClient and talking to a database directly. This forces us into a service oriented architecture and an asynchronous model. While this is definitely a best practice, it sometimes takes a little getting used to.

    With Silverlight we have to wrap up our data access layer into WCF services. (Or Astoria, RIA Services, or something similar.) It is also pretty standard to use some kind of ORM like the Entity Framework or Telerik OpenAccess to map to your database tables and then expose those entities as part of your WCF service. Mapping tables to entities may save you time, however, the part that bothers me is that there is a lot of generic “plumbing” code that has to get written for the WCF service to function.

    That is why Telerik created the OpenAccess WCF Wizard. The Telerik OpenAccess WCF Wizard is a tool that will automatically create the C# “plumbing” code and necessary project files for using OpenAccess entities with the following services:

    • Astoria (ADO .NET Data Services)
    • WCF
    • REST Collection Services (WCF REST Starter Kit)
    • ATOM Publishing Services (WCF REST Starter Kit)

    Using the wizard is pretty easy. If you already have a project with OpenAccess mapped entities in it, all you have to do is point the wizard to that location and have it generate the scv and .cs files of the WCF service (or Astoria, REST Collection or ATOM Pub service) as shown below. This will eliminate the need for you to write all of the WCF plumbing code.

    image

     

    We’ll map the Northwind tables and run the wizard and then create a WCF service project. Once you create the service, replace the .cs file with the one generated by the wizard and then create a new Silverlight project (or any project that wants to communicate with your OpenAccess enabled WCF service.) Then set a Service Reference to the WCF service and you can start to consume the it. Your projects in the solution will look like this:

    image

    Where:

    • OA.WCFWizard.Demo.DAL is the project containing your OpenAccess entities (mapped to Northwind tables).
    • OA.WCFWizard.Demo.SL is the project containing your Silverlight project, including the service reference to your WCF service. (First arrow.)
    • OA.WCFWizard.Demo.WCFService is the project containing the WCF service created by the WCF wizard (second arrow.)
    • OA.WCFWizard.Demo.Web is the asp.net site hosting your Silverlight application

    Writing some Silverlight code to consume the WCF service

    Consuming the service is pretty easy once you have the service reference set up. We’ll start with some basic XAML, but I will spare you the major XAML details since I am not a XAML expert. Here is my datagrid in XAML, notice that I am using data binding and predefined columns to make life a little easier:

    <data:DataGrid x:Name="dataGridCustomers" Grid.ColumnSpan="2" AutoGenerateColumns="False" ItemsSource="{Binding}">
         <data:DataGrid.Columns>
             <data:DataGridTextColumn Binding="{Binding Path=CompanyName}" Header="Company Name"></data:DataGridTextColumn>
             <data:DataGridTextColumn Binding="{Binding Path=ContactName}" Header="Contact Name"></data:DataGridTextColumn>
         </data:DataGrid.Columns>
    </data:DataGrid>

    When filled, it looks like this:

    image

    Pretty basic stuff, if you want more advanced looking grids and controls, talk to a designer. :)

    Ok, so how can we easily consume this service and bring this data from Northwind via OpenAccess and WCF to the Silverlight grid? Once you have a service reference set up (NorthwindWCFService) in your Silverlight project, you have to do a few things to call it. I created a LoadData() method to contain the code to fill the grid. We can call this on the page load event as well as on the UI with a “refresh” button, or after any “save” method.

    Inside of the LoadData() method, first you have to create an instance of the proxy or the “client” as shown in line 4 of the first code block below. Once you have this set up, you then have to register an event for the method you are going to call, as shown on line 6 below. This means that when you call your ReadCustomers method asynchronously the client_ReadCustomersCompleted event handler will fire when the ReadCustomers method is done. This is where you put your binding code (more on that in a second.)  Lastly we have to call our ReadCustomers method, we can only call the asynchronous version of this method as shown in line 9.

       1:  private void LoadData()
       2:  {
       3:      //ref to our service proxy
       4:      NorthwindWCFService.SampleWCFServiceClient wcf = new NorthwindWCFService.SampleWCFServiceClient();
       5:      //register the event handler-can move this up if you want
       6:      wcf.ReadCustomersCompleted += new EventHandler<NorthwindWCFService.ReadCustomersCompletedEventArgs>(client_ReadCustomersCompleted);
       7:      //make an async call to ReadCustomer method of our WCF serice
       8:      //get only the first 100 records (default)
       9:      wcf.ReadCustomersAsync(0, 100);
      10:  }

     

    The code for the event handler is pretty straightforward, we just set the datagrid’s DataContext to the e.Result of the event handler. This will contain an ObservableCollection<Customers> that was defined automatically for you via the proxy when you created your service reference.

       1:  void client_ReadCustomersCompleted(object sender, OA.WCFWizard.Demo.SL.NorthwindWCFService.ReadCustomersCompletedEventArgs e)
       2:  {
       3:      dataGridCustomers.DataContext = e.Result; 
       4:  }

     

    That is it! I will soon post a video here showing how to do this in more detail as well as an update method since our grid is editable (it is super easy.) Next week I will show some examples using ADO .NET Data Services (Astoria) where the wizard will also automatically create the IObjectScope OpenAccess and Astoria plumbing code for you.

    posted on Wednesday, August 19, 2009 6:04:20 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
    # Thursday, August 6, 2009

    The reason why Apple products are so slick and cool is two fold, the first is that they are a great consumer product/design company hands down. But the second is an equally important reason, a reason that will potentially prevent them from massive long term market share (like Windows, Oracle, etc.) The second reason why Apple products look and work so nicely is that they have a tight control over the software installed on their devices. For example if you are a software developer and want to build an application for the iPhone or the Mac, you need to follow the strict Apple design guidelines and then get approval from Apple before you can sell (or give away) your software.

    This is great, it gives the vendor (Apple) near complete control over what gets installed by the user base and the vendor (Apple) can control the user experience. This of course has some great benefits: less virus attacks, less crashes (windows is usually unstable due to people like me: software developers) and less hacks. You can also guarantee that there is no porn or politically sensitive content on your device.

    This also has a negative side effect. Pissed off developers. Tech blog TechCrunch reports that many software developers are getting angry with Apple due to the rejection of their apps, random removal of their apps, or rejection of an upgrade of their original app from the Apple AppStore. This will only anger more and more devs and over time, will limit the developer community on that platform. As we all know, with the apps, there will be no platform.

    I am not saying that this is happening (developers leaving in droves) now, but it can happen. A recent decision to pull an app may have started the revolution. Apple last week pulled the Google Voice application from its AppStoe. Google Voice is pretty cool and allows you to use VOIP to make and receive calls (among over cool stuff.) So free phone calls means less minutes AT&T (and other international carriers) can sell.

    This caused a bit of an uproar in the tech world. Some major influencers including prominent Apple supporters decided to quit using the iPhone over the decision to remove Google Voice. Google’s CEO Eric Schmidt has decided to step down from Apple’s board due to the conflict of interest. Lastly, the US government has gotten interested, last week, the FCC launched an investigation about the removal of Google Voice.

    Apple (and AT&T) should allow any application to be installed on the iPhone as well as any other phone for that matter. On the regular wired internet, I can buy a PC and then download and install anything I want, my ISP does not control what computer I can buy and what I can see and what I can’t see. Why is it different for phones? I can’t install everything I want, nor can I even buy whatever phone that I want, I have to buy the phone from the carrier in a “locked” mode.

    There is a reason: the United States is large country by land mass. The government has let the carriers have some control due to them promising to wire the whole country-this is why you can get signal in remote places where there is not a lot of demand. But now years later we are paying the price. It is time to open up the airwaves and allow us to buy any phone and install any application. The Apple AppStore is a walled garden that eventually will fail. While Apple risks losing a few design points and some system crashes and AT&T will lose some revenue, over the long run, if they allow anyone to develop software and anyone to install it, we all will be better off.

    posted on Thursday, August 6, 2009 5:14:53 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback