# Thursday, September 24, 2009

Those of you who know me know that I love Nepal. My first of four visits to Nepal was in 2002 and I have been hooked ever since. My Everest expedition in 2003 changed my life and my base camp expedition in 2008 was my first time acting as a professional guide. We also raised over $20,000 for charity on that adventure. I am leaving tomorrow (Friday Sept 25th) on a new challenge: building a school and library in the remote village of Chyangba in Nepal. Chyangba is a special place since it is home to my lead (sidar) Sherpa, Ngima. Ngima just summated Mt. Everest for the first time in May. Ngima has been at my side each and every trip I have made to Nepal and he is family to me.

The village where he grew up, where his mother lives, and where most of the Sherpa he hires for my trips live is Chyangba. Last year volunteers built a school there. This year we raised enough money to get a lot of books and get every kid a uniform. Now we are building a library. The structure is mostly built, we are headed there for the next 10 days to complete the project.

Joining me are:

Notice that 4 MVP are coming (including myself) representing 3.5 countries (since I am from USA but live in Hong Kong.) The four of us have decided to adopt Chyangba and will continue to return and donate to the village. I hope to create an endowment for the school and library and enable them to have internet access so the school in New York that we raised money for last year will be able to become a sister school and allow the kids to web cam each other. Next year we hope to bring running water to the village (we need $20,000 for that.)

I hope that as a community we can also help out. We are fortunate to have great jobs and great opportunity. When I told geeks in Germany this week at Basta! about my adventure, several handed me cash on the spot. (And due to the strength of the Euro it turns out to be a lot of money.) Individual members of Telerik have given me money as well and the company as a whole has supported my efforts. I spoke to the boys at arch-rival DevExpress and they are game too. If you want, you can donate here.

In addition to the 4 MVPs that are going, we have the organizers of the charity coming and Richard Campbell is bringing his wife and friend Roger from Vancouver. Roger is a carpenter, who brought about 90 lbs of tools and supplies. We spent all day today in Hong Kong looking for containers to pack the equipment in. (We found a good sturdy bag to get it all there.)

I’ll be going offline for two weeks, see you in early October….

image

posted on Thursday, September 24, 2009 9:45:33 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
# Tuesday, September 22, 2009

I will be doing my Daily Scrum talk and a keynote on Silverlight 3.0 Line of Business features at the Basta! Fall conference from September 21-25th in Mainz, Germany. Hope to see you there.

image

posted on Tuesday, September 22, 2009 2:43:50 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Sunday, September 20, 2009

Every fall, the kids go back to school, the weather gets cooler, Munich kicks off its annual Oktoberfest festival, and the fall conference season heats up. It seems that I always miss Oktoberfest. I had friends who lived in Munich earlier this decade and each year my trips to Mt. Everest got in the way. Now that Telerik has a Munich office, I got to go to Oktoberfest (O#) with geeks. I can see the eyes rolling by the non-technical readers of this blog (basically my Mom is the only non-technical person who reads this blog), however, geeks can drink a lot, judging by how I had to crawl up the spiral staircase in my hotel room last night. (Yes you read that right. I also thought that European rooms were suppose to be small. I think that the staircase is a cruel joke for Oktoberfest and they only give the room to dumb, obnoxious Americans, but I digress.)

IMG_0270

 

While I am here to talk about the future direction of OpenAccess and how to further evolve the WCF Wizard that I recently wrote a blog series on, we all will be headed up to Mainz for Basta 2009. Since the fall conference season is upon us, I figured I will outline here all of the events I will be speaking at this fall, plus a special trip to Nepal I want to tell you about.

Basta! 2009, Mainz, Germany 21-25 September

This is my first Basta event, but many of my colleagues have spoken there for years (including fellow RDs and ex RDs Ingo Rammer, Markus Egger, and Christian Weyer.) and have raved about the passion of the audience. I’ll be speaking on scrum as well as doing a keynote on Silverlight’s line of business applications (this keynote will be one long demo.) Telerik is also going to be there, as a sponsor and with a booth. We have enough tee-shirts for every man, woman, and child at the conference. Should be fun!

School building in Chyangba Village, Nepal, 25 September-October 6

Instead of going to Mt. Everest this year, I will be going to my sherpa’s home village and help construct a library for the local school. I am also going with a few other geeks like Richard Campbell, Kathleen Dollard, and Maciej Pilecki. We are raising money for the village and trying to set up an endowment. I would love to see the tech community help us. Since speakers don’t get paid for these events, my tagline this fall will be asking for geeks to donate to the cause. (Hey if people can “walk” for cancer, I can speak for a village.) More on this on a blog post later this week before I fly to Kathmandu, but you can sponsor here. I have to thank Telerik for being so supportive of this passion of mine.

DevReach, Sofia, Bulgaria 12-13 October

DevReach is another passion of mine since the conference founder Martin Kulov reached out to me for help in planning the first ever DevReach in 2006. It is also how I met the Telerik boys. It is also how I discovered how beautiful Bulgarian women are. All of that said, it is a great show, now in our 4th year and of course Telerik is a huge sponsor and will have a great presence there. I’ll be doing the scrum session as well as Data Access Hacks and Shortcuts and Building RESTful Applications with Microsoft tools.

CodeCamp, Cracow, Poland 17 October

Fellow RD Tad Golonka, who is totally awesome, introduced me to the crazy country of Poland (also another land of beautiful women, seeing a trend??) Long story short, but if you remember I was the global recruiter for the Curing Cancer project, and one of the folks I hired was Szymon Kobalczyk (also recommended by Tad.) Szymon, who says I have changed his life (I just hope for the better!), runs the CodeCamp, so I could not say no! Talking scrum and data as well and I expect to have a great time.

Software Developers Conference (SDC),  Arnhem, The Netherlands, 19-20 October

This will be my 12th year of speaking at SDC (something like 15 events) and my first SDC was back in May 1998. The SDC took a chance on a young inexperienced speaker (I only spoke at a few Advisor DevCons in the United States before then) and I am forever grateful. To be honest, I have no idea why the Dutch like me so much, I constantly show up for sessions drunk (one year they even put the word “Beer” in my session title (start listening at 22 minutes in)) and insult Dutch people. I got very drunk and very abusive in 2007 and they made me do a keynote in 2008. I guess I am not learning. That said, I will be back with the usual cast of characters.  This is my favorite event of the year.

Tech*Days Hong Kong 2-4 November

This will be my first time speaking at Tech*Days in Hong Kong. There are usually a few thousand folks at this event and I will doing a session called “Sharing Code between .NET and Silverlight” as well as my Daily Scrum talk. Looking forward to this one!

Tech*Ed Europe, Berlin, Germany 9-13 November

After setting a TechEd record of doing 10 sessions last year (only to break that record and do 11 in LA this year), the TechEd Europe organizers figured that they had enough of me and only assigned me 2 sessions (Estimation and “Agile Tools and Teams”.) I lost track, but I think this is my 10th TechEd in Europe! Telerik will be there in force with a booth and developers staffing the booth. This should be a great event.

PDC 2009, Los Angeles, California (why?!) 17-19 November

While PDC is pretty much a Microsoft only speaker event talking about future technology, Joel and I will be doing a BOF session on Agile Tools and Teams. Basically a repeat of our BOF at TechEd in LA (and my session in Berlin.  Watch this related video.) Telerik will be at the PDC in full force, as a sponsor and with a booth. Known for great software and also awesome must have t-shirts, we will have over 1,000 copies of our new t-shirt, making its debut at PDC. Stop by the booth for that (as well as .NET Ninjas, Geeketts, and some others.) Also Telerik will be unveiling its newest product and will have demos all week will give away licenses.

That is a lot of events, but it will be great! Hope to see you at one (or all)!

posted on Sunday, September 20, 2009 6:14:45 AM (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
# Thursday, September 17, 2009

As I showed yesterday, the new version of the Telerik OpenAccess WCF Wizard now allows you to work with any version of OpenAccess. Here is a video of how to do that by .NET Ninja in training Peter Bahaa.

Telerik OpenAccess WCF Wizard: How-to Video #6-Auto detection of OpenAccess Version from Stephen Forte on Vimeo.

posted on Thursday, September 17, 2009 4:19:58 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, September 16, 2009

When the Telerik OpenAccess WCF Wizard shipped last month, it only worked with the Q2 version of OpenAccess. The problem is that Telerik makes internal builds of a product available in-between releases so developers can play around with new bits faster-and the OpenAccess WCF Wizard did not work with them. Telerik Internal Builds fix bugs out of band so lots of folks us them. The feedback we got on the WCF Wizard is that the wizard should work with any version of OpenAccess, including internal builds.

image

The latest version of the Telerik OpenAccess WCF Wizard does just that. Now when you open the Wizard and you attempt to connect to a data access layer built by a version of OpenAccess that the Wizard does not understand, a versions store dialog will come up as shown below. The dialog will tell you what version of OpenAccess the DAL was created with and you will have to navigate to the Telerik.OpenAccess.dll file and add it to the versions store. You will also have to exit the wizard and come back in. Once you have done so, you are free to use the wizard with that version of OpenAccess. You will also be allowed to use older versions that are saved in the store.

image

Enjoy!

posted on Wednesday, September 16, 2009 2:46:40 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
# Sunday, September 06, 2009

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

Telerik OpenAccess WCF Wizard: How-to Video #3- REST Collection from Stephen Forte on Vimeo.

posted on Sunday, September 06, 2009 8:12:34 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, September 04, 2009

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

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

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

image

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

Connecting to SQL Azure with SQL Server Management Studio

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

image

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

image

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

image

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

image

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

select * from sys.objects

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

Migrating Existing SQL Server Objects to a SQL Azure Database

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

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

 

image

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

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

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

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

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

image

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

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

Migrating Data from SQL Server to SQL Azure

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

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

image

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

image

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

image

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

posted on Friday, September 04, 2009 4:19:51 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, September 02, 2009

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

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

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

     

    The corresponding TSQL will look like this:

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

     

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

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

    You can get the paper here.

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