ADO.NET Data Service in Plain English

I have been using ADO.NET Data Service in Silverlight since Astoria team released the client library for Silverlight. I didn’t have a particular idea to use that service except this is something new that I like to try. After reading a few article about Astoria, I come to know that I can retrieve the data from Astoria service by typing the URL in browser. And we have to use the different HTTP verbs for CRUD operations. That’s all? I think “No”. So, I raised a question in MSDN forum last week. Today, I got very useful and informative reply from Mike Flasko. (Thanks a lot for your reply, Mike.)

Here is the original thread that I posted in MSDN forum. Now, I’m here to share this information with you all. Hope that you will find it useful.

Question : What is ADO.NET Data Service (Astoria)?

Hello,

Could anyone please explain me about ADO.NET Data Service in plain english without using marketing term?

AFAIK,
– we can query the data by typing URL in browser.
– it supports CRUD operations with different HTTP verb.

But I believe that there might be some important reasons why people created this framework.

  • What is the ADO.NET Data Service?
  • What are the advantages of using ADO.NET Data Service?
  • What’s wrong with Web service?
  • What is the reason why making differnt HTTP verb for CRUD operation?

Thanks in advance.
Michael Sync

Answer from Mike Flasko (Astoria Program Manager [MSFT] )

Hi Michael,

In general the goals of ADO.NET Data Services are to create a simple REST-based framework for exposing data centric services. We built the framework in part from analysis of traditional websites and then looked at how architectures were changing with the move to AJAX and RIA based applications. One key observation the team had was that in traditional approaches to web development the information exchanged between a client (ex. a webbrowser) and the mid tier was a combination of presentation + behavior + data (ex. HTML file with javascript and inline HTML tables of data) and that the core interactions to retrieve raw data was between the mid-tier and backend store (ex. SQL server or other). When we looked at RIA, AJAX, smart client, etc applications it became apparent that these architectures pushed much more “smarts” to the client tier where the client first retrieves the presentation + behavior information (as a DLL in the case of a Silverlight application) and then as the user interacts with the client application, the app turns back (ex. background async call) to the mid-tier to retrieve the data needed to drive the user experience. This is nothing new (separation of presentation + behavior from data), but its interesting to note it now not only a best practice but mandated in the architectures of today’s web and RIA apps. From this we looked at how such clients could consume data from the mid-tier today and how could we help improve the experience for the developer. A few areas came up:

  • Creating and maintaining rich data oriented services with current approaches requires a significant developer investment
  • Building generation purpose client libs/tools with current approaches to data centric services is hard

For #1, imagine you wanted to expose the data in your CRM database to you client tier application. Further assume you want to enable typical application scenarios like retrieving sorted views of the data, paging over the data, filtering, etc. To expose this data as a set of callable remote methods (using current approaches to developing web services) you would need to write a large number of methods to expose each of the entities in your CRM DB (customers, orders, etc) and then add additional methods for each to retrieve entities by key, sort them, page over them, etc etc. ADO.NET Data Services, addresses this issue by allowing you to declaratively state the contract of such a data centric service, by telling us the schema of the data and having the data services technology automatically create the required remote endpoints, enabling paging, sorting, etc with no code from the developer. Then as you change your data model, your service endpoints also change.

For #2 above, an interesting artifact of a REST-based approach to web services is that it promotes creating a uniform interface. That is, how you address items in an ADO.NET Data Service (i.e. how to construct URIs), how to interact with data (using HTTP verbs), etc is the same across any ADO.NET Data Service, regardless of the data it exposes. This uniform interface enables code reuse against your web services such that one can create reusable client libraries and UI widgets for all their services. For example, the ADO.NET Data Service team is doing this by shipping .NET , Silver light, AJAX, etc libraries which can talk to any data service. In addition, this feature (uniform interface) enables us to add features such as LINQ to ADO.NET Data Services since the translation of LINQ query statements to URIs is stable and well known.

This is already probably a bit too long Smile, but in addition to the items noted above, additional advantages of REST-based approaches also apply such as rich integration with HTTP such that you can leverage existing HTTP infrastructure (ex. HTTP Proxies) deployed at large …

I hope that helps….
~ Mike

Here are a few links for those who don’t know about REST Service.  

Hope you find it useful.
Related ~

Bulk Image Downloader for WordPress Users

A tool for downloading images from your WordPress.com blog to your local machine. It is also an example of how to use XML RPC service in C#.

Executable : WpBulkDownloader-Alpha-Executable.zip
SourceCode : WpBulkDownloader.zip

Contents

  • Introduction
  • Background
  • Software Requirements
  • How to use
  • How it works
  • FAQ

Introduction

This is a tool that helps you to download all of your images that you posted in your blog. This tool is created especially for WordPress.com users but it will support all other blogging softwares in future. You will definitely need this tool when you want to move your blog from wordpress.com to self-host.

WP Bulk Image Downloader (Alpha) for WordPress Users

Background

My blog was hosted on WordPress.com last year. I had too many images uploaded in my free space. When I wanted to move my blog to self-host, I noticed that there is no way to bulk-download all of my images from WordPress account to my local disk. I didn’t want to copy each and every images manually so I wrote this tool that can scan each and every urls from my blog and create the directory based on the URL. And then, download them into my local harddisk. It’s just 2 hours program that I wrote at that time. So, I’m sure that there won’t be all features that you want in this program. But don’t worry. Just drop a comment in this post. I will add the feature that you want in next release.

Software Requirements

How to use it?

The steps are very simple.

  • Configure your blog in Bulk Image Downlader. Click “Options” and fill your blog URL, user name and password as picture below.

WP Bulk Image Downloader - Options

  • Click “OK” button to save your configuration and close the dialog
  • Click “Get Files” button to get the list of image URLs from your blog. (You may need to wait a few minutes while retrieving the list of images from your blog.)
  • After retrieving the list of Image URL, you can click “Download” button to download the images to your local disk. (You may need to wait a few minutes while processing. )
  • After that, you can check all of your images in “Downloaded Images” directory.

How does it work?

Note: This is for those who like to read the sourcecode and want an explanation about codes. If you are just a normal user, you may skip this section.

Firstly, the program will read the user name, password and blogurl from config file. It will append “xmlrpc.php” which is the standard XML RPC interface for WordPress at the end of blogurl string. Then, it will invoke getRecentPost() API of wordpress. I used opensource XML-RPC.NET library in this sample. As there is no getPosts() API in xmlrpc.php, we have to use the alternative method (getRecentPost() API) for retrieving the posts from the blog. The max number of posts is set to 1000 in the program. If you have more than 1000 posts in your blog, you probably need to change the default value.

If the authenticating is successful then we will get the list of posts from the blog. So, we have to filter the URL of images from the contents. Initially, I was thinking to filter <img> tag from the content. But there are some cases that we used big image in <A> tag and small images in <img> tag. So, I decided to filter the <img> tag and <a> tag from the contents based on the extensions (*.jpg, *.png, *.gif) by using regular expression. After that, I shows the list of URLS in ListView.

When the user clicks “Download” button, I start downloading the image one by one. (Note: I used C# downloader class which is written by Shailen Sukul in this example. ) Based on the URL, the program will create the directory accordingly. For example, If the image URL is “http://your.wp.com/2009/09/image1″ then the program will create the directories like “09” folder under “2009” folder under “/Downloaded Images/” folder. So, you can easily upload all of your images to your new host via FTP.

That’s all about how Bulk Image Downloader works. If you have any question, please let me know.

FAQs

1. Can you make the better UI for this program?

Yes. Of course. I’m thinking to change this Windows Form to WPF version so that you will definitely get the better UI for this program.

2. The form is freeze while downloading the images. Why?

Sorry about this issue. For the time being, all processes are running in single thread so that UI will be freeze while processing. I will separate the UI and logic into different thread in next release.

3. Can I request new feature?

Yes. Of course. This is the main reason why I released it as alpha. Feel free to drop a comment in this post. I will make a list of feature requests and will be added in next version.

Liz called me an SOB

Liz at Successful blog (one of top blogs about blogging) gave me the Official SOB award yesterday. <link> I’m really happy to receive this award and this is my first time that I receive an award for my blog.

SOB (Successful and Outstanding Blogger) Award

What is SOB?

SOB stands for Successful and Outstanding Bloggers. This award is for those who are contributing a lot of great resources to the community and their readers. If you want to know more details about this award, you can read this link (What is an SOB? )

How to become an SOB?

The short answer is that you have to do something useful for other people. then, let liz know about your blog and what you contributed for community. That’s all. She will come and visit your blog. Then, she will decide whether she should call you an SOB or not.

Here is what Liz wrote about this in her blog ~

If You Want to Be an SOB

Find a way to start a dialogue about how blogging helps business, or carry the dialogue here back to your own blog. Offer a great feature, post, idea, or an article that will shed new light for the blogosphere. Add an outstanding idea, insight, or spark to the conversation going on at this blog or start one on your own and share what happened here. Contribute something that demonstrates that you think like a Successful and Outstanding Blogger. Find a unique way to “add value” to the conversation going on in the blogosphere to make it grow stronger.

Then just tell me about it. I’m pretty easy to persuade. E-mail Liz at lizsun2@gmail.com with a link to your post or a brief description of what you did.
That’s all there is to it.

Every SOB is automatically included in the SOB Hall of Fame. Stop in there when you’re looking for a great read.

Can’t wait until I can call you an SOB too.

The following post are the most popular posts of my blog and those are the reason that I become an SOB.

Technical Articles

Firebug Tutorials ( This tutorial is featured in the most of popular post of del.icio.us and the best links in Smashing Magizine. )

Blogging

Fun

Thanks a lot for giving me this award, Liz.

Silverlight Tips/Tricks: Communicating between Javascript and C#

This post is not an article. Just small notes that I made while I’m playing Silverlight. I attached all sample sourcecodes in this post. I hope you will find it useful. If you have some tips that you want to share with others, please let me know.

Contents

  • Calling Javascript function from C#
  • Passing the parameters to Javascript function from C#
  • Calling C# function from Javascript

Tip #1. How to call Javascript function from C#

Download : Sourecode (CallJSFromCSharp.zip)

  • Add System.Windows.Browser namespace
    using System.Windows.Browser;
    
  • Make your class scriptable by adding [Scriptable] attribute
    [Scriptable]
    public partial class Page : Canvas {
    
  • Register the scriptable object in constructor of your class or Page_Load
    WebApplication.Current.RegisterScriptableObject("EntryPoint", this);
    
  • Add eventhandler in your class
    [Scriptable]
    public event EventHandler CallbackToBrowser;
    
  • Open test.html.js file and Add onload() event in Silverlight.createObjectEx()
    function createSilverlight()
    {
    Silverlight.createObjectEx({
    source: "Page.xaml",
    parentElement: document.getElementById("SilverlightControlHost"),
    id: "SilverlightControl",
    properties: {
    width: "100%",
    height: "100%",
    version: "1.1",
    enableHtmlAccess: "true"
    },
    events: {
    onLoad: OnLoaded
    }
    });// Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
    var silverlightControl = document.getElementById('SilverlightControl');
    if (silverlightControl)
    silverlightControl.focus();
    }
    function OnLoaded(sender, args)
    {
    sender.Content.EntryPoint.CallbackToBrowser = onManagedCallback;
    }
    

    Note: “EntryPoint” is the scriptable object that you register in the PageLoad event in C#. And “onManagedCallback” is the name of Javascript function that you want to call from C#.

  • Add the following function that you want to call from C# in TestPage.html.js
    function onManagedCallback(sender, args)
    {
    alert("JS!");
    }
    
  • You can call Javascript function from C# by raising CallbackToBrowser event
    if (CallbackToBrowser != null) {
    CallbackToBrowser(this, new EventArgs());
    }
    

Tip #2. How to pass the parameters to Javascript function from C#

The default EventArgs class doesn’t have the parameters so that we have to create our own class which is inherited from EventArgs. Don’t forget to make it scriptable. Otherwise, it won’t work. (Thanks to Shawn Wildermuth who pointed me my mistake in this thread.)

Download : Sourcecode (PassParasToJsFromCSharp.zip)

  • Follow the step that I mentioned in Tip #1.
  • Add your own eventargs class in your silverlight project
    [Scriptable]
    public class EventArgs&lt;T&gt; : EventArgs {
    private T _data;public EventArgs(T args) {
    _data = args;
    }
    
    [Scriptable]
    public T Data {
    get {
    return _data;
    }
    }
    }
    
  • You have to change the code a lit bit for calling the javascript function from previous example
    if (CallbackToBrowser != null) {
    CallbackToBrowser(this, new EventArgs<string>("my value"));
    }
    
  • then, you can get the value which is passed from C# in Javascript function.
    function onManagedCallback(sender, args)
    {
    if(args.Data){
    alert(args.Data);
    }
    }
    

Tip #3: Calling C# function from Javascript

Download : Sourcecode(CallCSharpFromJS.zip)

  • Register the scriptable object in Page_load event of Page.xaml.cs.
    WebApplication.Current.RegisterScriptableObject("EntryPoint", this);
    
  • Add one button in TestPage.html and call the javascript function on onclick event of that button
    <input type="button" value="Click Me" onclick = "invokeManagedCode();" />
    
  • Write the javascript function to invoke the C# function.
    function invokeManagedCode(){
    var control = document.getElementById("SilverlightControl");
    control.Content.EntryPoint.Test();
    }
    

    Note: “SilverlightControl” is the id of Silverlight object that you created in TestPage.html.js. (If you are Silverlight 1.1 developer, you might not notice about that. )

  • Write the scriptable C# function like below
    [Scriptable]
    public void Test() {
    
    }
    
  • Set the breakpoint and run the application. (C# function will be fired when you click the button.)

Consuming ADO.NET Data Service (Astoria) from Silverlight

This post describes how to access the ADO.NET Data Service (Astoria) from Silverlight by using “ADO.NET Data Services Silverlight Add-On“.

Download : SourceCode

ADP.NET Data Service (Astoria) from Silverlight (Silverlight ListView)

Contents

  • Introduction
  • Prerequisites
  • Getting Started
  • SQL Database
  • Creating Web Application in Visual Studio 20008
  • Creating ADO.NET Entity Data Model
  • Creating ADO.NET Data Service
  • Silverlight ListView
  • Conclusion

Introduction

This article is just an introduction of how to use Astoria in Silverlight application. The sample that I used in this article is nearly as same as the sample which is mentioned in ASP.NET 3.5 Extensions Preview (Quick Start). But I used the Astoria Silverlight Addon and create the Silverlight listview that looks cool.

Background

Project Astoria Team released ADO.NET Data Service library for Silverlight on 11st January, 2008. This is very interesting news for Silverlight developer. I was thinking to give a try when I heard that news but a lot of things keep me busy until 15th of Jan. Now, I got a chance to try and make this sample for you all. I hope you guys like it.

Prerequisites

You need to install the following installers in order to use Astoria Service, Silverlight.

Getting Started

After installing all required installers, you started creating new project to give a try how to use ADO.NET Data Service in Silverlight application. Like my other articles, I will give you the step-by-step details on how to consume Astoria in Silverlight. If you are not clear something, please just drop a comment in this post. I will get back to you as soon as I can.

SQL Database

You need to create one database that can be used in our sample. (If you already download the sample, you can find the SQL database called EmployeeMgmt.mdf in zip file.) If you want to create your own database, open SQL 2005 management studio and create new database. Then, create new table and fill some data in that table. (As this article is not for creating the database in SQL, I won’t go step by step. If you have some problems in doing this, please let me know.)

Creating Web Application in Visual Studio 20008

After creating the database, we will start creating new ASP.NET web application in Visual Studio 2008.

  • Click “New Project” icon or Press “Ctrl+Shift+N”
  • Select “ASP.NET Web Application” and name the application as “ADO.NETSrv”
  • Click “OK” button
  • Go to the properties of “ASP.NET Web Application”
  • Select “Web” tab
  • Select “Specific” port as the screenshot below (Visual Studio uses the dynamic port for ASP.NET by default. But using the dynamic port will give us the trouble “Cross-domain issue” since we are going to hard-code the service URL in our silverlight project. So, we just make sure our site to run with static port.)Making the static port in Visual Studio 2008

This is about creating ASP.NET web application in Visual Studio 2008. We will create “ADO.NET Entity Data Model” in next step.

Creating ADO.NET Entity Data Model

  • Add new item “ADO.NET Entity Data Model” to our web application
    ADO.NET Entity Data Model
  • Click “OK” button (Entity Data Model Wizard will be shown as the picture below).
  • Select “Generate from Database”Model Generate from Database
  • Click “Next” button
  • Choose Your Data ConnectionChoose Your Data Connection
  • Click “Next” button
  • You have to choose your table in that step. (Customer table in my case)
    Choose Your Database Objects
  • Click “Finish” button (Visual Studio will create Model1.edmx in your project.)
    Customers Table

That’s all about creating “ADO.NET Entity Data Model” in Visual Studio 2008. We will create “ADO.NET Data Service” in next step.

Creating ADO.NET Data Service

  • Add “ADO.NET Data Service” to your web application (Note : If you don’t have ASP.NET 3.5 extension installed in your machine, you won’t see this template.)ADO.NET Data Service
  • Click “Add” button
  • Open “WebDataService1.svc.cs” file. ( You will see “WebDataService< /* TODO: put your data source class name here */ >” in WebDataService1 class.)
  • Write your data source class name in that place. ( WebDataService<EmployeeMgmtEntities> in my case.) If you don’t see the class in your intellisense, add your data model namespace (e.g. using EmployeeMgmtModel;) in that class. (if you don’t know what your data model namespace, you can check it in “Model Browser” )
  • Write the following code in InitializeService method
    config.SetResourceContainerAccessRule("*", ResourceContainerRights.All);
    

That’s all about creating ADO.NET Data Service in Visual Studio. You can run the project now. It will show you like Feed. So, if you want to see the XML, you need to disable the “Feed Reading View”. Go to “Internet Options”>Content>Feeds Setting. Uncheck “Turn on feed reading view”.

“Turn on feed reading view”.

Then, you can run the application. You will see the data as XML format in browser. You can query the data from url like http://localhost:49970/WebDataService1.svc/Customers or http://localhost:49970/WebDataService1.svc/Customers(1001)/ in address bar. (1001 is the id of first customer.) This is one cool thing about ADO.NET Data service. If you want to know more about this query, you can read here. Okay!!. We will create the Silverlight project in next step.

Creating Silverlight project with ADO.NET Data Service Silverlight Addon

  • Add the Silverlight project to your solution
  • Add “Microsoft.Data.WebClient.dll” as a reference in your silverlight project
  • Add the SilverlightLink to Web applicationAdd Silverlight Link
  • Copy TestPage.html, TestPage.html.js and Silverlight.js to Web Application
  • Set TestPage.html as a startup page
  • Create the class like below. (Note: The class name should be the same as your table name. The fields should be the same as your table structure.)
    public class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    }
    

    I don’t like to create that class in Silverlight project but this is by-design issues so that I have no choice. I hope Astoria Team will do something about it.

  • Write the following code in Page_Load event to invoke the ADO.NET Data Service from Silverlight
    try {
    WebDataContext ctx = new
    WebDataContext("http://localhost:50527/WebDataService1.svc");WebDataQuery<Customer> customers = ctx.CreateQuery<Customer>("/Customers?$orderby=CustomerID");
    
    foreach (Customer c in customers) {
    Console.WriteLine(c.CustomerID + "," + c.CustomerName);
    }
    }
    catch (Exception ex) {
    Console.WriteLine(ex.Message);
    }
    

You can set the breakpoint in foreach loop and run the application. You will get all records from your database. but how we can show the data in Silverlight?

Silverlight ListView

There is no Gridview or ListView in Silverlight application. So, we have to create our own control for that. Based on the design of Microsoft Download Beta, I have created one simple Silverlight ListView to show the data in Silverlight application.

Let’s try to check how our listview looks like. We have to comment all codes in Page Load event and write the following code to show the ListView. Then, run the application.

ListView _listview = new ListView();
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.UpdateView();
this.Children.Add(_listview);

Great! our listview looks cool.

Silverlight ListView

then, update the code like below in Page load event. And run the application. All records from Database will be shown in our ListView through ADO.NET Data Service.


try {

WebDataContext ctx = new
WebDataContext("http://localhost:50527/WebDataService1.svc");

ListView _listview = new ListView();

WebDataQuery<Customer> customers = ctx.CreateQuery<Customer>("/Customers?$orderby=CustomerID");

foreach (Customer c in customers) {
Console.WriteLine(c.CustomerID + "," + c.CustomerName);
_listview.Items.Add(new ListViewItem(c.CustomerID.ToString(), c.CustomerName));
}

_listview.UpdateView();

this.Children.Add(_listview);

That’s all about consuming the ADO.NET Data Service from Silverlight application. Even though this article doesn’t cover any details about ADO.NET Data Service, I hope you will get some understanding about how to use that service in Silverlight application. This is the purpose of writing this article. Hopefully, you enjoy reading it. Feel free to drop a comment if you have any suggestion or comment. Thanks.

Related ~

Ascgen2 – OpenSource Image to Text (ASCII) Converter

I found this awesome opensource image to ASCII converter from lifthacker blog. This project is hosted in SourceForge <link> and is completely written in C#. This project is released under GPL license and you can download the executable and sourcecode from SourceForge with free of charges. Here is the technique used in this tool.

Original Image

Tifa - Final Fantasy Girl

Generated Image

ASCII Girl

The image above is generated by uisng Ascgen2. If you want to take a look the generated HTML version, you can check this link. (Demo : http://michaelsync.net/demo/ASCII-tifa.html )

Credit : I got Tifa Lockhart’s photo from Google Image Search. Full credits go to the original creator.

BTW, this girl is animated but I think she is hot. Wat ya say?

Related ~