Galin Iliev's blog

Software Architecture & Development

How to insert record to DB using Javascript and Astoria Service

I wrote several posts regarding Astoria Services and in this one I will demonstrate how to insert reocord in database using AJAX calls.

Read my previous post - How to consume Astoria Service - in order to get deeper into solution environment.

I extended Javascript code so there is one more function that add new record to database. As it is for demostration purposes excuse hard-coded values, please.

So in order to add new record you need:

  • to create and instanciate variable with appropriate JSON format. Be careful here! All required fields from DB must present and have valid values.
  • set HTTP POST verb to the request.
  • set URL that point to root of entity type (Customer in our case)
  • set Request's headers "Accept" AND "Content-Type" to "application/json"
    wRequest.get_headers()["Accept"] = "application/json";
    wRequest.get_headers()["Content-Type"] = "application/json";
  • set request body's content with serialized variable content.

and finally call Invoke() method.

Here is full function:

   1:  function createNewCustomer(custID, contactName, companyName)
   2:  {
   3:      //create new item
   4:      var customer = {__metadata: {Type:"Customer" },
   5:          CustomerID:custID ,ContactName: contactName, CompanyName: companyName, ContactTitle:"", Address:"", City:""
   6:          , Region:"", PostalCode:"", Country:"", Phone:"", Fax:"" };
   8:      //save item to server using Astoria Service
   9:      var wRequest =  new Sys.Net.WebRequest();
  10:      wRequest.set_httpVerb("POST");
  11:      wRequest.set_url("http://galcho-pc:86/northwind.svc/Customers"); 
  13:      wRequest.get_headers()["Accept"] = "application/json";
  14:      wRequest.get_headers()["Content-Type"] = "application/json";
  15:      wRequest.add_completed(function (response, eventArgs){
  16:          var statusText = response.get_statusText();
  17:          alert(statusText);
  18:      });
  20:      wRequest.set_body(Sys.Serialization.JavaScriptSerializer.serialize(customer));
  21:      wRequest.invoke();
  22:  }

And the button that execute is defined with following HTML

<input type="button" value="New Customers" onclick="createNewCustomer('AAAA','Galin Iliev', 'Galcho.COM');" />

Hope you find it interesting.

UPDATE: Here is sample project: (191.09 KB)

In order to run sample project do following:

  • make sure you installed the packages stated here.
  • extract files and modify Connection string NorthingEntites in web.config to match your SQL server that run Northwind DB
  • when running the sample make sure the URL in browser's address bar contain same hostname as in astoriaUrl JS variable (Default.aspx line 29) otherwise you will get "Access Denied!" error from browser single origin restriction. 

How to consume Astoria Service

A week ago I wrote about setting-up Astoria Service. Now is time to expose real power of Astoria - consuming data from client script.

Once you have setup your Web Data Service you're ready to write ASP.NET AJAX script to consume it. Basically you need these things:

  • set Requiest's header "accept" value of "application/json" so the data can be used directly in JS
  • call appropriate URL
  • and, of course, process data

The rest is done form Astoria team :) Kudos for them

this is how the code looks like:

   1:  function loadCustomers(){
   2:      var webRequest = new Sys.Net.WebRequest();   
   4:      webRequest.set_url("http://galcho-pc:86/northwind.svc/Customers");   
   6:      webRequest.get_headers()["accept"] = "application/json";
   8:      webRequest.add_completed(function (result){
   9:          var cust = result.get_object();   
  10:          for (i = 0; i < cust.length; i++){   
  11:              addCustomer(cust[i].ContactName, cust[i].CompanyName);
  12:          }  
  13:      });   
  15:      webRequest.invoke(); 
  16:  }
  18:  function addCustomer(contactName, companyName){
  19:      $get("customers").innerHTML += "<div>" + contactName + "</div>" + companyName + "<br/>";
  20:  }

There main function is loadCustomers(). It does all I described above. And there is a helper function that fills a DIV's innerHTML property with approperiate content.

Here is the HTML:

   1:  <div id="customers">
   2:      <span style="font-size: large; font-weight: bold; border: solid 1px black; width: 100%;
   3:          display: block;">
   4:          <div>
   5:              Contact Name</div>
   6:          CompanyName</span>
   7:  </div>

And the result looks like:


You can download full ASPX file from here: (0.94 KB)

More sophisticated article for Astoria consumer app is coming. It is based on MIX AJAX classed that provide infrastructure for CRUD operations.

Let's trace down to.... .NET Framework source :)

Microsoft announced they will release ... the source of .NET Framework 3.5 and we will be able to trace how our data is handled by .NET base libraries.

Also it would be very good for education purposes for young devs.

And, in the manner they say in TV Ads, this is not all. You also get access to  Program database - .pdb file - where debug symbols live so the VS 2008 IDE can match the code that is executed with the line is source code :)

So who says Microsoft is not open company?

(via ScottGu blog)

Getting started with Astoria (screenshots story)

Today I will lead you through the process of creating Astoria service. It is pretty easy as you’ll see.  In my previous post I described the required packages to run Astoria.

There are mainly to stages:

  • Create and setup Entity Framework data Model
  • Create Astoria Service

Once you have them you can start Visual Studio 2008 Beta 2

Then select form the menu Project -> Add new Item… and select ADO.NET Entity Data Model

Then we follow the EF wizard to Generate Model from database

We select accordingly the connection to MS SQL Server which has AdventureWorks dabatase.

On next screen we select objects that will be added to EF Schema and click Finish button:

And we have the schema ready to use:

Now we are ready to setup Astoria Service:

Select form the menu Project -> Add new Item…

When we have class generated all we have to done is to set Context Object for EF Model. We enter AdventureWorksModel.AdventureWorksEntities and compile.

And this is all! We are ready to use it. It was pretty easy,  wasn’t it?

Now let’s test it. All we have to do is loading AdventureWorks.svc from the browser:

On this screen we see all entities in the schema. We could navigate further with just changing URL:

You could play with some other Astoria specific queries like those (change your host:port to match yours):

There is one very good tool that you can use . On order to use the page you must host it on same application as Astoria service otherwise browser single origin check will stop the requests. So Save the page and add it to your project

In next post I will show you how to consume the data from Javascript

Astoria CTP Refresh for EF Beta 2

Pablo Castro annonced there is CTP Refresh of Astoria bits. Astoria is very cool project based on .NET 3.0 (WFC), Entity Framework to provide pure HTTP access to SQL Server data. This means that we will be able to pull data using... Javascript 

In order to use you need:

I am preparing a (short) article that shows how to leverage data from Javascript and ASP.NET AJAX... Stay tuned and I will annonce it here

Ultimate C# Tutorial

Unified C# 3.0 Specification Now Available. In this document (above 500 printed pages) you can find every C# feature and some examples. It can be called also "Ultimate C# Tutorial".

This document combines the 1.1 version of the spec, the 2.0 version, and various other bits and pieces into one large document some 500 pages in length. Here you will find the definitive technical description of the C# language in the words of the engineers who created it.  It is the single most authoritative reference for the C# language. Though not called out by name in this document, many of the people who created the C# language contributed to it, and they are its primary authors.

(via Charlie Calvert's Community Blog )

Update: If you are non-Bulgarian speaker or you do not want to read my LINQ Tutorial and you want quickly to ramp up with C# 3.0 (without reading 519 pages) you can find read C# 3.0 specifications (30 pages) by Anders Hejlsberg
(thanks to Matthieu Mezil)

Speed up ASP.NET Debugging with Patch for VS 2005

ScottGu announced VS 2005 HotFix Patch that speed up debugging ASP.NET related projects in VS 2005. You can read more about it in this KB article here.

Background on the Issue

The particular bug fixed in this hotfix was surprisingly difficult to track down.  The slowdown issue occurred when breakpoints were set in multiple source files in the same project that had the same short file names (for example: two default.aspx.cs files) and which were organized in a certain directory structure pattern on disk.  The patch fixes this issue and should prevent the debugger from pausing when trying to load the web project's assembly symbols in this case.

The bad news and the good news

LINQ to SQL Debug Visualizer was removed from VS 2008 Beta 1... if you use LINQ to SQL you know how useful it is to examine generated SQL code from LINQ statements as well as returned results. but it was removed from Beta 1 and still missing in Beta 2...

Now the good news :) There is way to install it back. But this is not all. You can download the source code and make changes (if you want) or just examine it. I guess there are no doubts who posted it :) - Scott Guthrie wrote a post with full explanation what is LINQ to SQL Debug Visualizer, how to use and how to install.

How to build custom LINQ provider?

Many people asked this question since May 2006 LINQ Preview was announced. We know there are several providers implemented by Microsoft:

But if we have custom datastore how we can implement LINQ provider for it? For a long time LINQ to Amazon by Fabrice Marguerie, was the only third-party provider and although he explained it was still many question left opened. (I've just found that there was LINQ to WebQueries by Hartmut Maennel predates LINQ to Amazon by few days.)

Matt Warren started very nice and deep series of blog posts that covers the process of writing custom LINQ provider. Even if you don't plan to write custom provider this post can give you an idea how the things work:

Of course, it is good idea to check if the provider is not written already :) See below list of providers.

OakLeaf Systems blog has a nice post that gives list of third-party LINQ providers (re-posted): 

  • LINQ to WebQueries by Hartmut Maennel handles searches in the SiteSeer and MSDN Web sites. (This provider predates Fabrice's LINQ to Amazon provider by a few days.)
  • LINQ to Amazon by Fabrice Marguerie, a co-author of the forthcoming LINQ in Action book, was the first third-party LINQ provider that I know of. LINQ to Amazon returns lists of books meeting specific criteria.
  • LINQ to RDF Files by Hartmut Maennel handles queries against Resource Description Format files' triples. Part I of the two-part post is here.
  • LINQ to MySQL by George Moudry, based on the LINQ May 2006 CTP, was in the development stage as of January 2007, but George says it's "capable of simplest queries and updates" and "now has support for most primitive joins."
  • LINQ to NHibernate by Ayende Rahien (a.k.a. Oren Eini) translates LINQ queries to NHibernate Criteria Queries and is based on the Orcas March 2007 CTP. The documentation that describes development of the provider presently is at the Part 1 stage.
  • LINQ to LDAP by Bart de Smet is a "query provider for LINQ that's capable of talking to Active Directory (and other LDAP data sources potentially) over LDAP." As of 4/11/2007, Bart's "IQueryable Tales - LINQ to LDAP" consisted of Part 0: Introduction, Part 1: Key Concepts, Part 2: Getting Started with IQueryable, Part 3: Why do we need entities?, Part 4: Parsing and executing queries, and Part 5: Supporting Updates.
  • LINQ to Flickr by Mohammed Hossam El-Din (Bashmohandes) uses the open-source FlickrNet C# library as its infrastructure.
  • LINQ to Google Desktop by Costa Rican programming language enthusiast Luis Diego Fallas supports GDFileResult and GDEmail types. A subsequent Adding support for projections to Linq to Google Desktop implements the LINQ Select expression.
  • LINQ to SharePoint by Bart de Smet supports writing LINQ queries for SharePoint lists in both C# 3.0 and Visual Basic 9.0 and communicates with SharePoint via Web services or though the SharePoint Object Model. The SpMetal command-line utility automates C# or VB class generation.
  • LINQ to Streams (SLinq, Streaming LINQ) by Oren Novotny processes continuous data streams, such as stock tickers or sensor data. The project's home page on CodePlex includes an animated GIF simulation of a stock ticker displayed in a DataGridView. The current version supports Select, Where, Order By, and Descending only.
  • LINQ to Expressions (MetaLinq) by Aaron Erickson (the developer of Indexes for Objects a.k.a i4o*) lets you query over and edit expression trees with LINQ. Like .NET strings, LINQ expression trees are immutable; the only way you can change a LINQ expression tree is to make a copy, modify the copy, and then replace the original. MetaLinq's ExpressionBuilder lets you create an "Editable Shadow of an expression tree, modify it in place, and then by calling ToExpression on the shadow tree, generate a new, normal, immutable tree." ExpressionBuilder is an analog of the .NET StringBuilder.

* i4o isn't a LINQ provider, per se, but a helper class that can increase the speed of LINQ queries against large collections by a factor of 1,000 or more. InfoQ published on June 22, 2007, Aaron Erickson on LINQ and i4o, an interview of Aaron Erickson by Jonathan Allen about i4o's purpose and background.

Hope you'll find this useful