Cleaner JSON from a WCF service with webHttp behavior


This post improves on an earlier post, Consuming WCF services using JQuery JSON. The JSON serialized by the WCF service in that post is wrapped inside a d property. In this post we modify the service to return cleaner JSON by using webHttp behavior, and WebInvokeAttribute class.

Self-hosted WCF service

The code example follows. Note that we have removed the WebGetAttribute class from the methods in the service contract interface, and added WebInvoke attribute to the methods in the service implementation.

using System;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace wcf
{
    [ServiceContract]
    interface IMyService
    {
        [OperationContract]
        void SetSomething(string something);

        [OperationContract]
        string GetSomething();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    class MyService : IMyService
    {
        string _something = String.Empty;

        #region IMyService Members

        [WebInvoke(Method = "GET",
                   ResponseFormat = WebMessageFormat.Json,
                   UriTemplate = "SetSomething?something={something}")]
        public void SetSomething(string something)
        {
            _something = something;
        }

        [WebInvoke(Method = "GET",
                   ResponseFormat = WebMessageFormat.Json,
                   UriTemplate = "GetSomething")]
        public string GetSomething()
        {
            return _something;
        }

        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(wcf.MyService)))
            {
                host.Open(); // end point specified in app config

                Console.WriteLine("Hit Enter to quit.");
                Console.ReadLine();
            }
        }
    }
}

app.config

The modified app.config follows. Note that the behavior is now webHttp instead of enableWebScript.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="wcf.MyService">
        <endpoint address="http://localhost:8003/myservice"
          binding="webHttpBinding"
          contract="wcf.IMyService"
          behaviorConfiguration="webHttp"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

jQuery test app

The code follows. Only difference being, we don’t access the d property to read value returned by the service. We can send parameters in the URI instead of query string, now that we use UriTemplate.

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script type="text/javascript"
      src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js">
    </script>
    <script type="text/javascript">
        var url = 'http://localhost:8003/myservice/';
        $(document).ready(function () {
            $("#set").click(function () {
                var urlSet = url + 'SetSomething?something='
                    + $("#text").val();
                $.getJSON(urlSet, function (data) {
                    // nothing to do
                });
            });

            $("#get").click(function () {
                var urlGet = url + 'GetSomething';
                $.getJSON(urlGet, function (data) {
                    $('#text').val(data);
                });
            });
        });
    </script>
  </head>
  <body>
    <p>Test MyService</p>
    <form action="">
      <input id="text" type="text" value="Hello" />
      <input id="set" type="button" value="Set"/>
      <input id="get" type="button" value="Get" />
    </form>
  </body>
</html>

Support cross-origin requests

Cross-origin (CORS) requests are easily supported by adding a custom behavior as documented here.

Advertisements

User-Centered Design by Travis Lowdermilk; O’Reilly Media


User-Centered Design

By a developer for developers, the book is short, succinct, and can be read in a few short bouts of reading. Experienced developers will find that several user-centered design (UCD) practices have clearly been borrowed from, or absorbed into, classic software engineering practices.

Remainder of this review discusses the contents of each chapter.

Chapter 1 starts with “On January 9, 2007, a man quietly walked onto a stage and changed the course of technological history.” That had me hooked.

Chapter 2 explains Usability, Human Computer Interaction (human factors), UCD, user experience, and how they relate to each other. It then goes on to explain UCD by describing what it isn’t.

Chapter 3 is about working with users, knowing who your users are, understanding the different kinds of users, knowing when to listen to them, and when not to listen too literally.

Chapter 4 describes how to define a plan for your project. It starts with crafting a team mission statement. Project details are defined next with a title, description, stakeholders, and impact assessment. Importance of collecting user requirements without thinking about solutions follows next. That is followed by a discussion on collecting functional requirements, and how the application will solve the user requirements. The chapter proceeds with capturing data and workflow modeling, and ends with prototyping. Prototyping is also explained in greater detail in Chapter 8. Appendix A has a nice sample project template.

Chapter 5 starts with the importance of defining a manifesto or vision statement for an application. That is followed by a discussion on exercising restraint when adding features. The chapter delves into narrative, personas and scenarios, and their usage in the UCD process to refine the vision.

Chapter 6 delves into the need for creativity, and why it takes courage and hard work to exercise it. It discusses several ways for enhancing creativity, including studying how others do their work.

Chapter 7 delves into the study of design principles and their importance to UCD. It discusses the Principle of Proximity (Gestalt Principle), Visibility, Hierarchy, Mental Models and Metaphors, Progressive Disclosure, Consistency, Affordance and Constraints, Confirmation, Reaction Time (Hick’s law), and Movement Time (Fitt’s law).

Chapter 8 delves into gathering feedback for a new application using surveys, informal interviews, formal interviews, contextual inquiry, task analysis, heuristic evaluation, and A/B testing. Story boarding and prototyping as a means of visualizing the new application are also discussed in detail.

Chapter 9 discusses usability studies of existing applications as a means of gaining feedback. It details procedures and tools that may be used.

Every developer should read this book and absorb the practices described here, especially older developers who have been hearing about UCD but are not aware of its practices.

winusbnet patch to handle language id


winusbnet throws an exception when reading string descriptors using the WinUsb_GetDescriptor call. Basically, that WinUsb call returns false as it is called with a Language ID of 0, a reserved value.

Patch GetStringDescriptor in WinUSBDevice.cs

The GetStringDescriptor method does not accept a language ID, so we need to patch it to fix that. That change is reproduced below.

public string GetStringDescriptor(byte index, ushort languageID)
{
    byte[] buffer = new byte[256];
    uint transfered;
    bool success = WinUsb_GetDescriptor(_winUsbHandle, USB_STRING_DESCRIPTOR_TYPE,
                index, languageID, buffer, (uint)buffer.Length, out transfered);
    if (!success)
        throw APIException.Win32("Failed to get USB string descriptor ("  + index + ").");
           
    int length = buffer[0] - 2;
    if (length <= 0)
        return null;
    char[] chars = System.Text.Encoding.Unicode.GetChars(buffer, 2, length);
    return new string(chars);
}

Patch GetDeviceDescriptor in USBDevice.cs

Tha patched GetDeviceDescriptor queries the available languages by calling GetStringDescriptor with an index of 0. It then uses the first language ID to recover other string descriptors.

private static USBDeviceDescriptor GetDeviceDescriptor(string devicePath)
{
    try
    {
        USBDeviceDescriptor descriptor;
        using (API.WinUSBDevice wuDevice = new API.WinUSBDevice())
        {
            wuDevice.OpenDevice(devicePath);
            API.USB_DEVICE_DESCRIPTOR deviceDesc = wuDevice.GetDeviceDescriptor();
            string q = wuDevice.GetStringDescriptor(0, 0);
            if (q.Length == 0)
                throw new USBException("Failed to get USB string descriptor (0).");
            // TODO: Using the first language id. Need to improve API.
            ushort langID = q[0];
            string manufacturer = null, product = null, serialNumber = null;
            byte idx = 0;
            idx = deviceDesc.iManufacturer;
            if (idx > 0)
                manufacturer = wuDevice.GetStringDescriptor(idx, langID);

            idx = deviceDesc.iProduct;
            if (idx > 0)
                product = wuDevice.GetStringDescriptor(idx, langID);

            idx = deviceDesc.iSerialNumber;
            if (idx > 0)
                serialNumber = wuDevice.GetStringDescriptor(idx, langID);
            descriptor = new USBDeviceDescriptor(devicePath, deviceDesc, manufacturer, product, serialNumber);
        }
        return descriptor;

    }
    catch (API.APIException e)
    {
        throw new USBException("Failed to retrieve device descriptor.", e);
    }
}

Patch can now be obtained from GitHub.

Office 365 Home Premium a tremendous success?


Let me start with a story. At the end of last year Walmart.com.br kicked off its Black Friday deals. I went through the discounted products and found a gem. Office Home & Student 2010, priced at 45 Brazilian Reais (BRL) instead of its regular 199 BRL price tag, valid for three PCs. It also came with an offer to upgrade to the next version, whose launch was right around the corner. To get that free upgrade I had to register my e-mail at http://office.microsoft.com/en-us/offer/.

Microsoft launched Office 2013 as a subscription service called Office 365 Home Premium and also a normally priced Office Home and Student 2013. The offer I signed up for came with a raw deal. I could either update to the subscription version and still keep using the earlier version, or upgrade to the non-subscription version valid for only one PC and never go back. Guess which I chose? It was a no brainer to go with the subscription version. So now when I read that Office 365 is a tremendous success, I silently wonder if that success isn’t based on coercing users to upgrade to a version of Office they wouldn’t have chosen.

Office 365 has now arrived on the iPhone. I do own all the apps in the iWork suite, so I won’t probably use it to create content. Viewing content created by others is a different matter. No Office substitute I have used on iOS provides seamless compatibility. I am hoping Office 365 will be different. Will I renew my Office 365 subscription next year? That’s a $99 question I’ll need to answer as and when it arises. At $29 a year, I might consider it a strong possibility.

Problem of Windows 8 is its positioning


I have said this before, I love Windows 8, but I spend most of my day on the desktop. I just don’t have enough reason to adopt Windows 8 apps, yet. I have been using certain apps, just not that often.

For users that live on the desktop, switching back and forth between the Start screen and the desktop is cumbersome. All that will change with Windows 8.1, hopefully. Users who don’t have a hybrid laptop or PC will then return to using the desktop as they have always done. Users with hybrid laptops will use Windows 8 apps more often while they lay back and enjoy a book, game, movie, or do something else more productive.

Windows 8 tried to force a touch and gesture interface on existing laptops and PCs that just don’t benefit from it. It should be easy to switch to that interface on touch enabled hybrid laptops and devices though. Maybe the device can detect when it is in “tablet mode” and switch to the Start screen. Just a thought…

WWDC 2013


WWDC 2013 has been mostly about software, although I am salivating at the idea of owning the new MacBook Air and Mac Pro, with the fourth generation processors from Intel. Here’s what I found interesting in the Keynote.

iOS 7

What a refreshing change iOS 7 will be. Suddenly things are at your fingertips, easy to turn on/off Wi-Fi and Bluetooth, notification center in the lock screen… I could go on and on. I like the fact that all apps can now be in the background. Game controller support takes iOS devices into the game console realm.

It must have been incredibly hard to redesign and engineer iOS 7 in such a compressed schedule. I have defended Skeuomorphism in the past as a way for Apple to sell a lifestyle. I am now wondering whether the physical stores will change to reflect the iOS 7 experience.

iWork in iCloud

The demo of iWork in iCloud, working across different browsers, was phenomenal. Apple has finally shown that it can deliver incredible apps in the browser. What a surprise that must have been for Google and Microsoft. Will Maps be next?

Safari

Safari in OS X Mavericks and iOS now syncs your passwords and other sensitive information to iCloud. That is the only reason I use Chrome on iOS. The splendid news is that performance of the Nitro JavaScript engine of Safari is superior, the memory footprint lower.

iTunes Radio

I haven’t purchased much digital music, nor do I like to spend time organizing what music I do have. I like radios because you get to discover new music, old or contemporary. So what if I have to listen to or view ads. I think iTunes Radio will fill a useful void, as and when it arrives in Brazil.

What next?

I am impressed with OS X Mavericks, but don’t own a Mac. I’d rather not get too eager lest I feel obliged to part with some hard earned money. Making something that changes the game is what I have come to expect from Apple. I am still waiting…

Will threads become a relic?


Newer concurrency APIs have hidden the concept of threads. They instead expose task parallelism by applying the thread pool pattern, making migration from thread pools to other means of task parallelism easier. Some implementations expose asynchronous calls, doing away with the need to even create tasks. If the process has a single thread of execution, as in the case of Node.js, you don’t have to bother with locks. Scaling is achieved using multiple processes and shared data.

Evidence of this change can be seen in several popular programming APIs:

  • Concurrency Utilities in Java
  • Parallel Extensions for .NET framework, and C# async and await
  • Grand Central Dispatch in OS X and iOS 4

Hopefully in the future we’ll see tasks magically dispatched to dedicated co-processors such as Epiphany and the GPU.

All that leads me to conclude that threads will become a relic in most programming languages.