Welcome!

Blog Feed Post

Using complex types to make calling services less… complex

So far, my examples of using jQuery to interact with ASP.NET AJAX services have avoided passing complex data to the server during the request. This has been intentional, because I didn’t want to over-complicate the examples.

For primarily read-only scenarios, like the RSS reader examples, passing just a few simple values to the service is often all you need. However, this scalar approach quickly becomes untenable when making real-world service calls.

In this post, I’m going to show you how passing complex types to the server helps alleviate complexity, how json2.js and a data transfer object (DTO) facilitates this, and how to use jQuery to very easily build the DTO.

Setting the stage

Let’s say that we want to improve the performance of a data entry application used to add Person records to a database. The original version was developed quickly using an UpdatePanel, but performs poorly. Not wanting the Person-data-entry-department to spend more time waiting than they do typing, we must find a way to improve the application’s performance.

Having done some research, we might decide that replacing the UpdatePanel with jQuery and a web service would be a great way to speed things up.

A foundation and a facade

The properties of the existing Person class could be as simple as this:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
 
  public void Add()
  {
    // Magic happens here.
  }
}

The original entry form probably used TextBox controls, but that will no longer be necessary. Regular HTML input elements carry less overhead and ensure that we don’t have to worry about ClientID issues:

<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" />
 
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" />
 
<label for="Address">Address:</label>
<input type="text" id="Address" />
 
<label for="City">City:</label>
<input type="text" id="City" />
 
<label for="State">State:</label>
<input type="text" id="State" />
 
<label for="Zip">Zip:</label>
<input type="text" id="Zip" />
 
<input type="button" id="Save" value="Save" />

Note that the input elements have IDs matching the corresponding Person property. This will help us implement an improvement to our client-side code later on.

One way not to do it

Now that we’ve had a look at the front and back ends, it’s time to connect them together with a web service. One unfortunate anti-pattern that often emerges in this situation is a service method with too many parameters:

[WebMethod]
public void AddPerson(string FirstName, string LastName, 
                      string Address, string City,
                      string State, string Zip)
{
  Person newPerson = new Person();
 
  newPerson.FirstName = FirstName;
  newPerson.LastName = LastName;
  newPerson.Address = Address;
  newPerson.City = City;
  newPerson.State = State;
  newPerson.Zip = Zip;
 
  newPerson.Add();
}

Not only do we have to manually keep that method’s parameter list in sync with the Person class, but we also have to maintain the pointless object initialization code.

Calling the service on the client-side is just as messy too:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'FirstName':'" + $("#FirstName").val() + "', "
       + "'LastName':'" + $("#LastName").val() + "',"
       + "'Address':'" + $("#Address").val() + "',"
       + "'City':'" + $("#City").val() + "',"
       + "'State':'" + $("#State").val() + "',"
       + "'Zip':'" + $("#Zip").val() + "'}",
  dataType: "json"
});

As ugly as it is, that will work and be much faster than anything we could possibly implement in an UpdatePanel. It would also be a nightmare to maintain.

Let’s continue improving this until it’s something we can be proud of.

Things can only get better

A good first improvement is to refactor the web service to get rid of the parameter list and redundant object initialization.

Most examples (including my own) never go beyond passing a string, integer, or maybe an array, but that only scratches the surface of what’s possible. An underutilized feature of ASP.NET AJAX “ScriptService” methods is that they can accept complex types as parameters and parse those parameters from JSON.

Leveraging this, we can dramatically simplify the web service:

[WebMethod]
public void AddPerson(Person NewPerson)
{
  NewPerson.Add();
}

Unfortunately, calling this method on the client-side is just as messy as ever:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson': {'FirstName':'" + $("#FirstName").val() + "',"
                     + "'LastName':'" + $("#LastName").val() + "',"
                     + "'Address':'" + $("#Address").val() + "',"
                     + "'City':'" + $("#City").val() + "',"
                     + "'State':'" + $("#State").val() + "',"
                     + "'Zip':'" + $("#Zip").val() + "'}}",
  dataType: "json"
});

That’s about the same as before. However, instead of sending a flat group of input field values, now we’re sending a JSON object corresponding to the Person class.

In other words, that declarative JSON data string is equivalent to this JavaScript:

var NewPerson = new Object();
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();

ASP.NET AJAX seamlessly translates the JSON string into a new instance of our Person class and passes that object into the service method. It works exactly as you’d expect, which is almost too good to be true!

Cleaning up the client-side

The best way to improve the client-side situation is to abandon our manual JSON serialization in the $.ajax() call. It works well enough for a couple parameters, but has devolved into a ball of mud as the parameter count increased.

Douglas Crockford’s json2.js contains a stringify function which is exactly what we need. Stringify() accepts a JSON object and returns the same type of string that we’re manually concatenating together right now.

Using json2.js, our previous client-side code can be refactored to this:

// Initialize the object, before adding data to it.
var NewPerson = new Object();
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson':" + JSON.stringify(NewPerson) + "}",
  dataType: "json"
});

It’s still a fair amount of code, but it’s much cleaner. If you dropped this in my lap and asked me to maintain it, we wouldn’t have a problem.

Using a data transfer object

Adding json2.js and its stringify functionality made our code significantly more readable, but we can do better. There’s still a bit of manual JSON string building in the $.ajax() call, which would be nice to avoid.

Since we already have JSON.stringify() at our disposal, we can build and stringify a JSON object to represent the entire request’s data instead of just the form data:

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var NewPerson = { };
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
 
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: JSON.stringify(DTO),
  dataType: "json"
});

By creating a data transfer object (often referred to as a DTO), we’ve completely eliminated all manual JSON string building.

Even though it’s a small change, it feels quite a bit cleaner doesn’t it?

Bonus: jQuery makes everything better

Using the DTO makes sending the form data clean, but we’re still stuck with the unnecessary chore of maintaining the NewPerson initialization block. jQuery is perfectly suited to solving this problem:

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var NewPerson = { };
 
// Iterate over all the text fields and build an
//  object with their values as named properties.
$(':text').each(function() {
  // Ex: NewPerson['FirstName'] = $('#FirstName').val();
  NewPerson[this.id] = this.value;
});
 
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: JSON.stringify(DTO),
  dataType: "json"
});

Using jQuery.each() to iterate over the fields and build our client-side object is a nice improvement. Even in this simple example, it cuts down on the amount of JavaScript we have to write and maintain. In real-world scenarios where your objects have dozens of properties, this will save you a lot of time (and typos).

More important than saving a few keystrokes, we’ve got one less place to worry about updating if the Person class changes in the future. We can modify the Person class, update the entry form accordingly, and this will continue working.

Conclusion

We have solidly accomplished the goal of refactoring this until it’s something we can be proud of. There’s always room for improvement, but this will serve as a great start for writing robust, maintainable client-side service calls.

Death by a thousand dependencies: When I first started experimenting with this stringified DTO pattern, I was reluctant to take on the json2.js dependency. However, it’s tiny when minified, has no dependencies of its own, and is ideal for rolling into another combined script. Its dependable functionality is well worth a few kilobytes.

A great thing about committing to the JSON.stringify usage is that web browsers are beginning to natively support it. So, at some point in the future, you’ll actually be able to drop the json2.js dependency and this method will still work (faster).

DTOs: If your server-side situation is more complex than this example (and it probably is), don’t be afraid to use a throw-away DTO class as the service method parameter.

For example, our Person class could also have been a PersonDTO class, specifically intended to take these form submissions and merge them into a more complicated domain.

Source

jQuery DTO source download

###

Originally posted at Encosia. If you're reading this elsewhere, come on over and see the original.

Using complex types to make calling services less… complex

Read the original blog entry...

More Stories By Dave Ward

Dave Ward wrote his first computer program in 1981, using good ‘ol Microsoft Color BASIC and cassette tapes for data storage. Over the years since then, he has had the opportunity to work on projects ranging from simple DOS applications to global telecommunications networks spanning multiple platforms.

Latest Stories
"We are an IT services solution provider and we sell software to support those solutions. Our focus and key areas are around security, enterprise monitoring, and continuous delivery optimization," noted John Balsavage, President of A&I Solutions, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"DivvyCloud as a company set out to help customers automate solutions to the most common cloud problems," noted Jeremy Snyder, VP of Business Development at DivvyCloud, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We want to show that our solution is far less expensive with a much better total cost of ownership so we announced several key features. One is called geo-distributed erasure coding, another is support for KVM and we introduced a new capability called Multi-Part," explained Tim Desai, Senior Product Marketing Manager at Hitachi Data Systems, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
There is a huge demand for responsive, real-time mobile and web experiences, but current architectural patterns do not easily accommodate applications that respond to events in real time. Common solutions using message queues or HTTP long-polling quickly lead to resiliency, scalability and development velocity challenges. In his session at 21st Cloud Expo, Ryland Degnan, a Senior Software Engineer on the Netflix Edge Platform team, will discuss how by leveraging a reactive stream-based protocol,...
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
DevOps at Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to w...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"With Digital Experience Monitoring what used to be a simple visit to a web page has exploded into app on phones, data from social media feeds, competitive benchmarking - these are all components that are only available because of some type of digital asset," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Kubernetes is an open source system for automating deployment, scaling, and management of containerized applications. Kubernetes was originally built by Google, leveraging years of experience with managing container workloads, and is now a Cloud Native Compute Foundation (CNCF) project. Kubernetes has been widely adopted by the community, supported on all major public and private cloud providers, and is gaining rapid adoption in enterprises. However, Kubernetes may seem intimidating and complex ...
"Outscale was founded in 2010, is based in France, is a strategic partner to Dassault Systémes and has done quite a bit of work with divisions of Dassault," explained Jackie Funk, Digital Marketing exec at Outscale, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.