# Tuesday, January 18, 2011

S.A. Developer.net

January 2011 – Building RESTful Applications with the Open Data Protocol

Please join us for an interesting session presented by Stephen Forte

Overview:

Applications today are expected to expose their data and consume data-centric services via REST. In this session we discuss what REST is and have an overview of WCF Data Services and see how we can REST enable your data using the Open Data Protocol (OData). Then you will learn how to leverage existing skills in Visual Studio, LINQ and data access to customize the behavior, control-flow, security model and experience of your data service. We will then see how to enable data-binding to traditional ASP.NET controls as well as Silverlight. We’ll look at other consumers of oData including SQL Server PowerPivot for Excel, wrapping up the session by talking about consuming other OData based applications in .NET as well talk about a non-Microsoft client. This is a very demo intensive session..

Speaker Bio – Stephen Forte:

Stephen is the Chief Strategy Officer of Telerik, a leading vendor in .NET components. He sits on the board of several start-ups including Triton Works and is also a certified scrum master. Prior to this he was CTO and co-founder of Corzen, Inc, a New York based provider of online market research data for Wall Street Firms and before that CTO of Zagat Survey in New York City as well as co-founder of the New York based software consulting firm The Aurora Development Group. Stephen is the Microsoft Regional Director for the NY Metro region, an MVP, INETA speaker and co-moderator and founder of the NYC .NET Developer User Group. He speaks regularly at industry conferences around the world and has written several books on application and database development. He currently Stephen has an MBA from the City University of New York.

Date: 27th January, 2011
Time: 18:15 for 18:30
Venue: Microsoft Cape Town (Please note the address below)
Golf Park 3, Engen House, Raapenberg Road, Mowbray
Please RSVP (!) at http://sadevct201101.eventbrite.com/

posted on Tuesday, January 18, 2011 5:46:09 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Wednesday, December 08, 2010

If you are creating OData or WCF services in your application and have been using the Telerik Data Services Wizard, things just got a whole lot easier. As I have shown before, you can go from File|New to a new CRUD application in 30 seconds using the wizard. With the Q3 release last month, Telerik gives you more control over the wizard and its output. Some of the new features are: the ability to isolate your service in its own project, the ability to select which CRUD methods gets created for each entity, and Silverlight data validation. Let’s take a look.

When you run the wizard, on its first page you now have the option, as shown here, to separate the service in its own class library. You can check the checkbox and type in a project name and the Data Services Wizard create the implementation files for the service in this new class library for you.

image

In previous versions of the wizard, the wizard would create all of the CRUD operations for you automatically. We received feedback from customers that said they would like more control over this process, allow some entities to be read only for example. The Q3 version of the wizard now allows you to select which CRUD methods to generate for each entity.

image

Lastly, if you choose the automatic Silverlight application generation, the wizard will read the database validation rules and replicate them as client side validation rules, saving you a lot of configuration and coding!

image

Enjoy the new wizard’s improvements!

posted on Wednesday, December 08, 2010 8:35:15 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Thursday, August 05, 2010

Yesterday I did the “Building RESTFul applications with the Open Data Protocol” session at VSLive on Microsoft’s campus in Redmond, Wa. We had a lot of fun, we did the following:

  • Looked at some public OData feeds listed at Odata.org
  • We randomly picked a feed, the City of Vancouver street parking feed, and consumed it
    • We also discovered that they have weird primary keys
    • we also discovered the FireFox consumed the OData feed much faster then IE (this on Microsoft’s own network!)
  • Saw how to create a feed automatically from SQL Azure tables
  • Consumed a feed in Microsoft PowerPivot
  • Build a feed on the fly using the Entity Framework and WCF Data Services
  • Consumed that feed in ASP.NET and Silverlight
    • Also looked at Query Interceptors and Service Operations briefly
  • Talked about security, both at the service level and at the IIS/ASP level
  • Made fun of the previous speaker
  • Showed how you can create a feed using 3rd party tools

I wrapped up the talk with a discussion about when you would use OData compared to other technology, such as RIA Services. My rule of thumb was that if you are building an application that you control and your users will consume, you should consider technology such as RIA Services (if you are using Silverlight) or ASP.NET, MVC, etc. If you want to expose parts of your application as a data feed and let others consume it and build applications around it then consider OData.

You can download the slides and code here.

posted on Thursday, August 05, 2010 9:25:53 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [1] Trackback
# Thursday, June 24, 2010

Read the other posts in this series:

In the previous blog posts listed above, I showed how Telerik’s new LINQ implementation works with WCF RIA Services. I showed how to build your own Domain Service, build custom query methods, and make a metadata class. In this post I will show how to expose your Domain Service as an OData feed.

The Open Data Protocol (OData) is a Web protocol for querying and updating data in a RESTful fashion. You create OData feeds when you want to set up feeds for 3rd parties to consume, typically without your knowledge. For example Twitter has a RESTful feed of all its public tweets and many applications will consume that feed.

You may use WCF RIA Services to create your application, however, you may want to expose parts of your application as a feed for others to consume. This is real easy to do. Let’s see how.

I will continue using the same project from the first three parts of this blog series. In the server (ASP.net) project you have to do three things. First set a reference to System.ServiceModel.DomainServices.Hosting.OData.

Next we have to configure an OData endpoint. You do this by adding the following to your web.config under the system.serviceModel node:

<domainServices>
  <endpoints>
   <add 
name="OData" type="System.ServiceModel.DomainServices.Hosting.ODataEndpointFactory, 
System.ServiceModel.DomainServices.Hosting.OData, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </endpoints>
</domainServices>

Lastly, you have to tell RIA Services what methods of your DomainService you want to expose. The methods you expose have to be an IQueryable and parameterless (which means the query methods in Part II are ineligible) and decorated with the IsDefult=true attribute. I will expose our GetCustomers() method from Part I as shown here by adding the attribute to the method:

   1:  //enable OData
   2:  [Query(IsDefault = true)]
   3:  public IQueryable<Customer> GetCustomers()
   4:  {
   5:      return this.DataContext.Customers
   6:          .Where(c => c.Country == "Germany")
   7:          .OrderBy(c => c.CustomerID);
   8:  }

Now you can run your project and view the OData feed from a browser. The format of the URL is the namespace+typename for the DomainService with dots replaced by hyphens followed by “.svc/odata/”. (Note, I have found that this is case sensitive and requires the terminating /.)

So for example, our Namespace is SilverlightApplication6.Web and our Domain Service is DomainService1, so our url would be http://servername/SilverlightApplication6-Web-DomainService1.svc/odata/

My URL is the following and the results are shown below:

http://localhost:1055/SilverlightApplication6-Web-DomainService1.svc/odata/

clip_image002

Now let’s explore the OData feed. Being a RESTful service you will access the feed and each resource via HTTP. The resource in this case will be the names of your Entities. What is great is that the OData feed respects the business rules of your RIA Service (since it is using the same DomainService), so you don’t have to worry about data leakage, nor duplicate any work replicating your business rules. Let’s drill down into the CustomerSet:

http://localhost:1055/SilverlightApplication6-Web-DomainService1.svc/odata/CustomerSet

clip_image004

That is it. You can then consume the feed from an iPhone app, .NET application, Excel PowerPivot, or any other application that supports HTTP and XML (which is pretty much anything.)

Enjoy!

posted on Thursday, June 24, 2010 4:00:03 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [2] Trackback
# Monday, June 21, 2010

Read the other posts in this series:

In the previous blog posts listed above, I showed how Telerik’s new LINQ implementation works with WCF RIA Services. I showed how to build your own Domain Service as well as build custom query methods. In this post I will show how to build a metadata class. (Note: future versions of the OpenAccess LINQ Implementation will produce the metadata class for you automatically.)

The WCF RIA Services metadata class is a separate class from the DomainService that contains information about the entities. In this class you can write custom validation logic, set attributes of the properties of the entities or indicate whether the property is to be generated on the client or not.

To create this class, create a new class in Visual Studio and name it: YourDomainSeriveClassName.metadata.cs. For example, our DomainService is DomainService1, so the metadata class is: DomainService1.metadata.cs.

Erase everything in the class and then replace it with the following, using the proper namespace in your project:

 

   1:  namespace SilverlightApplication6.Web
   2:  {
   3:      using System.ComponentModel.DataAnnotations;
   4:   
   5:      // The MetadataTypeAttribute identifies CustomersMetadata as the class
   6:      // that carries additional metadata for the Customers class.
   7:      [MetadataTypeAttribute(typeof(Customers.CustomersMetadata))]
   8:      public partial class Customers
   9:      {
  10:          internal sealed class CustomersMetadata
  11:          {
  12:              // Metadata classes are not meant to be instantiated.
  13:              private CustomersMetadata()
  14:              {
  15:              }
  16:              public string Address { get; set; }
  17:              public string City { get; set; }
  18:              public string CompanyName { get; set; }
  19:              public string ContactName { get; set; }
  20:              public string ContactTitle { get; set; }
  21:              public string Country { get; set; }
  22:              public string CustomerID { get; set; }
  23:              public string Fax { get; set; }
  24:              public string Phone { get; set; }
  25:              public string PostalCode { get; set; }
  26:              public string Region { get; set; }
  27:          }
  28:      }
  29:  }

As you can see this class has each of the properties of your entity (lines 16-26), now you can set them as required, specify a length, or validate with a RegEx pattern. You can also specify that a property should not be sent down to the client. Of course you can specify much more sophisticated rules, you can even write your own methods.

Let’s do a quick example on the CompanyName property, we will set it to required, set an error message to be displayed if the field is not entered as well as set a length of 32. This is done with two attributes:

   1:  [Required(ErrorMessage = "CompanyName is Required!!")]
   2:  [StringLength(32)]
   3:  public string CompanyName { get; set; }

Now when you perform databinding, RIA Services will enforce these rules for you on the client. For example, if try to edit our data in the application built in Part II, RIA Services automatically adds validation for us and passes on the error message we specified in the attribute. (Note you have to add an UpdateCustomer method to your DomainService1 class to enable editing.)

clip_image002

Enjoy!

posted on Monday, June 21, 2010 6:55:05 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, June 18, 2010

In my last blog post, I showed how Telerik’s new LINQ implementation works with WCF RIA Services. In that post I built a Domain Model from the Northwind database as well as a RIA Services Domain Service. I then showed the drag and drop features of RIA Services and created a simple Silverlight application with no code. Today we are going to take that example one step further by creating some custom server side Query Methods.

A query method is just a facility to query a data source. In RIA Services, you define a query method explicitly so it can be used on the client. This is pretty straight forward with RIA Services. Let’s create a query method to query the Customer table by its primary key (CustomerID) in the database. To do this, open the project we used in the previous blog post and add this code to the DomainService class in the server project.

   1:      //This query method will return only 1 customer
   2:      [Query(IsComposable = false)]
   3:      public Customer GetCustomersByID(string customerID)
   4:      {
   5:          //must also include the Germany restriction
   6:          //to keep in sync with the GetCustomers business logic
   7:          return this.DataContext.Customers.SingleOrDefault
   8:              (c => c.CustomerID == customerID 
   9:                  && c.Country=="Germany");
  10:      }

 

This method will return one customer and you need to specify that by the attribute IsComposable=False (Line 2). Everything else is pretty basic, you have a method signature that accepts a parameter (Line 3) and a LINQ statement that filters the data by CustomerID as well as by country (lines 8-9). We are filtering by country as well because in our original business logic (in Part I) we had a GetCustomers() method that filtered all of the records by the country Germany. This new GetCustomersByID method knows nothing of the GetCustomers() method so we have to replicate that business logic here. (We have hard coded the value of Germany, in a production application, you would most likely obtain this value from a database or cookie after authentication.)

Let’s create a second query method, one that will filter the Customer data source by the ContactName field and return a collection, not a single item. We define an IQueryable collection of Customer as the return value in the method signature (Line 3) and accept a parameter. This parameter is used in our LINQ statement to filter the data source (Lines 9-10). In addition, just like the previous example, we must also filter by the country Germany; also replicate the OrderBy of our GetCustomers() method (Line 11).

   1:  //This query method will return a collection of customers
   2:  //filtered by the letters passed in on the contact name
   3:  public IQueryable<Customer> GetCustomersByLetter(string letter)
   4:  {
   5:      //must also include the Germany restriction
   6:      //to keep in sync with the GetCustomers business logic
   7:      //also since we are returning a collection, must
   8:      //respect the OrderBy as well from the business logic
   9:      return this.DataContext.Customers.Where
  10:          (c => c.ContactName.StartsWith(letter) == true
  11:              && c.Country == "Germany").OrderBy(c => c.CustomerID);
  12:  }

 

Now that we have defined two query methods, let’s wire them up to our XAML form in the Silverlight application.

In our Silverlight application, delete the grid that we had dragged onto the form in Part I. Replace it with two labels, two text boxes, two buttons and a grid (set the grid’s AutoGenerateColumns property to True.) Your XAML page should look something like this:

image

Now we have to write some code.

In the last blog post we were able to use the drag and drop features of RIA Services and not write any code. Today I will show you how to perform similar and more advanced functions with just a little bit of code. First we need two using statements in order to get working:

using SilverlightApplication6.Web;
using System.ServiceModel.DomainServices.Client;

Next we need to create a global variable for the RIA Services DomainService’s context.

   1:  //domain context for all RIA operations
   2:  private DomainService1 domainContext = new DomainService1();

 

Next we will load the grid with all of the data the first time the XAML form loads. We load the data by calling the GetCustomers() method we created in the previous blog post (we use the domainContext global variable in line 6.).

   1:  void MainPage_Loaded(object sender, RoutedEventArgs e)
   2:  {
   3:      //since we are going across the wire, must explicitly tell
   4:      //RIA Services that we are going to load data 
   5:      LoadOperation<Customer> loadOperation = 
   6:          domainContext.Load<Customer>(domainContext.GetCustomersQuery());
   7:      //the actual binding of the results, RIA takes care of the async
   8:      this.dataGrid1.ItemsSource = loadOperation.Entities;
   9:  }

 

This code does the same thing as the drag and drop did in the previous blog post, call GetCustomers() (Lines 5-6) and bind the results (line 8). Notice in the codegen on the client, RIA Services appends the word “Query” to all query methods.  In the previous blog post this was done automatically, but today we did it via code. If we run this it will give us the following view:

image

Now let’s wire up the buttons so we can perform the filters. First we will wire up the button that will search by CustomerID. That button click event will call the GetCustomerByID query method (lines 11-13) and bind the results (line 15.) We have to pass in the data the user entered in the text box, make sure in production to validate this data!

   1:  private void button1_Click(object sender, RoutedEventArgs e)
   2:  {
   3:      //disable the buttons during the async load
   4:      //to prevent the user from clicking twice while waiting
   5:      button1.IsEnabled = false;
   6:      button2.IsEnabled = false;
   7:   
   8:      //since we are going across the wire, must explicitly tell
   9:      //RIA Services that we are going to load data 
  10:      //Also here is where you pass the parameter in 
  11:      LoadOperation<Customer> loadOp = domainContext.Load
  12:          (domainContext.GetCustomersByIDQuery(textBox1.Text), 
  13:              CustomerLoadedCallback, null);
  14:      //the actual data binding, RIA takes care of the async
  15:      dataGrid1.ItemsSource = loadOp.Entities;
  16:  }

As part of the operation, RIA Services will handle the asynchronous processing for you. The problem is that users are not used to async operations, so they may try to click on the button more than once. We account for this by disabling the buttons (lines 5-6) until the operation is complete.  We have to catch the end of the async operation in a callback function and pass that in as a parameter to the operation (line 13). The callback function is here:

   1:  //callback function for when the load is complete
   2:  private void CustomerLoadedCallback(LoadOperation<Customer> loadOperation)
   3:  {
   4:      //re-enable our buttons
   5:      //if you want to display an "IsBusy" graphic
   6:      //this is where you would remove it
   7:      button1.IsEnabled = true;
   8:      button2.IsEnabled = true;
   9:  }

 

Let’s run this and test it out. If you filter by “ALFKI”, the results look like this:

image

Now let’s do the same for the the filter by ContactName. The code behind the button event is here:

   1:  private void button2_Click(object sender, RoutedEventArgs e)
   2:  {
   3:      //disable the buttons during the async load
   4:      //to prevent the user from clicking twice while waiting
   5:      button1.IsEnabled = false;
   6:      button2.IsEnabled = false;
   7:   
   8:      //since we are going across the wire, must explicitly tell
   9:      //RIA Services that we are going to load data 
  10:      //Also here is where you pass the parameter in 
  11:      LoadOperation<Customer> loadOp = domainContext.Load
  12:          (domainContext.GetCustomersByLetterQuery(textBox2.Text),
  13:              CustomerLoadedCallback, null);
  14:      //the actual data binding, RIA takes care of the async
  15:      dataGrid1.ItemsSource = loadOp.Entities;
  16:  }

Similar to the previous example, we are calling the query method, this time GetCustomersByLetter (lines 11-13) and passing in the value the user typed into the text box. When we run this and filter by all contacts that start with the letter H, it looks like this:

image

Hopefully with these two examples you can see the power of using Telerik’s new LINQ implementation and WCF RIA Services.

Enjoy!

posted on Friday, June 18, 2010 5:20:56 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, June 17, 2010

With the Q1 release of Telerik OpenAccess ORM, Telerik released a brand new LINQ Implementation and supporting Visual Entity Designer. With the upcoming Q2 release next month, we will introduce full WCF RIA Services support. If you want to get started now you can wire up the services yourself pretty easily. Let’s take a look at how to get your feet wet with RIA Services and Telerik’s LINQ implementation.

Before you get started, you will need a few things installed:

  • Visual Studio 2010
  • Silverlight 4
  • WCF RIA Services for Visual Studio 2010
  • Northwind sample database
  • Telerik OpenAccess ORM Q1 Service Pack 1 or higher

Getting Started: The Easy Stuff

Let’s create a new Silverlight application first. In the New Silverlight Application dialog, check the “Enable WCF RIA Services” checkbox. This will enable RIA Services.

image

The next step is to create a new Telerik Domain Model in the server (ASP.NET) project. I have a detailed walk through here on how to do that. We’ll create a new Domain Model by right clicking on the server project and selecting “Add” and choosing the Telerik Domain Model from the menu. Then we will map all of the tables from Northwind using the wizard. We’ll also keep the default model name of NorthwindEntityDiagrams.

image

We’re in good shape. So far if you have used the new LINQ Implementation nothing is new (or LINQ to SQL/EF for that matter.)  Now let’s add the RIA Services stuff.

Housekeeping-Adding References

Since our RIA Services support is still beta, you have to wire up a few things manually, including some references. You need to add:

  • Telerik.OpenAccess.Ria.Extensions.dll (found under “Browse: Program Files|Telerik|OpenAccess ORM|Bin)
  • System.ServiceModel.DomainServices.Server.dll
  • System.ServiceModel.DomainServices.Hosting.dll
  • System.ComponentModel.DataAnnotations.dll

image

Now we are ready to create the domain class.

Creating the Domain Class

Add a new Domain Service Class by right clicking and selecting Add|New Item and choose Domain Service Class.

image

Accept the defaults in the dialog and then we are ready to go. (Note at this time OpenAccess does not support creation of the class for metadata, but will soon, possibly even before Q2.)

image

Once you accept this dialog, a new empty class is generated.

   1:      [EnableClientAccess()]
   2:      public class DomainService1 : DomainService
   3:      {
   4:      }

 

We need to add a using statement so we can make sure our DomainService uses the OpenAccess model: using Telerik.OpenAccess;

Now change the inheritance of DomainService1 to this:

   1:  [EnableClientAccess()]
   2:  public class DomainService1 : OpenAccessDomainService<NorthwindEntityDiagrams>
   3:  {
   4:  }

Now we have one last step to create our DomainService, we have to add the CRUD methods. (In the future all of this will be done automatically for you!)

   1:  {
   2:      public IQueryable<Customer> GetCustomers() 
   3:      { 
   4:          return this.DataContext.Customers; 
   5:      }
   6:   
   7:      public void InsertCustomer(Customer c)
   8:      {
   9:          this.DataContext.Add(c);
  10:          this.DataContext.SaveChanges();
  11:      }
  12:      public void DeleteCustomer(Customer c)
  13:      {
  14:          this.DataContext.Delete(c);
  15:          this.DataContext.SaveChanges();
  16:      }

These are the methods of your DomainService. You can also add business logic here. Let’s do that with our GetCustomers() query.  I will write some business logic that filters all of the customers by the country of Germany. Of course you would have more complex business logic here, however, I just want to demonstrate the point. All clients that use this DomainService will inherit this business logic, even if you expose your service as an OData feed. Our implementation is here:

   1:  public IQueryable<Customer> GetCustomers() 
   2:  { 
   3:      return this.DataContext.Customers
   4:          .Where(c=> c.Country=="Germany")
   5:          .OrderBy(c=> c.CustomerID); 
   6:  }

 

Now you are done. Compile and let’s get cracking on a Silverlight client.

Creating the Silverlight Client

This is the easy part. We’ll use the RIA Services drag and drop features. Open MainPage.XAML in the Silverlight application and in the Data Sources window, drag and drop the Customer entity to the XAML form. (Tip: if the Data Sources window is blank or not showing up, you can manually force it to come up via the “Data” menu option on the main menu in Visual Studio.)

Once you drag and drop the entity to the form, a grid will automatically show up.

image

Now press F5 and see the application running.

image

That's it! We just created an OpenAccess based RIA Services application!

Of course there is a lot more to RIA Services than just binding a grid, however, this demonstration should show you that once you create your DomainService class, all of the RIA Services “stuff” just works for you. In future posts we will look at more RIA Services features as well as creating a query method.

Enjoy!

posted on Thursday, June 17, 2010 9:06:30 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [3] Trackback
# Wednesday, June 16, 2010

The true power of OData is that the programming model is the same for any feed. I spend a lot of time building and demoing my own feeds- usually building an OData service around Northwind or AdventureWorks. To realize the power of OData you also need to know that you can consume public feeds. Let’s take a look at consuming the Microsoft TechEd Sessions OData Service. The TechEd service can be found here: http://odata.msteched.com/sessions.svc/

Being a RESTful service, we can drill down a little and investigate our data. I will do some URL querying and look at a list of all the speakers as well as their sessions. For example I can drill down to see all speakers named “Forte”

http://odata.msteched.com/sessions.svc/Speakers?$filter=SpeakerLastName eq 'Forte'

Or all of my sessions:

http://odata.msteched.com/sessions.svc/Speakers(1621)/Sessions

This is the beauty of OData, we don’t know how it was created, we also don’t care. All we care is if we can consume it easily. Let’s do so with an ASP.net application and the OData client for ASP.NET.

To get started, create a new ASP.NET application. In the application, right click on the References folder of the project in the Solution Explorer and select “Add Service Reference”. Put in the public URL of the TechED 2010 OData Service. This creates a proxy so you can code against the service locally and not know the difference.

image

Next set a reference to System.Data.Services.Client. This will enable us to use the OData client library and LINQ on the ASP.net client. Then drag a textbox, button, and a gridview to the ASP page. We’ll fill the gridView with the Speaker data filtered on the last name field based on what was typed in to the textbox. We accomplish this with the following code on the button click.

   1:  //set a reference to ServiceReference1 and System.Data.Services.Client
   2:  ODataTENA10Entities dat = 
   3:      new ODataTENA10Entities(new Uri("http://odata.msteched.com/sessions.svc/"));
   4:              
   5:  //LINQ statement to filter by the textbox
   6:  var result = from s in dat.Speakers
   7:                  where s.SpeakerLastName.StartsWith(TextBox1.Text.ToString())
   8:                  orderby s.SpeakerLastName
   9:                  select s; 
  10:   
  11:  //bind the results
  12:  GridView1.DataSource = result;
  13:  GridView1.DataBind();

 

Line 2 and 3 sets the data context and the LINQ statement is on lines 6-9. Line 7 is where we do the filtering based on the textbox. Pretty easy stuff.

image

Enjoy!

posted on Wednesday, June 16, 2010 7:19:13 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Monday, June 14, 2010

Last week at TechEd North America I did DEV303, Building RESTful Applications with the OData Protocol. I really enjoy doing this session since I get to code on the fly and talk about building applications. At a high level we covered:

  • What is REST, comparison to Web Services (REST is resource based, Web Services is RPC/method based)
  • What is OData, who is using it
  • When to use OData vs RIA Services (OData is for exposing data as a service across boundaries, RIA is for a VB6 style RAD application development)
  • Using WCF Data Services to build an OData Service
  • Consuming the WCF Data Service in Silverlight asynchronously –yes everyone had to suffer and watch me code
  • A Bill Gates joke
  • WCF Data Services Service Operations, Data Interceptors (Query and Change), Data paging
  • Consuming OData Services in ASP.NET (select and add, we even got to see my custom error raise)

You can download the slides and code here.

posted on Monday, June 14, 2010 8:25:55 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, June 03, 2010

Last week Telerik released a service pack for OpenAccess Q1. The service pack fixes a few issues with Telerik’s new LINQ implementation working under Visual Studio 2010. In addition, the service pack shipped the Data Services Wizard; the Data Service Wizard is no longer a separate install. You can use the Data Service Wizard with traditional OpenAccess classes or the new LINQ implementation. Today I will show show you a new feature of the wizard: automatically creating a styled Silverlight application from your domain model. Future blog posts will show how to use RIA Services as well as SQL Azure.

To get started open up Visual Studio 2010 and create a new ASP.net application. Create a new domain model by right clicking on the project and say Add|New Item and choose Telerik OpenAccess Domain Model from the dialog.

image

This will bring up the OpenAccess ORM Data Wizard to create your domain model by mapping tables to entities. Let’s use Northwind and map all tables and use the default model name: NorthwindEntityDiagrams. While there are other advanced features of the wizard, like T4 templates to override the default codegen, let’s just accept the defaults and finish.

image

Once you click Finish the wizard will add a new domain model to your project.

image

Now that we have our domain model, it is time to run the Data Services Wizard to automatically create the a RESTful service using WCF Data Services. (The data service wizard also gives us the ability to create a WCF endpoint as well.) This can be done from the Telerik|Data Services Wizard menu option from the Visual Studio main menu (or right clicking on the EntityDiagrams1.rlinq file.) The first page of the wizard asks you where the domain model lives and what project to place the new service in. We’ll do it all in the same project.

image

The next page of the wizard asks you what entities you want to expose in your service as well as if you want to generate a Silverlight Application. If you check this you are given the option to use the standard Microsoft Silverlight controls or the Telerik controls (if you have them installed.) If you choose the Telerik controls, you will also be able to choose a theme for your Silverlight application. The drop down will show you a list of all of the installed themes. I’ll go ahead and choose the Windows7 theme.

image

After you click through the finish page of the wizard, the next step is to hit F5 and run your application. A basic, but styled, Silverlight application is created for you, getting you started with all of the CRUD methods. The Telerik version has all of the features your would expect, built in sorting and filtering, grouping, etc. I know that you will want to change the baseline application, but this is a great start, eliminating all of the asynchronous CRUD code that you have to write. Not bad for about 30 seconds of work!

image

Enjoy!

posted on Thursday, June 03, 2010 3:41:03 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, May 28, 2010

Telerik has released Service Pack 1 of OpenAccess ORM, available now for download. There are a lot of new features (and of course bug fixes) but the three most important are:

  • The new LINQ implementation works fully with Visual Studio 2010
  • The Data Services Wizard is now fully integrated with the product, no separate install
  • A beta of RIA Services support

I will be doing a blog post on each of these in the coming weeks (expect some delays with TechEd US in the way.) One more thing to mention is that the Data Services Wizard now generates a Silverlight client and will give you the ability to automatically style the application, a feature I previewed last week at the Sydney User Group.

Enjoy!

posted on Friday, May 28, 2010 3:02:32 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, May 11, 2010

Douglas Purdy (@douglasp) and Jonathan Carter (@lostintangent) are doing an oData Roadshow in 7 cities around the world.  Their first stop is New York City this Wednesday, May 12, 2010!

Details from the odata.org website…

Join us for the OData Roadshow and learn how to implement Web APIs using the Open Data Protocol. This event will include depth presentations and hands-on time for you to explore ideas on building an API for your web application.

An important part of the OData Roadshow, will be the afternoon hacking sessions, where you'll have a chance to work OData into your own projects on whatever platform you choose. Bring your laptop, ready to experiment with your ideas and pound out some code.

Want to tweet about the OData Roadshow? Use the hash tag #OData.

Schedule
    • New York, NY - May 12, 2010
    • Chicago, IL - May 14, 2010
    • Mountain View, CA - May 18, 2010
    • Shanghai, China - June 1, 2010
    • Tokyo, Japan - June 3, 2010
    • Reading, United Kingdom - June 15, 2010
    • Paris, France - June 17, 2010

*Notice the lack of  a Hong Kong event. Don’t worry I complained personally to Doug…

Speakers
· Douglas Purdy (@douglasp)

Douglas Purdy is CTO, Data and Modeling in Microsoft’s Business Platform Division.

· Jonathan Carter (@lostintangent)

Jonathan Carter is Technical Evangelist in Microsoft's Developer & Platform Evangelism group.

Agenda
Morning
  • OData introduction, along with the ecosystem of products that support it
  • Implementing and consuming OData services
  • Hosting your OData assets in Azure
  • Monetizing your OData services via "Dallas"
  • Real-world tips & tricks to consider when developing an OData service
Afternoon
  • Open discussion and hands-on coding time to experiment with ideas and uses for OData in their current/future projects.

REGISTER HERE

Description: 
http://www.myworldmaps.net/map.ashx/31241c92-b1f5-4fbb-a1c0-25b70c921fc4/ping

posted on Tuesday, May 11, 2010 3:31:02 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, May 04, 2010

About a month or so ago I showed on this blog how to connect to MySQL using Telerik's new LINQ implementation.  Today I will show you how to take it one step further and build an OData service automatically using the Telerik Data Services Wizard. Just for fun, we will also automatically add a full CRUD Silverlight application that consumes the OData service. We’ll do this all in 30 seconds!

To get started, you have to download MySQL 5.x and the MySQL Workbench and also, as my colleague Alexander Filipov at Telerik reminded me, make sure you install the MySQL .NET Connector, which is available here.  I like to use Northwind, ok it gives me the warm and fuzzies, so I ran a script to produce Northwind on my MySQL server. There are many ways you can get Northwind on your MySQL database, here is a helpful blog to get your started.

Let’s get started! First we will just build our model with Telerik’s new LINQ implementation. I will repeat the steps I showed off in this blog post. Start up the Domain Model wizard by right clicking on the project in Visual Studio (I have a Web project) and select Add|New Item and choose “Telerik OpenAccess Domain Model” from the new item list.

image

When the wizard comes up, choose MySQL as your back end and enter in the name of your saved MySQL connection.

image

If you don’t have a saved MySQL connection set up in Visual Studio, click on “New Connection” and enter in the proper connection information. *Note, this is where you need to have the MySQL .NET connector installed.

image

After you set your connection to the MySQL database server, you have to choose which tables to include in your model. Just for fun, I will choose all of them.

image

Give your model a name, like “NorthwindEntities” and click finish. Now you have a new Telerik Domain Model named NorthwindModel.rlinq.

image

Now we are going to use the Telerik Data Services Wizard to build our OData service endpoint via WCF Data Services (Astoria) and also automatically build a Silverlight client that will consume this service. The service has full CRUD capability and the Silverlight application is pretty basic, but wires up the application to the service and gives you the hooks to extend on.

We are going to use the “express” version of the Data Service Wizard and build the service and Silverlight client in less than 30 seconds! (Note: I showed how to do this using SQL Server here.) To do this, right click on the NorthwindModel.RLINQ file in the solution explorer and choose from the context menu: Data Services Wizard|Data Services for .NET 3.51 Sp1 Version 2 (Astoria)|Add to Project with new SL Client|WebApplication13.

(Note depending on which version of Visual Studio and what versions of WCF Data Services you have installed on your machine, the choices may vary.)

image

You will have to click OK to the standard “Add Silverlight Project” screen that Visual Studio gives you, but the wizard does all the work for you. When you run the application, the results are an OData service and a simple Silverlight CRUD application:

image

Enjoy!

posted on Tuesday, May 04, 2010 10:14:37 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, April 08, 2010

After a great beta cycle, Telerik is proud to announce today the commercial availability of the OpenAccess Data Service Wizard. You can download it and install it with Telerik OpenAccess Q1 2010 for both Visual Studio 2008 and 2010 RTM. If you are new to the Data Service Wizard, it is a great tool that will allow you to point a wizard at your OpenAccess generated data access classes and automatically build an WCF, Astoria (WCF Data Services), REST or ATOMPub collection endpoint, complete with the CRUD methods if applicable.

4-1-2010 1-39-01 PM

If you are familiar with the Data Service Wizard already, there will be two new surprises in the release version.

If you generated a domain model with the new OpenAccess Visual Entity Designer, you have only one file added to your project, mydomainmodel.rlinq for example. The first surprise of the new Data Service Wizard is that if you right click on the domain model in Visual Studio, you can use an “express” version of the Data Service Wizard and generate your service with just one click! This is pretty awesome, you can create your domain model from a database and create a service in well under 60 seconds.

4-1-2010 1-30-24 PM

Surprise number two is that if you are using the new Visual Entity Designer, we now give you the option, in both the full wizard and the right-click “express” version to create a new Silverlight application as a consumer of your new service. The Wizard will generate a Silverlight application with the full CRUD methods for you. You can go from File|New Project in Visual Studio to a full domain model generated from the database, a full WCF or Astoria service, and a fully functional CRUD Silverlight client in under 60 seconds!

4-1-2010 1-47-12 PM

The Silverlight application generation feature is a very “1.0” feature and we have big plans for it moving forward. We will look forward to your feedback as what to add to this application generation feature next. While I expect you to put your own skin on it and write some validation code, the application we build for you is a great starter and will save you from having to write all of the asynchronous CRUD code in your client. Visit our forums and let us know what you think.

Lastly, when OpenAccess releases its Q1 Service Pack later this month, the Data Service Wizard will be part of the main product install, so there is no need for a separate install moving forward. Our release cycle will now be in sync with OpenAccess and we have a lot planned for Q2, I will post an updated roadmap here soon.

Technorati Tags: ,
Bookmark and Share
posted on Thursday, April 08, 2010 9:58:27 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, March 19, 2010

Ever since the “new” SQL Azure went to beta, I have craved an automated way to set up an OData (Astoria) Service from my SQL Azure database. My perfect world would have been to have a checkbox next to each table in my database in the developer portal asking to “Restify” this table as a service. It always seemed kind of silly to have to build a web project, create an Entity Framework model of my SQL Azure database, build a WCF Data Services (OData) service on top of that, and then deploy it to a web host or Windows Azure. (This service seems overkill for Windows Azure.) In addition to all of that extra work, in theory it would not be the most efficient solution since I am introducing a new server to the mix.

At Mix this week and also on the OData team blog, there is an announcement as how to do this very easily. You can go to the SQL Azure labs page and then click on the “OData Service for SQL Azure” tab and enter in your SQL Azure credentials and assign your security and you will be able to access your OData service via this method: https://odata.sqlazurelabs.com/OData.svc/v0.1/<serverName>/<databaseName>

image

I went in and gave it a try. In about 15 seconds I had a working OData feed, no need to build a new web site, build an EDM, build an OData svc, and deploy, it just made it for me automatically. Saved me a lot of time and the hassle (and cost) of deploying a new web site somewhere. Also, since this is all Azure, I would argue that it is more efficient to run this from Microsoft’s server’s than mine: less hops to the SQL Azure database. (At least that is my theory.)

image

To really give this a test drive, I opened up Excel 2010 and used SQL Server PowerPivot. I choose to import from “Data Feeds” and entered in the address for my service. I then imported the Customers, Orders, and Order Details tables and built a simple Pivot Table.

image

This is a great new feature!

image

If you are doing any work with Data Services and SQL Azure today, you need to investigate this new feature. Enjoy!

Technorati Tags: ,

Bookmark and Share
posted on Friday, March 19, 2010 4:40:11 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Saturday, March 13, 2010

This week Telerik released a new LINQ implementation that is simple to use and produces domain models very fast. Built on top of the enterprise grade OpenAccess ORM, you can connect to any database that OpenAccess can connect to such as: SQL Server, MySQL, Oracle, SQL Azure, VistaDB, etc. While this is a separate LINQ implementation from traditional OpenAccess Entites, you can use the visual designer without ever interacting with OpenAccess, however, you can always hook into the advanced ORM features like caching, fetch plan optimization, etc, if needed.

Just to show off how easy our LINQ implementation is to use, I will walk you through building an OData feed using “Data Services Update for .NET Framework 3.5 SP1”. (Memo to Microsoft: P-L-E-A-S-E hire someone from Apple to name your products.) How easy is it? If you have a fast machine, are skilled with the mouse, and type fast, you can do this in about 60 seconds via three easy steps. (I promise in about 2-3 weeks that you can do this in less then 30 seconds. Stay tuned for that.)

 Step 1 (15-20 seconds): Building your Domain Model

In your web project in Visual Studio, right click on the project and select Add|New Item and select “Telerik OpenAccess Domain Model” as your item template. Give the file a meaningful name as well.

image

Select your database type (SQL Server, SQL Azure, Oracle, MySQL, VistaDB, etc) and build the connection string. If you already have a Visual Studio connection string already saved, this step is trivial.  Then select your tables, enter a name for your model and click Finish. In this case I connected to Northwind and selected only Customers, Orders, and Order Details.  I named my model NorthwindEntities and will use that in my DataService.

image

Step 2 (20-25 seconds): Adding and Configuring your Data Service

In your web project in Visual Studio, right click on the project and select Add|New Item and select “ADO .NET Data Service” as your item template and name your service.

image

In the code behind for your Data Service you have to make three small changes. Add the name of your Telerik Domain Model (entered in Step 1) as the DataService name (shown on line 6 below as NorthwindEntities) and uncomment line 11 and add a “*” to show all entities. Optionally if you want to take advantage of the DataService 3.5 updates, add line 13 (and change IDataServiceConfiguration to DataServiceConfiguration in line 9.)

   1:  using System.Data.Services;
   2:  using System.Data.Services.Common;
   3:   
   4:  namespace Telerik.RLINQ.Astoria.Web
   5:  {
   6:      public class NorthwindService : DataService<NorthwindEntities>
   7:      {
   8:          //change the IDataServiceConfiguration to DataServiceConfiguration
   9:          public static void InitializeService(DataServiceConfiguration config)
  10:          {
  11:              config.SetEntitySetAccessRule("*", EntitySetRights.All);
  12:              //take advantage of the "Astoria 3.5 Update" features
  13:              config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  14:          }
  15:      }
  16:  }

 

Step 3 (~30 seconds): Adding the DataServiceKeys

You now have to tell your data service what are the primary keys of each entity. To do this you have to create a new code file and create a few partial classes. If you type fast, use copy and paste from your first entity,  and use a refactoring productivity tool, you can add these 6-8 lines of code or so in about 30 seconds. This is the most tedious step, but don’t worry, I’ve bribed some of the developers and our next update will eliminate this step completely.

Just create a partial class for each entity you have mapped and add the attribute [DataServiceKey] on top of it along with the key’s field name. If you have any complex properties, you will need to make them a primitive type, as I do in line 15. Create this as a separate file, don’t manipulate the generated data access classes in case you want to regenerate them again later (even thought that would be much faster.)

   1:  using System.Data.Services.Common;
   2:   
   3:  namespace Telerik.RLINQ.Astoria.Web
   4:  {
   5:      [DataServiceKey("CustomerID")]
   6:      public partial class Customer
   7:      {
   8:      }
   9:   
  10:      [DataServiceKey("OrderID")]
  11:      public partial class Order
  12:      {
  13:      }
  14:   
  15:      [DataServiceKey(new string[] { "OrderID", "ProductID" })]
  16:      public partial class OrderDetail
  17:      {
  18:      }
  19:   
  20:  }

 

Done! Time to run the service.

Now, let’s run the service! Select the svc file and right click and say “View in Browser.” You will see your OData service and can interact with it in the browser.

image

Now that you have an OData service set up, you can consume it in one of the many ways that OData is consumed: using LINQ, the Silverlight OData client, Excel PowerPivot, or PhP, etc.

Happy Data Servicing!

Technorati Tags: ,,

Bookmark and Share
posted on Saturday, March 13, 2010 4:29:07 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Thursday, March 11, 2010

Love LINQ to SQL but are concerned that it is a second class citizen? Need to connect to more databases other than SQL Server? Think that the Entity Framework is too complex? Want a domain model designer for data access that is easy, yet powerful? Then the Telerik Visual Entity Designer is for you.

Built on top of Telerik OpenAccess ORM, a very mature and robust product, Telerik’s Visual Entity Designer is a new way to build your domain model that is very powerful and also real easy to use. How easy? I’ll show you here.

First Look: Using the Telerik Visual Entity Designer

To get started, you need to install the Telerik OpenAccess ORM Q1 release for Visual Studio 2008 or 2010. You don’t need to use any of the Telerik OpenAccess wizards, designers, or using statements. Just right click on your project and select Add|New Item from the context menu. Choose “Telerik OpenAccess Domain Model” from the Visual Studio project templates.

image

(Note to existing OpenAccess users, don’t run the “Enable ORM” wizard or any other OpenAccess menu unless you are building OpenAccess Entities.)

You will then have to specify the database backend (SQL Server, SQL Azure, Oracle, MySQL, etc) and connection.

image

After you establish your connection, select the database objects you want to add to your domain model. You can also name your model, by default it will be NameofyourdatabaseEntityDiagrams.

image

You can click finish here if you are comfortable, or tweak some advanced settings. Many users of domain models like to add prefixes and suffixes to classes, fields, and properties as well as handle pluralization. I personally accept the defaults, however, I hate how DBAs force underscores on me, so I click on the option to remove them.

image

You can also tweak your namespace, mapping options, and define your own code generation template to gain further control over the outputted code. This is a very powerful feature, but for now, I will just accept the defaults.

 image

When we click finish, you can see your domain model as a file with the .rlinq extension in the Solution Explorer.

image

You can also bring up the visual designer to view or further tweak your model by double clicking on the model in the Solution Explorer. 

image

Time to use the model!

Writing a LINQ Query

Programming against the domain model is very simple using LINQ. Just set a reference to the model (line 12 of the code below) and write a standard LINQ statement (lines 14-16).  (OpenAccess users: notice the you don’t need any using statements for OpenAccess or an IObjectScope, just raw LINQ against your model.)

   1:  using System;
   2:  using System.Linq;
   3:  //no need for an OpenAccess using statement
   4:   
   5:  namespace ConsoleApplication3
   6:  {
   7:      class Program
   8:      {
   9:          static void Main(string[] args)
  10:          {
  11:              //a reference to the data context
  12:              NorthwindEntityDiagrams dat = new NorthwindEntityDiagrams();
  13:              //LINQ Statement
  14:              var result = from c in dat.Customers
  15:                           where c.Country == "Germany"
  16:                           select c;
  17:   
  18:              //Print out the company name
  19:              foreach (var cust in result)
  20:              {
  21:                  Console.WriteLine("Company Name: " + cust.CompanyName);
  22:              }
  23:              //keep the console window open
  24:              Console.Read();
  25:          }
  26:      }
  27:  }

Lines 19-24 loop through the result of our LINQ query and displays the results.

image

That’s it! All of the super powerful features of OpenAccess are available to you to further enhance your experience, however, in most cases this is all you need.

In future posts I will show how to use the Visual Designer with some other scenarios. Stay tuned.

Enjoy!

Technorati Tags: ,,

Bookmark and Share
posted on Thursday, March 11, 2010 9:26:16 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Monday, February 22, 2010

Telerik has released the latest beta of the OpenAccess Data Service Wizard. We now support Visual Studio 2010 RC! You can also choose to use WCF 4.0 as one of the services you can build. Based on your feedback we also added a new feature: the ability to automatically generate dependent entities.

Download it today and give us your feedback. Next stop is the full release as part of our 2010 Q1 release of OpenAccess. See the OpenAccess roadmap here.

 image

Technorati Tags:

Bookmark and Share
posted on Monday, February 22, 2010 10:13:20 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Tuesday, February 09, 2010

.NET Ninja in training, Peter Bahaa, shows us how to build an AtomPub Endpoint using Telerik OpenAccess entities and the Data Services Wizard beta 1.

Telerik Data Services Wizard Beta1-ATOMPub from Stephen Forte on Vimeo.

Technorati Tags: ,,

Bookmark and Share
posted on Tuesday, February 09, 2010 4:11:38 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Friday, February 05, 2010

.NET Ninja in training, Peter Bahaa, shows us how to build a WCF Endpoint using Telerik OpenAccess entities and the Data Services Wizard beta 1.

Telerik Data Services Wizard Beta1-REST Collection from Stephen Forte on Vimeo.

Technorati Tags: ,,

posted on Friday, February 05, 2010 7:12:26 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Wednesday, February 03, 2010

.NET Ninja in training, Peter Bahaa, shows us how to build a WCF Endpoint using Telerik OpenAccess entities and the Data Services Wizard beta 1.

Telerik Data Services Wizard Beta1-WCF from Stephen Forte on Vimeo.

Technorati Tags: ,
posted on Wednesday, February 03, 2010 1:55:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Tuesday, February 02, 2010

.NET Ninja in training, Peter Bahaa, once again returns to show us how to build a WCF .NET Data Service (aka Astoria) using Telerik OpenAccess entities and the Data Services Wizard beta 1.

Telerik Data Service Wizard Beta1-Astoria from Stephen Forte on Vimeo.

 

Technorati Tags: ,
posted on Tuesday, February 02, 2010 1:55:39 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Saturday, January 23, 2010

Last week Telerik released the Data Service Wizard Beta 1. It will automatically create for you the end points for an Astoria, WCF, or RESTful service. New in the beta of the Data Service Wizard is the ability of the wizard to automatically generate the DataServiceKey attribute required to make relationships in Astoria work.

When you use "Astoria" (ADO.NET||WCF) Data Services, by default Astoria tries to map the primary keys in your entities using a convention. This is important for your service to work. The mapping works out of the box for the Entity Framework, however, if you are using LINQ to SQL or Telerik Open Access, it does not since some of your tables may have a primary key that will not map to the CLR primitive types that follow the Astoria convention for key mapping. (Order Details in Northwind bombs for example since both of its composite key are entities and not primitive CLR types.)

There is a very simple fix for this. You have to make your entity a partial class and then decorate the entity using the DataServiceKey attribute, in the constructor. Recently we added support for this in the Data Service Wizard: by default we do this for you by adding a “DalDataServiceKeys.cs“ (or VB) file to your data access layer project automatically.

image

The code is show below for our DalDataServiceKeys.cs file shown in the Telerik.OA.DAL project above. You will notice on Line 36 we will even convert the complex type to a primitive CLR type so Astoria can handle it.

   1:  namespace Telerik.OA.DAL
   2:  {
   3:      using System.Data.Services.Common;
   4:   
   5:      /// <summary>
   6:      /// Category Class Data Service Key Fix
   7:      /// </summary>
   8:      [DataServiceKey("CategoryID")]
   9:      public partial class Category
  10:      {
  11:      }
  12:      /// <summary>
  13:      /// Customer Class Data Service Key Fix
  14:      /// </summary>
  15:      [DataServiceKey("CustomerID")]
  16:      public partial class Customer
  17:      {
  18:      }
  19:      /// <summary>
  20:      /// Employee Class Data Service Key Fix
  21:      /// </summary>
  22:      [DataServiceKey("EmployeeID")]
  23:      public partial class Employee
  24:      {
  25:      }
  26:      /// <summary>
  27:      /// Order Class Data Service Key Fix
  28:      /// </summary>
  29:      [DataServiceKey("OrderID")]
  30:      public partial class Order
  31:      {
  32:      }
  33:      /// <summary>
  34:      /// OrderDetail Class Data Service Key Fix
  35:      /// </summary>
  36:      [DataServiceKey(new string[]{"OrderID","ProductID"})]
  37:      public partial class OrderDetail
  38:      {
  39:      }
  40:      /// <summary>
  41:      /// Product Class Data Service Key Fix
  42:      /// </summary>
  43:      [DataServiceKey("ProductID")]
  44:      public partial class Product
  45:      {
  46:      }
  47:      /// <summary>
  48:      /// Region Class Data Service Key Fix
  49:      /// </summary>
  50:      [DataServiceKey("RegionID")]
  51:      public partial class Region
  52:      {
  53:      }
  54:      /// <summary>
  55:      /// Shipper Class Data Service Key Fix
  56:      /// </summary>
  57:      [DataServiceKey("ShipperID")]
  58:      public partial class Shipper
  59:      {
  60:      }
  61:      /// <summary>
  62:      /// Supplier Class Data Service Key Fix
  63:      /// </summary>
  64:      [DataServiceKey("SupplierID")]
  65:      public partial class Supplier
  66:      {
  67:      }
  68:      /// <summary>
  69:      /// Territory Class Data Service Key Fix
  70:      /// </summary>
  71:      [DataServiceKey("TerritoryID")]
  72:      public partial class Territory
  73:      {
  74:      }
  75:  }

This will enable you to use Astoria with OpenAccess for all of the tables in your database. I converted my Tech*Ed “Data Access Hacks and Shortcuts” session demo to use OpenAccess and Astoria from the Entity Framework in less than 5 minutes. (I will show it and give away the code on my blog in a week or two.)

image

Enjoy!

Technorati Tags: ,
posted on Saturday, January 23, 2010 6:24:52 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Friday, December 18, 2009

The Astoria (aka ADO.NET Data Services) team released an updated .NET 3.5 SP1 version of Astoria the other day. There are tons of great new features like projections and my favorite, an inline row count. As I said on my blog yesterday, you have to alert Astoria that you want to use the new V2 features, by default Astoria 2.0 runs in Astoria 1.0 mode. (For backwards compatibility.)

Telerik has enhanced the Data Services Wizard to support Astoria 2.0 (officially the “Data Services update for .NET 3.5 SP1” but I digress….)

Now if you have the updated Data Services DLLs on your machine, you will have the option to create a service using V1 or V2. If you choose V2, we will automatically set the MaxProtocolVersion property to V2 for you.

12-17-2009 5-38-01 PM

Happy Data Servicing!

Technorati Tags: ,
posted on Friday, December 18, 2009 5:41:52 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Thursday, December 17, 2009

The Astoria (aka ADO.NET Data Services) team released an updated .NET 3.5 SP1 version of Astoria last night. This version of Astoria is an inplace update and will overwrite your current version of Astoria (System.Data.Services.*.dll). You can download it from the following locations.

The new version of Astoria has some very useful and powerful features. They include projections, data binding, row count, feed customization, server based paging and better BLOB support. There is one small issue, in order to support these new features you have to tell the framework you are using the new version of Astoria. For backward compatibility reasons, by default Astoria will work in “1.0” mode and none of the new features will work out of the box. To take advantage of the 2.0 features, you have to make two minor changes to the InitializeService method:

   1:  //change the IDataServiceConfiguration to DataServiceConfiguration
   2:  public static void InitializeService(DataServiceConfiguration config)
   3:  {
   4:      config.SetEntitySetAccessRule("*", EntitySetRights.All);
   5:      //take advantage of the "2.0" features
   6:      config.DataServiceBehavior.MaxProtocolVersion =
   7:          System.Data.Services.Common.DataServiceProtocolVersion.V2;
   8:  }

The first thing that you need to change is on line 2, change the interface IDataServiceConfiguration to be just DataServiceConfiguration (I am sure that there is a better way to do this, I have not figured it out yet.). Next, set the MaxProtocolVersion property of DataServiceBehavior to V2. After that you can take advantage of all the new features!

I want to take advantage of my favorite new feature, the inline row count. (I have been asking over and over for this feature, so: Thanks Astoria team!!!) The inline row count will return the number rows in the data feed regardless of paging ($skip, $top etc) as an XML element: <m:count>. This new property makes our RAD Grid and other paging aware controls much easier to perform paging. To make this work, you just add the inlinecount to the querystring:

servicename/entityname?$inlinecount=allpages
 

Let’s implement this with the example I did the other day using Telerik OpenAccess and the Data Service Wizard. If you remembered I built a simple Astoria 1.0 service exposing the Customers entity. We built this using “Astoria 1.0”, however, I upgraded my machine with the release of Astoria 2.0. When I use inlinecount, I get a 404 error. As with a brand new service, we have to tell the framework what version of Astoria we want to use before we can take advantage of inlinecount. I made the same changes as I did above (DataServiceConfiguration and MaxProtocolVersion ) and reran my application. Now when I type this URL: http://localhost:1191/WebDataService.svc/Customers?$inlinecount=allpages&$top=2

I get only the top two records but the total count of records.

image

Awesome.

Enjoy Astoria 2.0!

PS:

I thought that this was called “WCF Data Services”? According to the Astoria team blog:

Since this release is an update to the .NET Framework 3.5 SP1 we kept the name consistent with what was used in the 3.5 SP1 timeframe so that printed documentation, etc is consistent.  Going forward in .NET 4 and onwards you’ll see us use WCF Data Services.

Technorati Tags:
posted on Thursday, December 17, 2009 3:51:54 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Wednesday, December 16, 2009

Far and away the number one Business Intelligence client in the world is Microsoft Excel. While there are tons of data visualization tools out there, Excel is hands down the leader since it is both familiar to users and very powerful. Developers have built tons of business intelligence (BI) apps in Excel using connections to data warehouses (or cubes) and letting the users go crazy with pivot tables and charts.

Things are about to get even better with project Gemini or now  Microsoft SQL Server PowerPivot (we rebel and just call it PowerPivot).  PowerPivot is an add-in for Excel 2010 or Sharepoint. PowerPivot for Excel is a data analyses tool that allows you to connect to a database, download data and store it in a local data engine (VertiPaq) so you can slice and dice it to your heart’s content using familiar Excel tools such as pivot tables and charts. (You can then send it up to SharePoint if you like, but let’s just focus on Excel for now.) PowerPivot works in-memory using your local PC’s processing power and is optimized to handle millions of rows in memory on cheap commodity PCs. The VertiPaq OLAP Engine that is part of PowerPivot  compresses and manages millions of rows of data in memory for you.

There are many awesome features of PowerPivot, but something I learned reading the team’s blog on data importing was that PowerPivot supports SQL Azure natively. This scenario is great since you can download your SQL Azure data, store it locally and slice and dice offline.

Let’s imagine you have this set up in SQL Azure:

  • SQL Azure cloud based online-transaction processing database (OLTP)
  • SQL Azure cloud based online analytical processing data warehouse database  (OLAP)

You don’t have a local server to set up some Analysis services cubes and SQL Azure doesn’t provide that capability. You decide on a hybrid solution and provide a “self-service” distributed OLAP system. Your users, using Excel and PowerPivot, download from the cloud some of the OLAP data from SQL Azure and use their own hardware to do the number crunching. You maybe thinking, “I heard that this VertiPaq engine is great, but how will a laptop handle all of this data/processing?”  Remember if you architect your OLAP database properly, there will be a lot of “pre-crunching” already done, avoiding many segmentations and rollups. I tested about 100 million rows (of old Corzen data) on the “PDC laptop” with 2 GB of RAM and had near instantaneous results.While the cloud is real sexy right now, you can’t perform these type of operations without major latency.

Let’s walk through the basics, just getting some data from SQL Azure into Excel and PowerPivot. First you need Excel 2010 and PowerPivot. You can grab Excel via Microsoft’s web site for free (for now!) since it is in beta and PowerPivot from here. Make sure you download the proper version: x32 or x64.

Once installed, you will see a “PowerPivot” tab in Excel. You can click on on the PowerPivot window icon to get started.

image

The PowerPivot tool is mostly for managing data and connections. You can import data from a variety of data sources, including databases, files,  and services (including RESTful ones.) To connect and download from SQL Azure you have to choose From Database|From Other Sources from the Home tab on the ribbon.

image

This will bring you to a list of available data sources, choose Microsoft SQL Azure.

image

Of course, you will need to log into SQL Azure.

image

Once logged in, you can download data either from a TSQL query or just the tables and views raw. I choose to download just the tables from my Northwind database.

image

There are come cool features like the ability to select one table and then automatically select all related tables. You can also specify some filters to your imports (good if you are segmenting the data by user.) Once you are finished, PowerPivot will now import all of your data for you.

image

Now that your data is in PowerPivot you can play with it very easily. Remember that the data is located on the client in-memory as part of your workbook. (It is compressed.) PowerPivot gives you a tab for each data table you imported and you can go in and in typical Excel fashion, sort and filter, like I did for Barcelona (oh the fond memories of 5 TechEds in Barcelona…..) All of this sorting and filtering is happening in-memory on your machine, you can unplug your network cable if you like, however, you can also refresh your data as you need.  PowerPivot gives the developer several ways to refresh data. Some techniques and guidelines are here.

image

Next you can create some PivotTables, charts, or combination. Just choose PivotTable from the Home menu and then choose a PivotTable type. I will just make a dirt simple Pivot table to give you an idea of some of the interactivity you can build pretty rapidly. (I am also using the OLTP version of Northwind for this walk through, so I did not create any cool queries to work with yet. I’ll do another blog post with some more sophisticated demos after the holidays.)

image

Here is a very simple, yet super powerful PivotTable that I built in 30 seconds using the PowerPivot tools. Of course I just used the raw Order table and my lookups (ShipVia and Employee) are showing their integer value, but work with me. I have a pivot table where I can view the total amount each customer spent on freight in all of our orders,by country/city broken out by the employee who took the order. I can also dynamically filter the data set by the Country and also further filter it by the ShipVia data set.

This creates a very interactive data analysis “report” for your users. (Or they can create it themselves if they are Excel savvy.) In a few seconds the users can see multiple versions of the data, changing the filters (and sorts) on the fly. All shippers in all cities for all employees. No problem. Shipper ID 2 in USA only. Sure. You get the drift. (What is cool is that the users can share this via PowerPivot for SharePoint if they like!)

image

Here is what I did:

I Dragged the ShipCity and CustomerID to the “Row Labels” box to use ShipCity and CustomerID as the main data elements in our rows. I dragged Freight into the Values box to sum on freight for each CustomerID. (Customers have many orders with different freight costs, so freight is a good item to sum up.) I choose Country as a dynamic filter and will break out the Freight totals by EmployeeID (in the Column Labels box). Lastly, I added a Vertical Slicer where I see a slice of all shippers (ShipVia) and can do additional filters on all current data selections.

Pretty easy. Now combine this with some pre-built views on the server and your users can really go to town. All without a persistent connection back up to SQL Azure.

Enjoy!

Technorati Tags: ,
posted on Wednesday, December 16, 2009 5:14:02 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Tuesday, December 15, 2009

Last week Telerik released the December CTP of the Data Services Wizard. I posted on my blog a video that shows how to get started, however, for those of you that like walkthroughs better, here is one using a WCF Data Services (Astoria) service.

Getting Started: Mapping Data With OpenAccess

To get started, first download and install the Data Services Wizard. After that, fire up Visual Studio and create a new Class library application named Telerik.DSW.Demo.Astoria.DAL. Run the OpenAccess “Enable Project to use ORM” wizard and then run the Reverse Mapping Wizard and map to your database. For this demo I mapped the Northwind database.

Map as many tables as you like, you can also manually remove the complex properties (Customer Collection from the Order entity for example) via the mapping wizard if you want to use that entity in your service. (Don’t worry we will have a solution for this when we have our January beta!)

Note: your wizard may not have created the ObjectScopeProvider in your DAL project. If you don’t have one in your DAL project via the main menu choose Telerik|Open Access|Configuration|Connection Strings. Then select the ObjectScopeProvider check box showed in the dialog below and click on ok.

image

Next Up: Using the Wizard

The WCF Data Service that the wizard will create has to reside in another (Web) project. So let’s create a Web project named Telerik.DSW.Demo.Astoria.Web.

image

Now it is time to start the wizard. Just select from the main menu Telerik|Data Services Wizard.

image

This will bring up the first page of the wizard, Select DAL Project. Here you select the name of the project that has your OpenAccess entities. Select the DAL project and click Next.

image

The Select Data Service screen is where you have to enter in some important information.

First put in the namespace, this is the namespace of your web project. (Future versions of the wizard will default to this namespace), and the name of your service, I choose Northwind as my creative service name. Also select which entities to generate as part of your service. I choose Customer, Order, and OrderDetail. Lastly, select which type of Service to create, in this case a WCF Data Service (our wizard did not catch up with the name, so you have to select ADO.NET Data Service (Astoria).)

image 

After you click next, you can preview the generated code on the View Output screen.

image

Click next and then you will be asked to choose which project to add the service to on the Finish screen. Select the web project, or Telerik.DSW.Demo.Astoria.Web and click next.

image

Now the wizard does a lot of work for you.

First it sets a reference to all of the WCF Data Services libraries (System.Data.Services and System.Data.Services.Client.) Next it sets a reference to the DAL project for you (in our case Telerik.DSW.Demo.Astoria.DAL) and also sets a reference to the Telerik OpenAccess DLLs for you (Telerik.OpenAccess and Telerik.OpenAccess.Query.) Lastly, the wizard created the Northwind.cs OpenAccess reference file as well as the actual data service (svc and cs) files.

image

The last step is to run the service. Just right click on the SVC file and choose View in Browser from the context menu. You will see your RESTful service come up in the browser. From here you can set up a client to consume the service in ASP.net, Silverlight, or any other Microsoft and non-Microsoft technology.

image

Enjoy!

Technorati Tags:
posted on Tuesday, December 15, 2009 5:06:18 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Thursday, December 10, 2009

This week we released our third “alpha” CTP build of our Telerik OpenAccess Data Services Wizard on Telerik Labs. We have received tons of feedback on the tool and look forward to more feedback. The wizard’s development team and the entire OpenAccess team have come up with a roadmap and would like some feedback from the community on it. In the spirit of a transparent design, I am going to publish the entire roadmap here for community review. Of course all of this can change blah blah blah. (The lawyers made me say that.)

Beta 1: January 2010

  • Using T4 Code generation instead of text templates
  • VB.NET code generation (we had a ton of requests for this one!) 
  • Add WCF Data Services 1.5 full integration using the new Data Service Provider (of course we need to make changes to OpenAccess core to implement the DSP, however, the DSP is currently not fully documented by Microsoft, so we don’t know how much work this is just yet.)
  • Generate only the primitive types and prevent generation of complex entities for all services. (WCF barfs on complex types and entities.)

Beta 2: February 2010

  • Full support for WCF RIA Services
  • Full support for Azure Services
  • If you use the wizard to build a service, give you the option to automatically create a Silverlight client along with some code generation to consume the service to get you started
  • ASP.NET Dynamic Data support

Release: Telerik Q1 2010 Release

  • Full integration with OpenAccess’ installer. No longer making the wizard a separate install, it will just install as part of OpenAccess
  • Use of OpenAccess internal APIs
  • Visual Studio 2010 support
  • WCF 4.0 Support. We currently require the WCF 3.5 REST Starter Kit for two of our output modes: REST Collection and AtomPub. .NET 4.0 mode will eliminate this dependency and give you the option to produce WCF 4.0 REST services, etc.

After the Q1 release the roadmap is not super clear. I will assume that core development will slow down a little and that we will then focus mostly on adding support for new service types. I am sure that by next spring, there will already be some new service types to support like the release build of WCF RIA Services, maybe a new CTP of Astoria, etc.

Drop me a line and let me know what you think! Also, the tech support team is adding a separate Data Service Wizard forum in the Telerik support forums, so even though the wizard is technically a “lab” project and not supported, drop by and ping the team with your questions there. We’ll answer all your support questions there as well.

Enjoy and thanks for any feedback you send.

Technorati Tags: ,
posted on Thursday, December 10, 2009 8:10:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] Trackback
# Wednesday, December 09, 2009

Telerik released the December CTP of the Data Services Wizard earlier this week. Here is a video by .NET Ninja in training Peter Bahaa on using the wizard:

Telerik OpenAccess Data Services Wizard December CTP from Stephen Forte on Vimeo.

Technorati Tags: ,
posted on Wednesday, December 09, 2009 10:33:31 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Monday, December 07, 2009

We are proud to announce our December CTP of the Telerik OpenAccess Data Services Wizard (formerly known as the WCF Services Wizard). The Data Services Wizard (DSW) allows you to easily create a CRUD data service layer for your application. The DSW does this by using a data access layer already built by OpenAccess and automatically generating the C# code for your endpoints. The types of endpoints you can create are:

  • WCF Data Services (FKA Astoria and also FKA ADO. NET Data Services)
  • Raw WCF endpoints
  • WCF REST Collection endpoints
  • WCF ATOMPub endpoints

This version of the Data Service Wizard is very robust; we have made lots of changes based on your feedback. Our #1 piece of feedback from customers has been to integrate the DSW with OpenAccess and Visual Studio. I am proud to announce that in this version the DSW is fully integrated with Visual Studio!

We have also started to integrate the DSW into the OpenAccess product itself. No longer is the DSW a standalone product; the wizard is now  located under the “Telerik” menu in Visual Studio and looks like the other OpenAccess wizards. Integration will get tighter in the near future and soon just be part of OpenAccess proper, not a separate download.

The basics of the wizard are the same. The DSW will ask you which project your OpenAccess entities are located in and then which entities you will expose in your endpoint.

ScreenShot1

After you choose the entities you want to expose and what type of service you want to build (WCF, Astoria, etc), you can preview the code that is generated.

ScreenShot2

A major improvement with the December CTP is that you can now automatically insert these service endpoint files into a project, eliminating the manual step of copying them on over. This will make building the services so much easier!

image011

Go grab the wizard here. It is still considered a Telerik Labs project, but we will move it to a fully supported beta in January with our next build. On the dock for the next build (early January) are:

  1. Using T4 Code generation instead of text templates
  2. VB.NET code generation
  3. Add WCF Data Services 1.5 full integration (using the new Data Service Provider)
  4. Prevent the generation of complex entities for all services

Future versions of the product will be fully part of OpenAccess and will also support RIA Services, Azure Services, and Visual Studio 2010 and WCF 4.0. Download today and send us feedback!

posted on Monday, December 07, 2009 9:39:31 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Monday, November 30, 2009

I have been a fan of ADO.NET Data Services (Astoria) for a long time. Last week at the PDC, Microsoft unveiled the new name for ADO. NET Data Services: WCF Data Services. That makes sense since Astoria was built on top of WCF, not ADO .NET. I thought that Astoria was a cool code name and that ADO.NET Data Services sucked as a product name. At least WCF Data Services sucks less since at least it is more accurate and reflects the alignment of WCF, REST capabilities of WCF, and RIA Services (now WCF Data Services).

Astoria, I mean WCF Data Services :), is a way to build RESTful services very easily on the Microsoft platform. Astoria implements extensions to ATOMPub and uses either ATOM or JSON to publish its data. The protocol that Astoria used did not have a name. Since other technology was using this Astoria protocol inside (and even outside of) Microsoft, Microsoft decided to give it a name and place the specification under the Open Specification Promise. Astoria’s protocol is now called: the Open Data Protocol, or OData.

If you have been using Astoria and liked it, not much is different. What is cool is that other technology is now adopting OData including: SharePoint 2010, SQL Server 2008 R2, PowerPivot, Windows Azure Table Storage, and 3rd party products like IBM’s WebSphere eXtreme Scale.

With all of this technology supporting OData, Microsoft created the Open Data Protocol Data Visualizer for Visual Studio 2010 Beta 2. The tool gives you the ability to connect to a service and graphically browse the shape of the data. You can download it from here or search the extensions gallery for Open Data. Once you have it installed you can view OData data very easily. Here is how.

To get started you first have to create a WCF Web Data Service. I just mapped Northwind to an Entity Data Model using the Entity Framework and then created the WCF Data Service. Then I added a console application and set a service reference back to that Astoria Service. My projects looks like this:

image

To start the OData Protocol Data Visualizer, just right click on the Service Reference and click “View in Diagram.” This “View in Diagram” menu option will show up when you have a Service Reference that is OData compatible, whether you created it or not. (Meaning if you have a Sharepoint list as your service reference, it will work as well.)

image

This brings up the diagram canvas and corresponding OData Protocol Model Browser.

image

From here you can select an entity from the Model Browser and drag it onto the canvas. I dragged over the Customer entity and right clicked and was able to add all related entities.

image

From here you can interrogate your model and start to learn about it, all in Visual Studio. This is a great little add-in!

Enjoy!

Technorati Tags:
posted on Monday, November 30, 2009 7:43:07 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Tuesday, November 03, 2009

I have a simple demo application that uses ADO.NET Data Services as a data service back end for a Silverlight application.  My ADO.NET Data Service uses the Entity Framework to map the Northwind database tables of Customers, Orders, and Order Details. Once the Silverlight applications sets a service reference to the ADO.NET Data Service, you can use the client side LINQ libraries to build your application. My application looks like this, it has a drop down filled with customers, a grid with Order and a grid with Order Details. As you click on each one, it will filter the rest.

image

The LINQ statement for the drop down looks something like this:

   1:  //this uses the LINQ to REST proxy (servicereference1)
   2:  NorthwindEntities dat = new NorthwindEntities(
   3:      new Uri("Northwind.svc", UriKind.Relative));
   4:   
   5:  //linq query to get customers in ComboBox
   6:  var customers = from c in dat.Customers
   7:                  orderby c.CustomerID
   8:                  select c;

 

Pretty basic LINQ stuff. What I would like to do next is bind my drop down combobox to customers. There is one catch, since we are in Silverlight, this processing has to be done asynchronously, so that data binding code has to be done elseware.

There are a few ways to do this, the most straight forward it to set a delegate and catch an event, etc. Another is to use a code block and catch the event right in the same method.

While both of these solutions are fine, I don’t like them. I don’t like them because they look funny and pollute my data access code with tons of async communication stuff. Lastly, for each area where we have a LINQ statement, we have a lot of repetitive similar looking code. Every bone in my body wants to make that generic and only call it once.

Enter the AsyncLINQManager class I wrote. Forget about the details of this class for now, I will list it below in full. For now let’s show how to use the LINQ statement with the helper. First you have to create an instance of the AsyncLINQManager and then register an event. (No getting around the events!) You can do this in the page load handler:

   1:  //ref to the linq manager
   2:  alm = new AsyncLINQManager();
   3:  //register an event so we can do the databinding
   4:  alm.OnEntityFetched += Page_OnEntityFetched;

Now your LINQ statement needs one more line of code. Here is the same LINQ statement from above, passing customers to the AsyncLINQManager:

   1:  //this uses the LINQ to REST proxy (servicereference1)
   2:  NorthwindEntities dat = new NorthwindEntities(
   3:      new Uri("Northwind.svc", UriKind.Relative));
   4:   
   5:  //linq query to get customers in ComboBox
   6:  var customers = from c in dat.Customers
   7:                  orderby c.CustomerID
   8:                  select c;
   9:  //call async functions for the linq query
  10:  alm.LinqAsync(customers);

Line 10 is the only new line of code. Now the LINQ manager will take care of all of the async processing for us and we just have to put our data binding code in Page_OnEntityFetched() shown here:

   1:  //this event handler will do the actual databinding
   2:  void Page_OnEntityFetched(EntityEventArgument args)
   3:  {
   4:      switch (args.TypeName) //we get this info from the event
   5:      {
   6:          case "Customers":
   7:              CustomerCbo.ItemsSource = args.returnedList;
   8:              break;
   9:          case "Orders":
  10:              dg.ItemsSource=args.returnedList;
  11:              break;
  12:          case "Order_Details":
  13:               dg_Details.ItemsSource = args.returnedList;
  14:              break;
  15:   
  16:      }
  17:  }

 

You will notice that we do all of our data binding here, for all of our LINQ statements. This is the value of the AsyncLINQManager, now all of my binding code is in the same place. (I am sure that there will be some who disagree, but hey, build a better AsyncLINQManager and blog about it and I will link to it. :) )

So let’s take a look at the code to query the orders, you will notice that it will call the same LINQ manager and then have to come back to Page_OnEntityFetched() to do the binding:

   1:  //orders
   2:  private void AsyncBindOrdersCbo(string customerid)
   3:  {
   4:   
   5:  //this uses the LINQ to REST proxy (servicereference1)
   6:  NorthwindEntities dat = new NorthwindEntities(
   7:      new Uri("Northwind.svc", UriKind.Relative));
   8:   
   9:  //linq query to filter the Orders in the grid
  10:  var orders = from o in dat.Orders
  11:               where o.Customers.CustomerID == customerid
  12:               orderby o.OrderDate
  13:               select o;
  14:   
  15:      alm.LinqAsync(orders);
  16:   
  17:  }

What I really  like is that you can go ahead and write a simple LINQ statement like you are use to, pass the result to the AsyncLINQManager for processing and then just have one event handler take care of all of your data binding. To me, your code is more clean and your developers can code the LINQ statements almost like normal (minus that one extra line of code) and forget about all of the async stuff.

The code for the AsyncLINQManager is here. All it is doing is sending out the async request, catching it, and then returning an IList and object name in the event args.

   1:  using System;
   2:  using System.Linq;//for IQueryable
   3:  using System.Data.Services.Client;//for DataServiceQuery
   4:  using System.Collections;//for ILIST
   5:   
   6:  namespace LinqUtilities
   7:  {
   8:      //ASYNC Linq stuff
   9:      public class AsyncLINQManager
  10:      {
  11:          //see the EntityEventArgument class below for the event args
  12:          public delegate void EntityFetchCompleted(EntityEventArgument args);
  13:          //developer must register this event in the UI code to catch the IList
  14:          public event EntityFetchCompleted OnEntityFetched;
  15:   
  16:          //pass in linq query object for execution
  17:          public void LinqAsync<T>(IQueryable<T> qry)
  18:          {
  19:              //generic async call to start the linq query
  20:              DataServiceQuery<T> dsq = (DataServiceQuery<T>)qry;
  21:              //Call the code async and assign OnFetchComplete to handle the result
  22:              dsq.BeginExecute(OnFetchComplete<T>, dsq);
  23:           }
  24:   
  25:          //method to handle the async result
  26:          void OnFetchComplete<T>(IAsyncResult result)
  27:          {
  28:              //catch the status of the async call
  29:              DataServiceQuery<T> dsq =(DataServiceQuery<T>)result.AsyncState;
  30:              //if we are done, then stuff the data into a untyped List
  31:              if (OnEntityFetched != null)
  32:              {
  33:                  //delegate for event
  34:                  OnEntityFetched(new EntityEventArgument
  35:                                 { returnedList = dsq.EndExecute(result).ToList() });
  36:              }
  37:          }
  38:   
  39:      }
  40:      
  41:      
  42:      //event args class for the event on the client to 
  43:      //see what linq query they are handling
  44:      public class EntityEventArgument : EventArgs
  45:      {
  46:          public IList returnedList { get; set; }
  47:          public string TypeName
  48:          {
  49:              get { return returnedList.Count == 0 ? string.Empty : returnedList[0].GetType().Name; }
  50:          }
  51:   
  52:      }
  53:  }

You can download the sample code and the AsyncLINQManager code from my “DataAccess Hacks and Shortcuts” session demos here.

Enjoy!

Technorati Tags: ,,
posted on Tuesday, November 03, 2009 4:42:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Monday, November 02, 2009

Microsoft’s SQL Azure database offering has great 3rd party support. This week Telerik is releasing its Q3 version of its entire product line and the OpenAccess ORM will have more robust and native support for SQL Azure over what is currently available. I will expand on the example I did last week on connecting to SQL Azure by showing how to work with OpenAccess entities via WCF in a Silverlight application.

The fist thing that you have to do is create a project for your data access layer and connect to SQL Azure. I started a new class library and used the Enable Project to use ORM wizard. This is where you can specify your SQL Azure user account and credentials. I showed how to do this last week, so I will skip the steps here. (This is a new feature of Q3, in the previous version of OpenAccess, you had to use the SQL Server provider, now OpenAccess supports SQL Azure natively!)

Next we have to create a project to contain our WCF service. What we have to do next is point the Telerik Data Service Wizard to the DAL project and have it automatically create the SVC and CS files of our service for us.  The wizard will automatically create all of the CRUD methods for our entities. (In this demo I only used Customers.) In case you have not used the wizard yet, here is a walk through video on how to do that.

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

Now we will have two projects, one for our DAL and one for our WCF service. Now, add a Silverlight project and your solution should look like this, four projects: the DAL project, the WCF service project, the Silverlight Web project and the Silverlight project itself.

image

Next up we set a service reference to our WCF service and call the ReadCustomers method to get a list of all the customers and bind it to a XAML grid. (Remember that this being Silverlight, we have to do it all asynchronously.) We do this inside of a LoadData method in our form.

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

The first thing that we do in the code above is create a reference to our WCF service in line 4 and then register an event handler to catch the asynchronous completion of the event on line 6. On line 9 we make the (asynchronous) call to ReadCustomers(). Since ReadCustomers() will process asynchronously, we will have to go to the ReadCustomersCompleted() method to catch the event. Let’s look at that here:

   1:   
   2:  void ReadCustomersCompleted(object sender, ReadCustomersCompletedEventArgs e)
   3:  {
   4:      //if the filter is set use a LINQ statement
   5:      //this can also be done on the server via the service
   6:      if (CheckFilter.IsChecked == true)
   7:      {
   8:          var filter = from c in e.Result
   9:                       where c.Country == "Germany"
  10:                       select c;
  11:   
  12:          dataGridCustomers.ItemsSource = filter;
  13:      }
  14:      else
  15:      {
  16:          dataGridCustomers.ItemsSource = e.Result;
  17:      }
  18:  }

In ReadCustomersCompleted we are doing seeing if a checkbox is checked and if so, we do some client side LINQ statements to filter on the client for only customers in Germany. (This is a holdover from a demo I did at BASTA in Germany, of course you should move your countries to a drop down list and then filter with a parameter! Better yet, filter via the WCF service on the server!) If the checkbox is not checked, we will just show all of the customers.

image

If you want to edit a customer (or add, etc), the Silverlight grid allows you to do this inside the grid itself. However, you have to make sure that all of your dirty records are recorded so you only send back the dirty records to your backend WCF service. (Why bother updating all of the records?)

Here is the code to build the collection on the Begin Edit of the grid. This code just adds the current customer object into our custom collection (editedCustomers) so we can loop through it later on if we are doing an update.

   1:  void dataGridCustomers_BeginningEdit(object sender,
   2:   DataGridBeginningEditEventArgs e)
   3:  {
   4:      //build a list of Customer that are dirty
   5:      Customer customer = e.Row.DataContext as NorthwindWCFService.Customer;
   6:   
   7:      if (!editedCustomers.Contains(customer))
   8:      {
   9:          editedCustomers.Add(customer);
  10:      }
  11:  }

 

Now that we have our collection of dirty customers, we have to deal with the save button. The code below is run when the user clicks on the save button, saving all dirty records. Line 6 sets up the WCF service via the proxy and line 8 registers the event. Lines 11-15 is a loop of all of the dirty customers. (I get them via the custom collection editedCustomers shown above.) Inside of the loop on line 14 we make the actual asynchronous call to the WCF service’s UpdateCustomer method passing in the object and its correct ID. While the UpdateCusotmerCompleted event will fire (since this method is called asynchronously) when the update is complete, we have nothing really in that method except some cleanup of our custom collection and a message box to the users that the update is complete.

   1:  void ButtonSave_Click(object sender, RoutedEventArgs e)
   2:  {
   3:      
   4:      //the WCF service
   5:      //ref to our service proxy
   6:      SampleWCFServiceClient client = new SampleWCFServiceClient();
   7:      //register the event handler-can move this up if you want
   8:      client.UpdateCustomerCompleted += UpdateCustomerCompleted;
   9:   
  10:      //save only the dirty customers
  11:      foreach (NorthwindWCFService.Customer customer in editedCustomers)
  12:      {
  13:          //call the WCF method async to update the customer
  14:          client.UpdateCustomerAsync(customer.CustomerID.ToString(), customer);
  15:      }
  16:   
  17:  }

That is all there is too it! An add or delete is done in the same way.

Enjoy!

Technorati Tags: ,,,
posted on Monday, November 02, 2009 5:13:59 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Friday, October 30, 2009

With the official release of SQL Azure less than three weeks away, we are starting to see mainstream vendor support for SQL Azure. Telerik’s OpenAccess ORM is no exception. With the Q3 release of OpenAccess next week, OpenAccess will have full support for SQL Azure, going further than the basic support available today that I demonstrated on my blog last month. Full wizard support, forward and reverse mapping, and of course data services support via the Telerik Data Services Wizard. Let’s take a look at the basics here.

Getting Started

To get up and running and show the mapping and LINQ support, I will open Visual Studio 2008 (or 2010) and create a simple Console Application named OpenAccess.Azure.Demo. The first step is to enable the project to use OpenAccess via the Enable Project Wizard. As part of the wizard you need to specify which database you are going to connect to. OpenAccess gives you many choices besides Microsoft SQL Server, and one of the native choices is Microsoft SQL Azure. After you select SQL Azure, you will need to provide your credentials (don’t forget to put the tcp: in front of your server name.)

image

After you connect and finish the wizard, it is time to do some mapping.

Mapping Database Objects

To map some database objects to persistent classes, choose the Reverse Mapping wizard. This will bring up the Reverse Mapping dialog where you can select which tables, views, and stored procedures you want to map. In this case I will just select all of the defaults and map all of Northwind (remember I migrated Northwind up to SQL Azure.) Now it is time to build a simple application.

image

Working with SQL Azure Data

Let’s write a LINQ statement to fetch all of the customers from one country and print it out to the console window. First tings first, you have to put in a using statement for OpenAccess:

using Telerik.OpenAccess;

Next we will create our LINQ statement. The LINQ statement will work like any LINQ statement in OpenAccess, there is nothing special for SQL Azure, this LINQ statement would work against SQL Server, MySQL, or Oracle.

   1:  static void Main(string[] args)
   2:  {
   3:      //data context
   4:      IObjectScope dat = ObjectScopeProvider1.GetNewObjectScope();
   5:      //LINQ Statement
   6:      var result = from c in dat.Extent<Customer>()
   7:                   where c.Country == "Germany"
   8:                   select c;
   9:      //Print out the company name
  10:      foreach (var cust in result)
  11:      {
  12:          Console.WriteLine("Company Name: " + cust.CompanyName);
  13:      }
  14:      //keep the console window open
  15:      Console.Read();
  16:  }

The LINQ statement uses the data context, or IObjectScope in line 4, has a simple LINQ statement on lines 6-8 to filter by the customers in Germany and then iterates those customers and prints them out to the console window in lines 10-13. The result is shown here:

image

Pretty basic application, however, you can see that Telerik OpenAccess has full support for SQL Azure. Next week I will show a more complete example.

Enjoy!

Technorati Tags: ,
posted on Friday, October 30, 2009 3:47:58 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, October 27, 2009

The Telerik WCF Wizard that I have shown on this blog several times has been updated and is available on Telerik Labs for download.

Whenever Telerik puts something up on Telerik Labs we hope that some early adopters will try it out and give us feedback. We had an amazing demand for the Telerik OpenAccess WCF wizard and got tons of feedback. The most overwhelming piece of feedback is the name of the wizard: so as of this CTP, the wizard is now renamed the Telerik Data Services Wizard.

screen1

We made some key enhancements in this build for useability. The big thing is that you no longer have to be an ADMIN user to use the wizard. In addition, we made some of the navigation simpler as well as squashed some bugs (mostly around using LINQ statements in older versions of OpenAccess). Speaking of older versions of OpenAccess, the wizard will automatically detect what version of OpenAccess you have installed and auto-update itself to work with that version.

We’re working around the clock on a new build that will have Visual Studio integration and a new UI that is more consistent with the OpenAccess UI. A little further out, we will also include support for ADO.NET Data Services 1.5 CTP2 using the new “data service provider” interface available in Astoria 1.5. Once we are at that point, we will release this a full fledged beta with a target for the wizard to be part of OpenAccess proper by Q1 release next year at the latest.

Enjoy!

Technorati Tags: ,,,
posted on Tuesday, October 27, 2009 7:27:04 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, September 23, 2009

Yesterday at the BASTA! keynote I wrote an application on the fly showing how to write a WCF service and then call it from Silverlight asynchronously. Instead of posting the code, I figured that I would put up a walk through.

Getting Started

To get started fire up Visual Studio and start a new Silverlight 3.0 project. In order to use Silverlight 3.0 you will need the Silverlight 3.0 SDK installed. Once you have the new Silverlight application up and running you should have two solutions up and running, one with the Web host and one with the Silverlight XAML files. Right click on the Web project and choose Add|New Item and choose WCF Service.

image

Once you select the WCF Service, give it a name, I chose Basta1, but you can name it whatever you want. Next you will be brought into the interface file or Iyourservicename.cs. Here you have to define your POCO class as well as the method signature of your service.

In the demo I made a class of RockBand as shown here:

   1:  //POCO
   2:  public class RockBand
   3:  {
   4:    public int RockkBandId { get; set; }
   5:    public string RockkBandName { get; set; }
   6:  }

 

This is the definition of our “POCO” or “plain old CLR object” class. No attributes or any logic about the underlying database, just a simple CLR object. I am using a pretty simple design here, so if you are looking for some more complex demos or examples of using databases and ORM, check out my blog series on the Telerik WCF OpenAccess Wizard.

Now we have to define the WCF service contract. I will create a simple method, ReturnRockBands that will return a List of RockBand. Here we just define the method’s interface, we will implement the method in the service class.

   1:  [ServiceContract]
   2:  public interface IBasta1
   3:  {
   4:      [OperationContract]
   5:      List<RockBand> ReturnRockBanks();
   6:  }

Now just save the interface file and then go ahead and open the code behind of the SVC service file. We will implement the service contract interface of ReturnRockBanks (notice that I made a typo in my demo, hey you try coding in front of 500 people!)

   1:  public class Basta1 : IBasta1
   2:  {
   3:      public List<RockBand> ReturnRockBanks()
   4:      {
   5:          List<RockBand> rockbands = new List<RockBand>();
   6:   
   7:          rockbands.Add(new RockBand() { RockkBandId = 1, RockkBandName = "Depeche Mode" });
   8:          rockbands.Add(new RockBand() { RockkBandId = 2, RockkBandName = "The Smiths" });
   9:          rockbands.Add(new RockBand() { RockkBandId = 4, RockkBandName = "Britney Spears" });
  10:   
  11:          return rockbands;
  12:      }
  13:  }
  14:  }

 

This code is pretty straight forward, our class implements the interface we just created in line 1 and our method fills a List of RockBand and returns that list. We will now consume this service in Silverlight. But before we do that we have to change our WCF binding to basic in the web.config:

<endpoint address="" binding="basicHttpBinding" contract="SilverlightApplication20.Web.IBasta1">

Now just save (and compile) the project and let’s move into our client.

Building the Silverlight Client

We will create a simple Grid and a button in our XAML. When the user clicks on the button, we will call the WCF service and bind the data to the grid. Pretty simple application, but I just want to demonstrate how easy it is to do. A real application is not that much harder.

   1:  <StackPanel>
   2:  <data:DataGrid Name="MyGrid">
   3:   </data:DataGrid>
   4:  <Button Name="MyButton" Content="Push Me!" Click="Button_Click"
   5:  ></Button>
   6:  </StackPanel>

 

Since we defined a Click event for the button in line 4, let’s go into the C# code behind and call our WCF service. But first we have to set a reference to our service, we do that by right clicking on the “references” item in our solution and say “Add service reference.” Choose the reference we just created (by hitting the discover button) and we are good to go.

image

Now we have to do two things. First we have to set up a reference to our service proxy that was just created. This is done in line 3 and then we have to set an event to fire when our asynchronous call to the ReturnRockBank completes. This is done on line 4 and the method name to catch the event is called wcf_ReturnRockBanksCompleted. Lastly we call our WCF service’s method in line 6. Notice that the proxy added the “async” suffix to our method.

   1:  private void Button_Click(object sender, RoutedEventArgs e)
   2:  {
   3:      Basta1Client wcf = new Basta1Client();
   4:      wcf.ReturnRockBanksCompleted +=  wcf_ReturnRockBanksCompleted;
   5:      //call method WCF
   6:      wcf.ReturnRockBanksAsync();
   7:  }

Now we have to catch this event when it is done firing. We do that by implementing wcf_ReturnRockBanksCompleted. Then all we have to do is bind our data grid to the “result” in the event arguments (line 4).

   1:  void wcf_ReturnRockBanksCompleted(object sender, 
   2:          ReturnRockBanksCompletedEventArgs e)
   3:  {
   4:      MyGrid.ItemsSource = e.Result;
   5:  }

 

That’s it to get WCF services to work with Silverlight. When we run this and push the button, our application looks like this:

image

Now to make this a “real” application that is not hard coded, all you have to do is create WCF services for your CRUD methods and fill your POCO object with data from your database. There are tons of different approaches to doing that, you can check out some methods in my blog post here.

Enjoy!

posted on Wednesday, September 23, 2009 8:44:16 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, September 18, 2009

Over the past few weeks I have showed how to use Telerik OpenAccess with the WCF Wizard. I think that this wizard is a crucial piece of technology since I hate to write plumbing code myself, it takes me too long and I usually make mistakes.

I wish that SQL Azure would provide RESTful and WCF services wrapped around your database tables and views with just a check box in the Azure management page. But alas, I can dream. Until that day arrives, you will have to code the services yourself. So I decided to do it with OpenAccess and WCF (and of course the Wizard.)

First you need to get some data up in SQL Azure. Refer to my post from a few weeks ago as how to do that. Next you have to create a data access layer with Telerik OpenAccess. But you have to create your DAL against a local SQL Server 2005/2008 database with the same schema as the one up in SQL Azure. You have to do this because SQL Azure does not support querying of the schema. After you map your tables to classes (I will do just Customers for this demo), you have to go in and change the connection string in your DAL’s app.config to use SQL Azure instead of the database you used for the mapping:

   1:    <connection id="Connection1">
   2:      <databasename>Northwind_Lite</databasename>
   3:      <servername>tcp:tpzlfbclx1234.ctp.database.windows.net</servername>
   4:      <integratedSecurity>False</integratedSecurity>
   5:      <backendconfigurationname>mssqlConfiguration</backendconfigurationname>
   6:      <user>Stevef</user>
   7:      <password>gomets!</password>
   8:    </connection>

Now you have to create the WCF service via the wizard (if you forgot how to do that, watch this video). This will be done in a separate project to achieve a full separation of concerns.

image

After you create the WCF service via the Wizard, you can go ahead and create a Silverlight client. Your solution set up should consist of a DAL project, a WCF service project, a Silverlight web project, and a Silverlight client project.

image

 

Ok, XAML time. (In my head I am saying that to the tune of Hammer Time, but I digress….)  I will create a grid that will bind to the CompanyName, ContactName, City, and Phone fields of the Customer table. The grid will do most of the magic for us. I will also add a “Refresh” button as well as a “Save” button. The Refresh button will have the same LoadData() method as in all of my previous blog posts. We’ll talk about Save in a minute.

   1:  <data:DataGrid x:Name="dataGridCustomers" Grid.ColumnSpan="4" ItemsSource="{Binding}">
   2:      <data:DataGrid.Columns>
   3:          <data:DataGridTextColumn Binding="{Binding Path=CompanyName}"
   4:  Header="Company Name"></data:DataGridTextColumn>
   5:          <data:DataGridTextColumn Binding="{Binding Path=ContactName}" 
   6:  Header="Contact Name"></data:DataGridTextColumn>
   7:          <data:DataGridTextColumn Binding="{Binding Path=City}"
   8:   Header="City"></data:DataGridTextColumn>
   9:          <data:DataGridTextColumn Binding="{Binding Path=Phone}"
  10:   Header="Phone"></data:DataGridTextColumn>
  11:      </data:DataGrid.Columns>
  12:  </data:DataGrid>

 

If we run our application, you can see that the grid works as advertised, fetching data from SQL Azure.

image

I’ll go in and edit the city for the first record to say “Hong Kong.” In order to facilitate this, we need to handle the BeginEdit event of the grid. During this event handler shown below, we will stuff a Customer object into our own private collection so we know that the entity is dirty. (If we don’t do this, we won’t know which items are dirty and would have to update all of them, a big waste of resources.) I do this on line 9 (after a check to see if it already in my collection.)

   1:  void dataGridCustomers_BeginningEdit(object sender,
   2:                    DataGridBeginningEditEventArgs e)
   3:  {
   4:      //build a list of Customer that are dirty
   5:      Customer customer = e.Row.DataContext as NorthwindWCFService.Customer;
   6:   
   7:      if (!editedCustomers.Contains(customer))
   8:      {
   9:          editedCustomers.Add(customer);
  10:      }
  11:  }

Now we have to handle the button click. (When the user hits save.) The user can hit save after editing the entire page (or after each row if they prefer, but find me a user who wants to do that.) The code below calls the WCF service we created with the wizard asynchronously. In this case we call the service for each customer in our collection (loop is from lines 8-111, the call to the WCF service is online 10).

 
   1:   
   2:  void ButtonSave_Click(object sender, RoutedEventArgs e)
   3:  {
   4:      SampleWCFServiceClient client = new SampleWCFServiceClient();
   5:   
   6:      client.UpdateCustomerCompleted += UpdateCustomerCompleted;
   7:      //save only the dirty customers
   8:      foreach (NorthwindWCFService.Customer customer in editedCustomers)
   9:      {
  10:          client.UpdateCustomerAsync(customer.CustomerID.ToString(), customer);
  11:      }
  12:   
  13:  }

 

In the code directly above, we registered an event, UpdateCustomerCompleted, to fire when each Customer is done updating. In theory we don’t need to do anything as far as the data is concerned, however, we have to clean up our collection of dirty Customers (line 8) as well as set an internal counter to 0 (line 7). This will give us a clean slate when we start editing again. We will also use the opportunity to show a message box (line 10) to the user that the data was updated. (Yea, yea I know I need error handling, etc. This is a demo!! :) ) We do this clean up only after all Customers have been edited and their async calls have been caught. We do this with our counter (line 3 and 5), comparing our count to the number of dirty records. Old school, but effective.

   1:  void UpdateCustomerCompleted(object sender, UpdateCustomerCompletedEventArgs e)
   2:  {
   3:      this.updatedCount++;
   4:   
   5:      if (updatedCount == editedCustomers.Count)
   6:      {
   7:          updatedCount = 0;
   8:          editedCustomers.Clear();
   9:   
  10:          MessageBox.Show("All Customers have been updated successfully!",
  11:                                                "Updating Data", MessageBoxButton.OK);
  12:      }
  13:  }

 

You can see the results here.

image

So let’s do one last thing. Let’s add a client side filter. This will be a dirt simple one, using LINQ to Objects to filter for only customers in Germany. (Of course the filter should be dynamic, etc. Also you may want to move this functionality to the server via your WCF Service.)

In the XAML page, I provide a checkbox that says “Show only Germany.” When this is checked we will filter our results with a LINQ statement. When it is unchecked, we will show all the records.

image

Our LoadData() method calls the WCF service and registered an event, ReadCustomersCompleted. LoadData() is called on the page load, refresh button click, and check box click events.

In past demos, this just took the result and assigned it to the ItemSource property of the grid. In this case we will check to see if our filter check box is checked (Line 6) and if so, we will perform a LINQ query (Lines 8-10) and assign the result to the gird (Line 12). If the check box is not checked, we perform no filter (line 16).

 

   1:  void ReadCustomersCompleted(object sender, 
   2:                   ReadCustomersCompletedEventArgs e)
   3:  {
   4:      //if the filter is set use a LINQ statement
   5:      //this can also be done on the server via the service
   6:      if (CheckFilter.IsChecked == true)
   7:      {
   8:          var filter = from c in e.Result
   9:                       where c.Country == "Germany"
  10:                       select c;
  11:   
  12:          dataGridCustomers.ItemsSource = filter;
  13:      }
  14:      else
  15:      {
  16:          dataGridCustomers.ItemsSource = e.Result;
  17:      }
  18:  }

 

That is it! Of course you can create nice add and delete dialogs as well, it is just as easy.

Enjoy!

posted on Friday, September 18, 2009 6:37:59 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, September 15, 2009

The following video shows how to use the updated Telerik OpenAccess WCF Wizard with ATOMPub services via the WCF REST Starter Kit. The video is done by .NET Ninja in training Peter Bahaa and uses the same ATOMPub project I showed yesterday on my blog. Enjoy!

Telerik OpenAccess WCF Wizard: How-to Video #5: ATOMPub Property Selection from Stephen Forte on Vimeo.

posted on Tuesday, September 15, 2009 1:12:44 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Monday, September 14, 2009

Last week I showed how to use the Telerik OpenAccess WCF Wizard to automatically create a feed in Atom Syndication Format using the WCF REST Starter Kit’s Visual Studio project templates. Based on the feedback we have gotten from the community on the ATOMPub projects, Telerik has refreshed the WCF Wizard (go download it now) to enhance the ATOMPub projects.

Let’s take a step back first. The Atom Syndication Format is for feeds, similar to RSS. So when you run the project that we looked at in my blog last week in default IE 8 (or IE 7) feed view, it would look something like this. This is no different from what my feeds look like from CNN and ESPN, etc.

image

But how did IE decide what to put as the title or the description of each item in the feed? (And since we are just exposing OpenAccess entities as feeds, the real question is which properties (or database fields at the end of the day) did IE choose for you?)

If you go back to IE settings and turn off feed view (which I always recommend when working with Astoria, REST Collection, and ATOMPub services) you can view the raw XML.

image

As shown in raw XML ATOM feed below in lines 3 and 4 you can see that the Company Name and Contact name were randomly placed into those fields (and that is how IE uses that data to display.) Well it was not randomly selected, I just hard coded those two fields in my demo. For applications these two fields are usually ignored. But it would be nice to have them set to something useful.

   1:  <entry>
   2:    <id>ALFKI</id> 
   3:    <title type="text">Alfreds Futterkiste</title> 
   4:    <summary type="text">Maria Anders</summary> 
   5:    <updated>2009-09-14T08:16:30Z</updated> 
   6:   
   7:    <category term="customers" /> 
   8:  - <content type="text/xml">
   9:  
  10:    <Address>Obere Str. 57</Address> 
  11:    <City>Berlin</City> 
  12:    <CompanyName>Alfreds Futterkiste</CompanyName> 
  13:    <ContactName>Maria Anders</ContactName> 
  14:    <ContactTitle>Sales Representative</ContactTitle> 
  15:    <Country>Germany</Country> 
  16:    <CustomerID>ALFKI</CustomerID> 
  17:    <Fax>030-0076545</Fax> 
  18:    <Phone>030-0074321</Phone> 
  19:    <PostalCode>12209</PostalCode> 
  20:    <Region i:nil="true" /> 
  21:    </Customer>
  22:    </content>
  23:    </entry>

 

The latest version of the WCF Wizard will now give you a dialog, so you don’t have to alter the code at all. As you can see from the screen shot below, the wizard now gives us a drop down so we can choose which property to expose in feed view as the title and description. So just to be different, I will choose the company name as the title and the Address as the description.

image

 

When we look at the raw ATOMPub XML you will see Company Name and Address in lines 3 and 4.

   1:  <entry>
   2:    <id>ALFKI</id> 
   3:    <title type="text">Alfreds Futterkiste</title> 
   4:    <summary type="text">Obere Str. 57</summary> 
   5:    <updated>2009-09-14T08:47:12Z</updated> 
   6:     
   7:    <category term="customers" /> 
   8:  - <content type="text/xml">
   9:  
  10:    <Address>Obere Str. 57</Address> 
  11:    <City>Berlin</City> 
  12:    <CompanyName>Alfreds Futterkiste</CompanyName> 
  13:    <ContactName>Maria Anders</ContactName> 
  14:    <ContactTitle>Sales Representative</ContactTitle> 
  15:    <Country>Germany</Country> 
  16:    <CustomerID>ALFKI</CustomerID> 
  17:    <Fax>030-0076545</Fax> 
  18:    <Phone>030-0074321</Phone> 
  19:    <PostalCode>12209</PostalCode> 
  20:    <Region i:nil="true" /> 
  21:    </Customer>
  22:    </content>
  23:    </entry>

 

If you view the service in feed view in IE, you will now see the Company Name and Address as the title and description.

image

Of course this did not effect our Silverlight front end since the application just ignored those fields. Those fields are available to the application, but we did not use them (we only used two fields (company name and contact name from the main XML tree.)

image

posted on Monday, September 14, 2009 9:08:51 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, September 11, 2009

When SQL Data Services (now SQL Azure) released its first CTP it did not look anything like SQL Server: there were no tables, stored procedures, views, etc. With the new CTP, SQL Azure embraces SQL Server in the sky and supports the relational model, including stored procedures. This is good since there are millions of lines of stored procedures out there in production today and migrating them to SQL Azure is pretty easy.

I decided to give a simple stored procedure a test drive. I opened up SQL Management Studio, started a new query, entered in my SQL:

   1:  CREATE Procedure sel_CustomerOrder   
   2:  @CustomerID char(5)   
   3:  AS
   4:  SELECT o.OrderID, o.OrderDate,  p.ProductName,   
   5:       (od.UnitPrice*od.Quantity)-((od.UnitPrice*od.Quantity)*od.Discount) as TotalCost   
   6:  FROM orders o   
   7:       inner join [order details] od   
   8:              on o.OrderID=od.OrderID  
   9:       inner join products p  
  10:              on od.ProductID=p.ProductId  
  11:  WHERE CustomerID=@CustomerID
  12:  ORDER BY o.OrderID

 

I hit F5 and all was right with the world. So I decided to try it out:

Exec sel_CustomerOrder @CustomerID='ALFKI'

And got the expected results.

image

You can now use this stored procedure in all the applications that you connect to since SQL Azure supports standard ADO.NET connection strings. Pretty cool.

posted on Friday, September 11, 2009 12:48:44 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, September 10, 2009

I like the idea of a database in the cloud. We have sort of been doing it for years, connecting to a SQL Server database over 1433. With SQL Azure, we take this one level further and let Azure worry about the hardware. So we don’t have to worry about scaling out with the bandwidth, RAIDs, etc. 

Last week I showed the basics on how to migrate data from a SQL Server 2008 database to SQL Azure. Yesterday I showed using SQL Azure with Telerik OpenAccess  and the WCF REST Toolkit. Today I will show how to build a simple REST based application using ADO.NET Data Services (aka Astoria.)

To get started we need a SQL Azure database. See my previous blog post about the CTP and getting data into your SQL Azure database. Once you have a SQL Azure database all set up let’s get to work.

The next thing we need to do is to create a new Web project and create our Entity Framework data model. I’ll go ahead and create an Entity Data Model against my local SQL Server 2008 Northwind database that has the same schema as my SQL Azure one. This is because SQL Azure and the Entity Framework chokes on the designer (or at least my version!) I will map:

  • Customers
  • Orders
  • Order Details

Now that my EDM is all set up, I will go in and change the connection string in my web.config to use SQL Azure. Here is my new connection string:

<add name="NorthwindEntities" 
connectionString="metadata=res://*/Northwind.csdl
|res://*/Northwind.ssdl|
res://*/Northwind.msl;
provider=System.Data.SqlClient;
provider connection string=&quot;Data Source=tcp:tpzlfbclx123.ctp.database.windows.net;
Initial Catalog=Northwind_Lite;
Integrated Security=False;UID=Stevef;PWD=GoMets!;
MultipleActiveResultSets=False&quot;"
providerName="System.Data.EntityClient"/>

You have to manipulate the EF connection string and put in the SQL Azure server name of your CTP in the “Data Source” and put in the database name in the Initial Catalog, turn off integrated security and put in the UID/PWD from the CTP. I set MARS set to false since SQL Azure does not support MARS.

Now let’s create the Astoria Service. Add a new “ADO.NET Data Service” to your project. I named mine NwindRestService.

image

Astoria can’t make it any easier for you to get the service up and running. All you need to do is set up the name of your EDM in line 2, in our case it was NorthwindEntities and also set the access permissions on line 8. I just uncommented the generated line and put in an “*” so all of my entities will inherit the AllRead access rule. With that we are good to go!

   1:  //Enter the name of your EDM (NorthwindEntities)
   2:  public class NwindRestService : DataService<NorthwindEntities>
   3:  {
   4:      public static void InitializeService(IDataServiceConfiguration config)
   5:      {
   6:          //Must set up the AccessRule, here I allow read only access
   7:          //to all entities. I can also do this one by one.
   8:          config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
   9:      }
  10:  }

 

For the reality check, let’s run the service in the browser, being a RESTful service, Astoria will allow you to browse all of the Customers by typing in this URL:

http://localhost:1075/NwindRestService.svc/Customers

We should see this:

image

I also edited my first row in Northwind (ALFKI) to say “SQL Azure” at the end of the customer name so I know I am working with the SQL Azure and did not mess up my connection strings. That is it, you now have a RESTful service that is hooked up to SQL Azure.

The hard part is over. Now let’s build a simple ASP.NET client to consume the RESTful data.

First you have to set a reference to your service. This will give you a proxy to write some LINQ (to Astoria) code against.

image

 

Next we will create a simple ASP.NET GridView control and bind some data to it on the page load event. (Sure we can do a lot more, but this is just to get our feet wet with SQL Azure.)

   1:  //the address of our service
   2:  Uri url = new Uri("http://localhost:1075/NwindRestService.svc/", UriKind.Absolute);
   3:  //a ref to our proxy 
   4:  ServiceReference1.NorthwindEntities dat = 
   5:          new ServiceReference1.NorthwindEntities(url);
   6:   
   7:  //link statement to get the data, can use WHERE, Orderby, etc
   8:  var customers =
   9:      from c in dat.Customers
  10:      where c.Country == "Germany"
  11:      orderby c.CustomerID
  12:      select c;
  13:   
  14:  //bind to the grid
  15:  GridView1.DataSource = customers;
  16:  GridView1.DataBind();
 

This is pretty basic code from here.  Line 2 is a Uri reference to our service (which is technically in the same project, but it could (and should) be in a different project.) Line 4-5 is setting up a reference to the proxy we created and this is also our data context, representing the Astoria service. Lines 8-12 is a simple LINQ to Astoria statement to filter by the German customers (look like LINQ to SQL? That is the point!) and Lines 15-16 is where we do the data binding to the ASP.NET GridView. Our gridview looks like this, notice the ALFKI record says it is coming from SQL Azure:

image

That is all there is too it. Enjoy.

posted on Thursday, September 10, 2009 5:39:59 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, September 09, 2009

The following video shows how to use the Telerik OpenAccess WCF Wizard with ATOMPub services via the WCF REST Starter Kit. The video is done by .NET Ninja in training Peter Bahaa  and uses the same ATOMPub project I showed yesterday on my blog. Enjoy!

Telerik OpenAccess WCF Wizard: How-to Video #4- AtomPub from Stephen Forte on Vimeo.

posted on Wednesday, September 09, 2009 2:11:36 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, September 08, 2009

Feeds are part of what power Web 2.0. You can use RSS or ATOM to syndicate your content and allow readers to subscribe to your content. It is what powers Twitter, Facebook, as well as CNN and the New York Times. ATOM is a popular alternative to RSS. Just about every blog and “RSS” reader will support ATOM. When you are talking about ATOM, you actually are talking about two things: Atom Syndication Format, an XML language for feed definitions, and the Atom Publishing Protocol, a very simple HTTP protocol for creating and updating feed based content.

The WCF REST Starter Kit allows you to create services that will produce an ATOM feed or expose your data as a service via the ATOM Publishing Protocol. The WCF REST Starter Kit gives you a Visual Studio template to get your started.

You can use Telerik OpenAccess as a data source for the collections of your ATOMPub service. To do so you have to wire up some code in your svc file back to your OpenAccess entities. This can be accomplished by using the OpenAccess WCF Wizard.

Creating the ATOMPub Service and a Silverlight Front End

To get started, let’s create four projects in Visual Studio, one data access layer using OpenAccess, one AtomPub service project using the new WCF REST Toolkit Visual Studio template, and a Silverlight Web/Client.

image

Then you can use the Telerik OpenAccess WCF Wizard to automatically create the SVC and CS files for an ATOMPub service (the arrow above.) Once you have that and allow the project to talk to the DAL with a reference to that project, view the service in the browser for a reality check. You can do the format, similar to REST of: http:// server name / service name / resource name, for example:

http://localhost:54669/NorthwindAtomPubService.svc/Customers will return a list of all the customers and if you add an /CustomerID to the end of the URL like this: http://localhost:54669/NorthwindAtomPubService.svc/Customers/ALFKI then you will bring up one individual customer.

image

Now let’s consume this from a Silverlight application. Pretty easy stuff, but first we have to create a XAML grid:

<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>

After you build your XAML grid, let’s set a service reference to the AtomPub service and then start to write some code. Just like before, I will have a LoadData() method to fill the grid. Of course being Silverlight it has to be asynchronous. Here is the code.

   1:  private void LoadData()
   2:  {
   3:  //the URL of our ATOM Pub service
   4:  string uri = "http://localhost:54669/NorthwindAtomPubService.svc/Customers";
   5:  //set up the web request
   6:  HttpWebRequest request = HttpWebRequest.Create(
   7:      new Uri(uri)) as HttpWebRequest;
   8:  //HTTP GET (REST uses the standard HTTP requests)
   9:  request.Method = "GET";
  10:  //begin the async call in a code block
  11:  request.BeginGetResponse(ar =>
  12:      {
  13:          Dispatcher.BeginInvoke(() =>
  14:              {
  15:                  //catch the HTTPWebRequest
  16:                  HttpWebResponse response = 
  17:                      request.EndGetResponse(ar) as HttpWebResponse;
  18:                  //get the customers back
  19:                  var result = 
  20:                      Customer.GetCustomersFromAtom20Stream(response.GetResponseStream());
  21:   
  22:                  //stuff the customers into a LIST
  23:                  List<Customer> customers = new List<Customer>();
  24:   
  25:                  foreach (var customer in result)
  26:                  {
  27:                      customers.Add(customer);
  28:                  }
  29:                  //bind the LIST to the Silverlight DataGrid
  30:                  dataGridCustomers.DataContext = customers;
  31:              });
  32:      }, null);
  33:  }

 

This code is easier than it looks. We start off with a HTTPWebRequest for the service (line 6-7) using an HTTP GET (line 9) and a code block to handle the async call (starting on line 11) . This code block works similar to a callback method. Inside the code block we catch the HTTPWebRequest asynchronously and get the results into the implicitly typed local variable var on line 19. After that is just basic LIST stuff, filling the list and adding it as the source of the dataGrid.

image

Pretty easy. Since that was so easy, let’s shake it up a little bit. How about we make the backend database be SQL Azure instead of SQL Server 2008.

Connecting Telerik OpenAccess to SQL Azure

Turns out that using SQL Azure and Telerik OpenAccess is pretty easy. If you have an Azure schema that is the same as your SQL Server 2008 schema, all you have to do it change the connection string in the OpenAccess DAL project’s app.config.  Let’s change our connection string in the DAL project to use SQL Azure like this:

   1:  <connection id="Connection.Azure">
   2:    <databasename>Northwind_Lite</databasename>
   3:    <servername>tcp:tpzlfbclx123.ctp.database.windows.net</servername>
   4:    <integratedSecurity>False</integratedSecurity>
   5:    <backendconfigurationname>mssqlConfiguration</backendconfigurationname>
   6:    <user>Stevef</user>
   7:    <password>gomets</password>
   8:  </connection>

 

Line 3 is the server you get from the SQL Azure CTP program and the user name and password is what you set up when you got the CTP. (Don’t have a SQL Azure CTP? Sign up here!)

That is it. When I run it I get the same results, except that the data is coming from SQL Azure and not from SQL Server 2008. I went into my Northwind_Lite database in SQL Azure and edited the first Customer row so I always know the data is coming from SQL Azure:

Update Customers 
Set CompanyName= 'Alfreds Futterkiste SQL Azure'
Where CustomerID='ALFKI'

Now when I run the project, I see the data from SQL Azure:

image

That is all there is too it!

You can get the WCF REST Starter Kit here, the Telerik OpenAccess WCF Wizard here, and the code from this blog post here.

Enjoy!

posted on Tuesday, September 08, 2009 5:09:58 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Thursday, September 03, 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 03, 2009 8:59:03 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
    # Sunday, December 07, 2008

    Ever since the release of the Entity Framework and the Linq to SQL team’s move to the ADO.NET team we have been hearing about Linq to SQL being dead. The ADO.NET team (which owns the EF as well) released the roadmap where they said:

    “We’re making significant investments in the Entity Framework such that as of .NET 4.0 the Entity Framework will be our recommended data access solution for LINQ to relational scenarios.  We are listening to customers regarding LINQ to SQL and will continue to evolve the product based on feedback we receive from the community as well.”

    This caused an uproar as you might imagine. So a few days later Tim Mallalieu, PM of the Linq to SQL and Linq to EF teams clarified by saying this:

    “We will continue make some investments in LINQ to SQL based on customer feedback. This post was about making our intentions for future innovation clear and to call out the fact that as of .NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios….We also want to get your feedback on the key experiences in LINQ to SQL that we need to add in to LINQ to Entities in order to enable the same simple scenarios that brought you to use LINQ to SQL in the first place.”

    Sounds pretty dead to me. If you don’t believe me, just talk to any Fox Pro developer, VB 6 developer, or any Access developer who loves the Jet engine. They are still “supported” as well. As this has shaken out over the past month or so, there are two camps:

    I told you so! and No way man, it is part of the framework, it will be supported for 10 years!

    Well they are both wrong.

    The I told you so crowd is claiming victory. While Linq to SQL may be dead,  Linq to SQL has a lot of traction in the developer community. According to Data Direct Technologies’s recent .NET Data Access Trends Survey (November 24th, 2008), 8.5% of production .NET applications use Linq to SQL as their primary data access method. While this number is not huge, you can’t ignore these developers voting with their feet by using Linq to SQL in their applications.

    The “It is in the Framework” crowd also has it wrong. Just because something is in the Framework does not mean it will have a bright future. Windows Forms is in the framework and WPF is the “preferred” UI for Windows apps. ADO.NET is in the framework and Linq to SQL and EF are suppose to replace that?  Is anyone using System.Object anymore, or are we all using Generics?

    So what should the Linq to SQL developer do? Throw it all away and learn EF? Use nHibernate?

    No. The Linq to SQL developer should continue to use Linq to SQL for the time being. If the next version of the EF is compelling enough for a Linq to SQL developer to move to EF, their investment in Linq to SQL is transferrable to Linq to Entities. If Linq to SQL developers are to move in the future, Microsoft will have to provide a migration path, guidance, and tools/wizards. (The EF team has started this process with some blog posts, but the effort has to be larger and more coordinated.) When should the Linq to SQL Developers move to the EF? When this happens:

    • The EF feature set is a superset of the Linq to SQL feature set
    • Microsoft provides migration wizards and tools for Linq to SQL developers

    If Microsoft is serious about the Entity Framework being the preferred data access solution in .NET 4.0, why will have to do a few things:

    • Make EF 2.0 rock solid. Duh.
    • Explain to us why the EF is needed. What is the problem that the EF is solving? Why is EF a better solution to this problem? This  My big criticism of the EF team, the feedback I gave them at the EF Council meeting, is that they are under the assumption that “build it they will come” and have not provided the compelling story as to why one should use EF. Make that case to us!
    • Engage with the Linq to SQL crowd. This group can continue to provide feedback to the EF team since Linq to SQL has many features that EF/Linq to Entities needs.
    • Engage with the nHibernate crowd. Data Direct Technologies’s survey says that 18% of all .NET production applications use a framework like nHibernate, Open Access, or Spring.NET. (they also included ASP AJAX in this question, which is strange to me.) While you may not win all of these people over, you should find out what they like about their tools.
    • Engage with the “stored procedure” crowd.  The EF team on several occasions said that “Nobody is building an application using stored procedures and straight ADO anymore.” According to Data Direct Technologies’s survey, almost 65% of .NET developers are using straight Stored Procedures and ADO.NET and 14% are using the Enterprise Library, which is just a wrapper for SPs and ADO.NET. I am not attacking or defending this architectural decision, but the EF team has to realize that if this many of their customers are using this approach and there needs to be guidance, training, and migration tools, not to mention a compelling reason to move to EF.

    How will this shake out? I can’t tell you since I have no idea.The EF team (and nHibernate crowd) talk like the train has arrived at the destination already while in reality it has not even left the station. We are still at the station buying tickets (to an unknown destination). Stay tuned.

    posted on Sunday, December 07, 2008 10:14:31 AM (Eastern Standard Time, UTC-05:00)  #    Comments [9] Trackback
    # Friday, November 07, 2008

    I am a data guy. Maybe that is why the NHibernate Mafia likes to cal me a database weenie. Next week at TechEd Europe I am doing 5 sessions about data. Friday morning I am doing DAT02-IS Data Access Smackdown. As I said before, it is not really a smackdown, but a look at the SP1 technology and then have a discussion on how best to make choices about which technology to use in your projects. One of the things that I love is data as a service. That is one reason why I am so solidly behind the Astoria Project at Microsoft (aka ADO .NET Data Services.)

    One thing that I show in the Smackdown session is a simple LINQ to REST demo. Using LINQ you can go against a raw REST based data service. (You can also do this via a proxy, which I will also show at the session and at a later blog post.)

    I have a simple Astoria service here. Let’s take a look at how to talk to it via LINQ to REST. First you have to set a reference to System.Data.Services.Client and then pull in the namespace like so:

    using System.Data.Services.Client;

    Next you have to create an anonymous type to hold your data. Since we are modeling the Customer entity in my Astoria service you have to model the type to have exactly the same data types:

    public class Customer

        {

            public string CustomerID { get; set; }

            public string CompanyName { get; set; }

            public string ContactName { get; set; }

            public string ContactTitle { get; set; }

            public string Address { get; set; }

            public string City { get; set; }

            public string Region { get; set; }

            public string PostalCode { get; set; }

            public string Country { get; set; }

            public string Phone { get; set; }

            public string Fax { get; set; }

     

        }

    Next inside of a console application we create a new Uri to point to the Astoria service on my server. Then we will query the service using the Astoria Uri syntax ?$filter= and add that to the Uri. After that is real simple, just loop through the customers and do whatever you want with them. Pretty easy! In a future blog post I will show you how to use the traditional LINQ operands (from, where, select) against an Astoria service.

    static void Main(string[] args)

            {

                Console.Title = "Linq to Rest!!";

     

                Uri url = new Uri("http://stevef.goes.com/northwindservice/NorthwindService.svc/");

     

                DataServiceContext ctx = new DataServiceContext(url);

     

                IEnumerable<Customer> customers = ctx.Execute<Customer>(

                    New Uri("Customer?$filter=Country%20eq%20'Germany'", UriKind.Relative));

     

                //write it out to the console window

                foreach (var c in customers)

                {

                    Console.WriteLine(c.CompanyName);

                }

                //keep the window open

                Console.Read();

            }

    posted on Friday, November 07, 2008 11:44:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] Trackback