Archive for the 'ADO.NET Data Services' Category

15
May

ADO.NET Data Services AJAX client library

When the ASP.NET 3.5 Extensions preview was released back in December, it included the ADO.NET Data Services AJAX client library embedded into the System.Web.Extensions assembly, making it possible to reference by name from a ScriptManager (as shown here). This made it pretty simple to get up and running in order to consume a data service from within your ASP.NET applications.

With the release of .NET 3.5 SP1 beta 1, the ADO.NET Data Services AJAX client library has been pulled out of the System.Web.Extensions assembly and is no longer available out of the box. Luckily, the same JavaScript files that were baked into the ASP.NET 3.5 Extensions release are available on Codeplex and can be downloaded (here) and included in your projects.

Do you feel like consuming a data service from ASP.NET AJAX is a common enough scenario that you’d like to see the ADO.NET Data Service AJAX client library brought back into the framework? Or is having it on Codeplex suitable for those few situations when you might need it?

05
May

Which Data Service client environment is most compelling to you?

One of the great things about ADO.NET Data Services is the flexibility around consuming it. Being able to create a single service that can in turn be leveraged by different applications in different environments makes it a very powerful feature. Currently there are three client-libraries available:

  1. Standard .NET (for the lack of a better term)
  2. Silverlight
  3. ASP.NET AJAX

I’m curious which client environment people feel will prove to be the most useful. If you were to adopt ADO.NET Data Services and begin implementing it in your applications, which scenario would you see a data service fitting into best?

Would the ease of data service creation and consumption enable you to begin creating more AJAX-enabled web applications? Does the Silverlight data service client library motivate you to begin looking into developing data-centric Silverlight applications?

I’m interested to hear your thoughts…

12
Jan

ADO.NET Data Services in Silverlight

One of the biggest questions I’ve received from folks is when they can begin to play with the ADO.NET Data Services bits within a Silverlight app. Well the time is now! I’ll post some info about how cool this is in the future. In the meantime, download the Silverlight add-on for ADO.NET Data Services.

06
Jan

ADO.NET Data Services Part 9: Data Modification - AJAX (Action Sequences)

Is it just me or is this article’s title a little ridiculous? I think anytime you have a name that makes use of a colon, a hyphen, and parentheses, that’s a good sign you’ve gone too far. I was really tempted to throw an exclamation point at the end, but I was afraid that would cause this entire blog to implode on itself. But you know what? That’s just the kind of grammatical insanity you can expect from this site.

In the previous article we saw the Sys.Data.DataService class’s insert, update, and remove methods, which beautifully allow us to perform data modification operations against a data service using the ASP.NET AJAX libraries. We also learned that as powerful as that method trifecta is, it lacks a unit of work behavior that is sometimes needed, and instead makes individual service requests for each call. I made the statement that the DataService class doesn’t support the unit of work pattern, and that statement is in fact true. But, that doesn’t mean that you can’t achieve a unit of work by other means. There are two classes in the ADO.NET Data Services AJAX libraries that we haven’t yet covered that offer the ability to group together data modification operations into a batch, and execute them all at once. These two classes are Sys.Data.ActionSequence, and Sys.Data.ActionResult.

An ActionSequence object is simply a wrapper on top of a DataService. It maintains a list of data operations, and then uses its underlying DataService reference to execute the operations one by one. There are two ways to create an ActionSequence:

  1. Using its constructor, which takes a DataService instance
  2. Calling the DataService class’s createActionSequence method

Of the two choices, the later would be the preferred method (by me at least). You’re already going to have a reference to a DataService object, so once you determine that you need to create an operation batch, you can simply generate an ActionSequence object for your respective DataService like so:

var sequence = service.createActionSequence();

Now instead of using the DataService reference directly, by calling its insert/update/remove methods, I’ll work with the newly created ActionSequence instance to build my operations batch. At any time when working with an ActionSequence, if you need a reference to its internal DataService, you can use its service property.

var service = sequence.get_service();

That way you can pass around a reference to an ActionSequence and still be able to access its underlying DataService if needed. This property is read-only, so you’re stuck with the DataService used when the ActionSequence was created.

The ActionSequence class has methods that mirror the insert/update/remove methods of the DataService class, with a few differences:

  1. The ActionSequence methods don’t return a Sys.Net.WebRequest instance. This is because as opposed to the DataService, each individual operation isn’t served by a specific WebRequest.
  2. The ActionSequence methods don’t take success/failure callbacks as parameters. This is because you aren’t concerned with responding to the success or failure of the individual operations, but rather the entire batch.
  3. The ActionSequence methods don’t execute immediately.

Note that throughout the rest of the article, the variable “sequence” will simply refer to the ActionSequence instance created above.

Inserting

To add an insert operation to the ActionSequence, you simply call its addInsertAction method. This method takes 4 parameters: the entity object to insert, the name of the entity set to insert it into, arbitrary context data, and a boolean that determines whether you want to pass the refreshed entity object data back to the sequence’s execution callback (the default value is true). Only the first two parameters are required, and the last two are optional, and familiar from the DataService’s insert method.

var manufacturer = { Name: "JC's Awesome Phones" }; 
sequence.addInsertAction(manufacturer, "Manufacturers");

As you can see, nothing special is going on here. The logic to create a new entity object hasn’t changed, and we’re working with our ActionSequence pretty similarly to the way we did with our DataService in the last article. If you don’t need context data, and you want the ActionSequence to pass back your refreshed entity data, your call to addInsertAction can be as simple as seen above.

Our ActionSequence now contains a single command to insert the new manufacturer upon submission. No action has been taken yet, we’re simply building up our batch.

Updating

In order to add an update operation to the ActionSequence, you call its addUpdateAction method. This method takes the exact same parameters as the addInsertAction method. The only differences are:

  1. The URI parameter isn’t required.
  2. The URI parameter refers to a specific entity resource, not an entity set.
  3. The fourth boolean parameter defaults to false instead of true.

I’m going to query for a specific manufacturer:

sequence.get_service().query("Manufacturers?$filter=Name eq 'Nokia'", onSuccess);

Note how I’m accessing the underlying DataService from my ActionSequence reference. This is great because you only have to maintain a reference to your sequence, and not also to your DataService.

I’m now going to change their name, and add that modification to the ongoing sequence:

function onSuccess(result) 
{ 
    result[0].Name = "Nokia is cool"; 
    sequence.addUpdateAction(result[0]); 
}

Note that because I don’t have any context data, and don’t care about the data being passed back to the sequence’s callback, I can simply call addUpdateAction, passing it the modified entity object instance, and nothing else. For the above to work, my ActionSequence instance obviously has to be global. If you don’t prefer to go that route, I could just as easily have passed the ActionSequence reference around as my context data:

sequence.get_service().query("Manufacturers?$filter=Name eq 'Nokia'", onSuccess, null, sequence);

And modified my success callback like so:

function onSuccess(result, context) 
{ 
    result[0].Name = "Nokia is cool"; 
    context.addUpdateAction(result[0]); 
}

You can begin to see the uses of the context data parameter. You can get pretty creative with it and do some pretty cool stuff. The only down side to the above approach is that you might loose some explicitness in your code. The above success callback doesn’t make it clear that the context parameter is an ongoing ActionSequence object. You could obviously rename the parameter to something like “sequence” instead, which would help, but still might not be as clear as you want. If you want to get really cryptic you could even do this all in one step:

sequence.get_service().query("Manufacturers?$filter=Name eq 'Nokia'", 
                            function(result, context) 
                            { 
                                result[0].Name = "Nokia is cool"; 
                                context.addUpdateAction(result[0]); 
                            }, 
                            null, 
                            sequence);

However you decide to approach this, you can see the flexibility you have, which is always a good thing.

Deleting

If you want to add a delete operation, you simply call the ActionSequence’s addRemoveAction method. This method takes three parameters: the entity object instance to delete, the canonical URI of the entity instance to delete, and arbitrary context data. All three parameters are optional. Just like the DataService’s remove method, addRemoveAction allows you to either specify just the entity object reference, just the entity’s URI, or both. All three scenarios will successfully delete data. I prefer the URI approach, since it saves you a query to the data service.

sequence.addRemoveAction(null, "Manufacturers(2)");

If I already had a reference to the manufacturer instance I wanted to delete (or I reconstructed it), I could just call:

sequence.addRemoveAction(manufacturer);

Use whichever form works best for your situation.

Alright, so I’ve now got an ActionSequence that contains three operations:

  1. I’m inserting a new manufacturer called “JC’s Awesome Phones”.
  2. I’m renaming the Nokia manufacturer to “Nokia is cool”.
  3. I’m deleting the manufacturer with the Id of 2 (sorry #2)

Now that I’ve got this batch, how do I actually run it? You simply call the ActionSequence’s executeActions method. It takes two parameters: a callback, and arbitrary context data. Note I didn’t call it a “success callback”, and there is no failure callback. This is because you are executing a batch of operations, some of which may fail, and some of which may succeed. The callback you specify to the executeActions method is simply going to be called when all sequence operations have completed, regardless of their success or failure. Note also that the context data provided to the executeActions method is representative of the entire batch. As you recall, each individual operation has their own context data as well (if specified), so only provide context data to the executeActions method if you want some arbitrary data scoped to the entire group.

The signature for the callback method provided to the executeActions method takes three paramaters: an array of Sys.Data.ActionResult objects, a boolean that determines whether any of the sequence’s operations failed, and the context data provided to the call to the executeActions method (if any). The later two parameters are optional, so if you don’t care about context data, or checking if any errors occurred at the batch level, you can simply omit them.

I’m not concerned with any context data at this point, so I’ll just execute my sequence, passing it a callback:

sequence.executeActions(sequenceCompleted);

Since I’m not using any context data, my callback method could look like the following:

function sequenceCompleted(results, hasError) 
{ 
}

The hasError parameter will be true if an error occurred in any of the sequence’s operations. This isn’t necessarily useful, since you don’t know which operation failed, but it can be used to make a high-level check, before you do any further digging for error resolution. The real point of interest here is the results parameter, which holds an array of Sys.Data.ActionResult instances. The ActionResult class represents the result of an individual data modification operation that was a part of an ActionSequence. So for every operation you add to the sequence, you will have an ActionResult object. In our case, the results parameter will be an array of three ActionResult objects.

The ActionResult class contains three read-only properties and no methods:

  1. actionContext
  2. operation
  3. result

The actionContext property simply returns whatever arbitrary context data you specified (if any) when you called addInsertAction, addUpdateAction, or addRemoveAction. Between the individual context data for each ActionResult, and the context data for the overall batch, you can get pretty creative :)

The operation property returns a string that equals either: “insert”, “update”, or “remove”, depending on what the actual operation was.

The result property is the most interesting, as its value depends on the actual operation:

  1. If the operation was an insert or update, and you specified to pass back the refreshed entity data when adding the operation to the sequence, then the result property will return a refreshed version of the inserted/updated entity object.
  2. If the operation was an insert or update, and you specified not to pass back the refreshed entity data when adding the operation to the sequence, then the result property will return null.
  3. If the operation was a remove, then the result property will always return null.
  4. If the operation resulted in an exception, then the result property will return an instance of Sys.Data.DataServiceError that contains information about the error that occurred.

For an explanation of the DataServiceError class see part 6 of this series. Knowing the above result criteria will make it so you can diagnose just about every possible scenario. Below is an example of a callback method that handles the completion of an ActionSequence’s execution:

function sequenceCompleted(results, hasError) 
{ 
    if (hasError) 
    { 
        for (var i = 0; i < results.length; i++) 
        { 
            var result = results[i]; 
 
            if (Sys.Data.DataServiceError.isInstanceOfType(result.get_result())) 
            { 
                alert("The following " + result.get_operation() + " operation failed."); 
            } 
        } 
    } 
    else 
    { 
        alert("All operations succeeded."); 
    } 
}

If no errors occurred, I alert the overall sequence success, otherwise I enumerate through every ActionResult instance to determine which operations erred, at which point I alert the error reason. You can see how you could do some pretty sophisticated exception handling if you wanted to. I’m not even checking for timeouts or examining the actual exception message, type, or stack trace. Needless to say, the ActionResult class, paired with the DataServiceError class, provides you with a nice amount of information.

Being able to use the ActionSequence class to create a unit of work is very beneficial. This coupled with the ability to make individual data modification requests, as we saw in the last article, makes for a very powerful and flexible environment for working with a data service using the ASP.NET AJAX libraries.

The ActionSequence class has one more method of interest: clearActions. If you for some reason need to flush your current ActionSequence, you can use the clearActions method like so:

sequence.clearActions();

You could imagine developing some pretty sweet AJAX applications that let the user create a series of data modifications, and then choose to undo them. I absolutely love the ADO.NET Data Services AJAX libraries. They provide you with some amazing power and functionality. Having an arsenal this strong in JavaScript makes it very compelling to move application logic to the client-side. Between WebDataContext, Sys.Data.DataService, and Sys.Data.ActionSequence, you can build some awesome data service client applications, regardless what the environment is. The only thing left to see is consuming a data service from within a Silverlight 2.0 application, which will be so beautiful I’ll most definitely shed a few tears.

In the last three articles we’ve seen how to perform data modification operations from a client’s perspective. What we haven’t seen yet are the service-side aspects that relate to data modification scenarios. In the next article, we will see just what has to be taken into consideration when creating a data service that needs to accept data modification requests.

04
Jan

ADO.NET Data Services Part 8: Data Modification - AJAX

In the last article, we discussed how to perform data modifications against a data service using the WebDataContext class. While that represents a great solution for most scenarios, the need for an AJAX story still exists. You may recall from part 6 that the WebDataContext class has a counterpart in the ASP.NET AJAX library, namely Sys.Data.DataService. Reason would lend us to believe that the same functionality exposed by the WebDataContext class, in terms of data modification, would be available and similarly exposed on the DataService class, and reason would be right.

In order to use the ADO.NET Data Services client library, you have to perform some minor setup. Please refer to part 6, if you haven’t done so already, and ensure that you can query your data service using the JavaScript DataService object. The following article is meant to be an extension of the previous two articles, and therefore won’t restate anything previously explained.

Before moving on, we need to mention a few differences between WebDataContext and DataService. The biggest difference between the two is that DataService does not act as a unit of work. What does that mean? It means that DataService doesn’t “cache” a series of data modification operation, and submit them all as a single unit. When you work with the WebDataContext class, and you add/update/delete entity objects, none of that takes affect until you call SaveChanges, at which point all changes made are submitted at once. When working with the JavaScript DataService object, all data modification requests are made immediately. In most cases, this behavior is what you would want anyways, but it’s important to expect this behavior, otherwise one might be confused when transitioning from using WebDataContext to DataService.

The second difference between the two environments is that when working with the DataService object in JavaScript, you don’t have a generated (or hand-written) client-side model. This means that we don’t have a Carrier, CellPhone, or Manufacturer class. This isn’t an issue though since DataService works purely with JSON objects. This means that in order to create instances of entity objects, all you have to know is their required properties. For instance, the Carrier model class only has two properties: Id, and Name. Id is a service generated identity property, so in order to create a new carrier, I’d only need to be concerned with the Name property.

var carrier = { Name: "Lost In Tangent Mobile" };

That’s all that it takes to create a new carrier instance. The same logic would be applied to create more complex entity instances. Without further ado, let’s jump right into how to perform each individual data modification operation.

Note: Throughout the rest of the article, the variable “service” simply represents a Sys.Data.DataService object that points at the data service.

Inserting

Using our DataService instance, how can we insert the carrier instance created above?

service.insert(carrier, "Carriers", onSuccess, onFailure, context, true);

The insert method takes six parameters: the object you want to insert, the name of the entity set to insert into, success callback, failure callback, arbitrary context data, and a boolean that determines whether you want the DataService to pass a refreshed entity object back to the success callback. Only the first two parameters are required. This will immediately submit the insert request to the data service, and then call the respective callback upon success of failure. Pretty easy stuff.

The success and failure callback methods have the exact same signature as the success/failure callback methods used with the DataService’s query method as seen in part 6. The operation parameter will always equal “insert”.

Now you may be wondering what happened to the Id property. We didn’t specify it when we created the carrier JSON object above, but we know that the data service was going to generate one for us. In the previous article we saw that the WebDataContext class would actually refresh any properties on entity instances it modified when it submitted changes (as long as its MergeOption was set correctly). That way any generated identity values would be present after the call to SaveChanges. DataService offers the same behavior. After you call its insert method, it will not only refresh, but create any properties that were omitted but affected as a result of the insertion (i.e. the Id property of our carrier instance). This means that if I modified our success callback like so:

function onSuccess(result, context, operation)
{
    alert(result.Id);
}

I would get an alert message stating 7, or whatever the generated Id would be. As long as we create a valid JSON object, with the proper property names, the DataService will take care of the rest and fill in the gaps :) Now, this behavior is dependent upon the sixth parameter of the insert method being set to true, or being omitted (because the default value is true). If I modified the call to insert like the follow:

service.insert(carrier, "Carriers", onSuccess, onFailure, null, false);

The above onSuccess method would result in an error, because we told the DataService not to pass the entity object to the success callback. This provides the equivalent of the MergeOption property of the WebDataContext class.

One more point of interest is that the insert method returns the instance of Sys.Net.WebRequest that is used internally by the DataService to make the actual service request. For the most part, you probably won’t need to use the object manually, but it’s important to know it’s there, in case you do. Also note that the insert method is making an HTTP POST request to the data service, not an HTTP GET request, like the query method uses.

Updating

Once you have an entity instance, whether you’ve queried for it, or reconstructed it, you can modify its property values. If you want to persist those changes back to the data service, all you have to do is call the DataService’s update method.

service.update(carrier, "Carriers(2)", onSuccess, onFailure, context, true);

The update method takes the exact same six parameters as the insert method. There are five differences though:

  1. The second parameter isn’t the name of the entity set, but rather the URI of the exact resource you’re updating. This is why I’m specifying “Carriers(2)”, because that is the canonical URI of the carrier I’m updating.
  2. The resource URI isn’t required, which means you could call the update method, passing only the entity object you wish to update.
  3. The sixth parameter is false by default. This means that the DataService won’t pass a refreshed entity instance to your success callback, unless you specifically tell it to.
  4. The update method is creating an HTTP PUT request.
  5. The operation parameter passed to the success/failure callbacks will always equal “update”.

Deleting

To insert data, you call the DataService’s insert method. To update data, you call the DataService’s update method. That must mean if I want to delete data I can call the DataService’s delete method! There’s only one problem with that: delete is a reserved keyword in JavaScript, and therefore can’t be used as a method name. Does this mean that the ADO.NET team decided to omit the ability to delete data when working with a data service using the DataService class in JavaScript? Well that would have been ridiculous. Fortunately for us they weren’t too partial to naming the delete method “delete”, and just went ahead and called it “remove”.

service.remove(carrier, "Carriers(2)", onSuccess, onFailure, context);

The remove method takes five parameters, all of which are optional. Does that mean I can just call remove with absolutely no parameters, and the DataService be smart enough to know what data I actually wanted to delete? That would be pretty sweet wouldn’t it?

// Perform rediculous magic data deletion :D
service.remove();

Yeah, not so much. The two callbacks, and the context data are completely optional, but the first two parameters are exclusively optional. There are three possible scenarios for calling the remove method:

  1. Provide the instance of the entity object you want to delete and omit the resource URI.
  2. Provide the resource URI and omit the entity object instance.
  3. Provide the entity object instance and resource URI, which would be overkill, but perfectly acceptable.

If I already had a reference to the carrier I wanted to delete I could use the following:

service.remove(carrier, null, onSuccess);

If I didn’t have a reference to the carrier I wanted to delete, but I knew its resource URI, I could use the following:

service.remove(null, "Carriers(2)", onSuccess);

The awesome thing about the above approach is that you don’t have to make an extra service call to retrieve the entity object you want to delete, you can simply target it by URI, deleting it in one request. This is one thing that the DataService class does better than its WebDataContext counterpart. Using the later always requires a reference to the entity object instance you want to delete.

As you may have guessed, just like insert and update, the remove method returns the Sys.Net.WebRequest object used internally to make the HTTP DELETE request. Also note, the operation parameter passed to the success/failure callbacks will always equal “remove”.

Being able to perform data modification operations against a data service using the ASP.NET AJAX is extremely useful, but having a unit of work is essential in a lot of cases, and the above DataService method’s don’t satisfy that need. Luckily the DataService class does in fact support unit of work behavior for performing a series of data modification operations as a group. In the next article we will discuss action sequences.