{"id":290,"date":"2011-09-30T12:28:53","date_gmt":"2011-09-30T12:28:53","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/09\/30\/creating-net-web-services-for-firefox-ie-chrome-and-safari\/"},"modified":"2016-11-22T14:11:46","modified_gmt":"2016-11-22T19:11:46","slug":"creating-net-web-services-for-firefox-ie-chrome-and-safari","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/09\/30\/creating-net-web-services-for-firefox-ie-chrome-and-safari\/","title":{"rendered":"Creating .NET Web Services for Firefox, IE, Chrome and Safari"},"content":{"rendered":"<div class=\"content\">\r\n\r\nGuest blogger <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660\">Peter Webb<\/a> returns with another in an <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/\">occasional series<\/a> of postings about application deployment.\r\n\r\n&nbsp;\r\n<h3>Contents<\/h3>\r\n<div>\r\n<ul>\r\n \t<li><a href=\"#1\">Calling .NET Web Services from JavaScript<\/a><\/li>\r\n \t<li><a href=\"#2\">Exchanging Data with JavaScript Object Notation<\/a><\/li>\r\n \t<li><a href=\"#3\">Hosting the Service<\/a><\/li>\r\n \t<li><a href=\"#4\">A JavaScript Client<\/a><\/li>\r\n \t<li><a href=\"#5\">Building and Running the Example<\/a><\/li>\r\n \t<li><a href=\"#6\">Doing the Right Kind of Work<\/a><\/li>\r\n<\/ul>\r\n<\/div>\r\n<h3>Calling .NET Web Services from JavaScript<a name=\"1\"><\/a><\/h3>\r\nOur story so far: I've deployed a MATLAB-based .NET web service using <a href=\"https:\/\/www.mathworks.com\/products\/netbuilder\">Builder NE<\/a> and the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/netframework\/aa663324\">Windows Communcation Foundation<\/a> (WCF), and I've written a .NET client program that lets my users access that service. What happens when someone using a Mac\r\nor a Linux box asks for access? They can't run the Windows client -- but if they've got a web browser, I can provide them\r\na client built with HTML and a quirky little language called <a href=\"http:\/\/en.wikipedia.org\/wiki\/JavaScript\">JavaScript<\/a>.\r\n\r\nI'll demonstrate how to build a platform-independent web service client by extending a WCF-enabled deployed MATLAB component\r\nto support calls from JavaScript. My application has three parts:\r\n<div>\r\n<ol>\r\n \t<li>A deployed MATLAB component implementing a WCF-enabled type safe API.<\/li>\r\n \t<li>A WCF server publishing the type safe API via a service contract.<\/li>\r\n \t<li>A JavaScript client that requests service operations from the server.<\/li>\r\n<\/ol>\r\n<\/div>\r\nThe server requires WCF and must run under Windows, but the client can run in any browser that supports JavaScript and <a href=\"http:\/\/en.wikipedia.org\/wiki\/HTML5\">HTML 5<\/a> (and nowadays that's most of them -- except, ironically, IE).\r\n\r\nTwo words of warning here: first, this post builds on the <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/\">others<\/a> in the type safe API series, so you'd be well-served to read them first (at the very least, read the <a href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/06\/03\/introducing-type-safe-apis-with-builder-ne\/\">initial WCF post<\/a>); and second, the complexity of client server applications makes it impossible to fully describe how they work in this (relatively)\r\nshort article. I've included links for most of the jargon, I hope -- click on them if there's something you don't understand.\r\nThat being said, I do encourage you to keep reading. You can likely download and build the application without understanding\r\nall the theory behind it.\r\n<h3>Exchanging Data with JavaScript Object Notation<a name=\"2\"><\/a><\/h3>\r\nFor the client and server to successfully communicate, they must agree on a data format. The defacto standard data format\r\nfor JavaScript clients, <a href=\"http:\/\/www.json.org\/\">JavaScript Object Notation<\/a> (JSON), represents all types of data with strings of JavaScript code, sacrificing storage efficiency for readabilty and ease\r\nof use. Essentially, the server sends little program fragments to the client, which executes them to recreate the data objects.\r\nSince the client and server trust each other implicitly in this case, transmitting executable code creates no <a href=\"http:\/\/en.wikipedia.org\/wiki\/Eval#JavaScript\">security risks<\/a>.\r\n\r\nIn a <a href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/08\/17\/builder-ne-and-the-windows-communication-foundation\/\">previous post<\/a>, I developed a WCF service that publishes an <tt>IFractal<\/tt> <tt>ServiceContract<\/tt> with a single operation, <tt>snowflake<\/tt>. Here, I extend <tt>IFractal<\/tt> to support JSON output by making two changes. First, I add the <tt>[WebGet]<\/tt> attribute, specifying the output format <tt>WebMessageFormat.Json<\/tt>:\r\n<pre>[ServiceContract]\r\npublic interface IFractal\r\n{\r\n    [OperationContract(Name = \"snowflake\")]\r\n    [WebGet(ResponseFormat = WebMessageFormat.Json,\r\n            UriTemplate = \"\/?n={n}&amp;width={width}&amp;height={height}\")]\r\n    FractalOutline snowflake(int n, int width, int height);\r\n}<\/pre>\r\n<tt>UriTemplate<\/tt> defines a pattern determining how to map named web request parameters to <tt>snowflake<\/tt>'s inputs.\r\n\r\nThe original <tt>snowflake<\/tt> returns two values: the first in the function's return value and the second via a C# <tt>out<\/tt> parameter. But my client invokes the service through JavaScript's <a href=\"http:\/\/en.wikipedia.org\/wiki\/XMLHttpRequest\"><tt>XMLHttpRequest<\/tt><\/a> API, which only permits a single return value. Hence, the second change: returning the two pieces of data in a single structure.\r\nTo enable WCF to automatically marshall the sructure, I decorate the return type, <tt>FractalOutline<\/tt>, with the <tt>[DataContract]<\/tt> attribute, and each of its fields with <tt>[DataMember]<\/tt>.\r\n<pre>[DataContract]\r\npublic struct FractalOutline\r\n{\r\n    [DataMember]\r\n    public int[][] vectors;\r\n    [DataMember]\r\n    public int[] bbox;\r\n}<\/pre>\r\nWith these changes, the service will send a block of JSON code in response to HTTP requests.\r\n<h3>Hosting the Service<a name=\"3\"><\/a><\/h3>\r\nI <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms730158%28v=VS.90%29.aspx\">host<\/a> the <tt>KochJSON<\/tt> service in a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms731758%28v=VS.90%29.aspx\">Windows console application<\/a>, configuring its <tt>HttpBinding<\/tt> endpoint to publish the <tt>IFractal<\/tt> contract using the <tt>webHttpBinding<\/tt> protocol. A <tt>webHttpBinding<\/tt> endpoint listens for requests that use XML rather than the more complex SOAP, greatly simplifying the client code. I add\r\nthe new endpoint to the application's configuration file, <tt>App.config<\/tt>:\r\n<pre>&lt;endpoint\r\n       address=\"\"\r\n       binding=\"webHttpBinding\"\r\n       bindingConfiguration=\"webHttpConfig\"\r\n       contract=\"IFractal\"\r\n       name=\"HttpBinding\" \/&gt;<\/pre>\r\nClients making an <tt>XMLHttpRequest<\/tt> require an <tt>webHttpBinding<\/tt> endpoint.\r\n<h3>A JavaScript Client<a name=\"4\"><\/a><\/h3>\r\nMy client performs two tasks: requesting the outline of the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Koch_snowflake\">Koch snowflake<\/a> from the <tt>KochJSON<\/tt> web service and then drawing the snowflake in the browser window. <tt>IFractal<\/tt>'s <tt>[WebGet]<\/tt> attribute defines the format of the URL serving the snowflake data. To retrieve the 4th iteration of the Koch snowflake,\r\nscaled to fit within a 300x300 rectangle, make the following request:\r\n<pre>http:\/\/localhost:42017\/KochJSON\/?n=4&amp;width=300&amp;hieght=300<\/pre>\r\nI've configured the service host to listen for client requests on port <tt>42017<\/tt> on my local machine. The string of parameters following the service name match the pattern specified by the <tt>UriTemplate<\/tt> I defined in the <tt>[WebGet]<\/tt> attribute of the <tt>IFractal<\/tt> <tt>[ServiceContract]<\/tt>. The parameter <tt>n<\/tt> here maps to <tt>snowflake<\/tt>'s input <tt>n<\/tt>, and so on, and the service calls <tt>snowflake(4, 300, 300)<\/tt>.\r\n\r\nMaking this request in JavaScript requires an <tt>XMLHttpRequest<\/tt> object, which you create with <tt>new<\/tt>:\r\n<pre>var request = new XMLHttpRequest();<\/pre>\r\nCall <tt>open<\/tt> to initialize the request with the HTTP method (<tt>GET<\/tt>), the HTTP address of the service, and <tt>true<\/tt> to specify the request should be made asynchronously. Then call <tt>send<\/tt> to make the request.\r\n<pre>request.open(\"GET\",\r\n   \"http:\/\/localhost:42017\/KochJSON\/?n=4&amp;width=300&amp;height=300\",\r\n   true)\r\nrequest.send(null);<\/pre>\r\nThe <tt>XMLHttpRequest<\/tt> object notifies me when the asynchronous request completes by invoking a callback function I provide. I convert the response\r\ndata from its JSON text notation into a live JavaScript object by invoking <tt>eval<\/tt>:\r\n<pre>var jsonOutline = eval( '(' + request.responseText + ')' );<\/pre>\r\nMy <tt>[DataContract]<\/tt> structure, <tt>FractalOutline<\/tt>, contains two fields, <tt>vectors<\/tt> and <tt>bbox<\/tt>. Since JSON data marshalling preserves field names, I retrieve the data from <tt>jsonOutline<\/tt> by referencing its <tt>vectors<\/tt> and <tt>bbox<\/tt> fields.\r\n<pre>var outline = jsonOutline.vectors;\r\nvar bbox = jsonOutline.bbox;<\/pre>\r\n<tt>vectors<\/tt> and <tt>bbox<\/tt> are native JavaScript arrays, so I manipulate them using native JavaScript syntax. I draw the outline with a for-loop, at\r\neach step calling the HTML 5 <a href=\"http:\/\/en.wikipedia.org\/wiki\/Canvas_element\"><tt>canvas<\/tt><\/a> function <tt>lineTo<\/tt>:\r\n<pre>x = x + outline[i][0];\r\ny = y + outline[i][1];\r\ncontext.lineTo(x, y);<\/pre>\r\nThere's a bit more code in the callback to manage errors and ensure that it doesn't start drawing until the entire outline\r\nis available, but it can't be more than ten lines or so. One line for data marshalling (the <tt>eval<\/tt> statement), a few lines to make and manage the request, but the bulk of the code I had to write myself focuses on solving\r\nthe problem at hand, drawing the outline.\r\n<h3>Building and Running the Example<a name=\"5\"><\/a><\/h3>\r\n<a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/31295-creating-builder-ne-web-services-for-firefox--ie--chrome-and-safari\">Download the code<\/a> from MATLAB Central.\r\n\r\nThe download contains the <a href=\"https:\/\/www.mathworks.com\/products\/matlab\/\">MATLAB<\/a> function <tt>snowflake.m<\/tt>, a Visual Studio 2008 solution <tt>KochJSON.sln<\/tt> and an HTML page, <tt>KochSnowflake.html<\/tt>, defining the JavaScript client. Create the server program by following these three steps:\r\n<div>\r\n<ol>\r\n \t<li>Build the <tt>IFractal<\/tt> interface DLL.<\/li>\r\n \t<li>Create the <tt>Snowflake<\/tt> .NET assembly and the <tt>KochIFractal<\/tt> type safe interface.<\/li>\r\n \t<li>Compile the server program, <tt>KochJSON<\/tt>, after referencing <tt>IFractal<\/tt> and <tt>KochIFractal<\/tt> in the <tt>KochJSON<\/tt> project.<\/li>\r\n<\/ol>\r\n<\/div>\r\nThe client does not require compilation.\r\n\r\nThe file <tt>ReadmeWCFJSON.txt<\/tt> contains detailed instructions.\r\n\r\nTo run the example, open a DOS window for the server. Make sure the DOS window's runtime environment supports the execution\r\nof deployed MATLAB .NET components (you'll need the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f12-999353.html\">MCR<\/a> on your <tt>PATH<\/tt>), then run <tt>KochJSON\\KochJSON\\bin\\Debug\\KochJSON.exe<\/tt>. When the server is ready, it prints a short message:\r\n<pre>Koch JSON Snowflake Service started.\r\nPress any key to terminate service...<\/pre>\r\nActivate the client by double-clicking on <tt>KochSnowflake.html<\/tt>. The first client to contact the server causes the server to load the MCR, which takes some time. However, subsequent requests\r\nprocess very rapidly. The server supports multiple clients -- try connecting from different architectures, using different\r\nbrowsers. HTML 5-capable browsers should display something like this:\r\n\r\n<img decoding=\"async\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/290\/Snowflake.png\" hspace=\"5\" vspace=\"5\" \/>\r\n<h3>Doing the Right Kind of Work<a name=\"6\"><\/a><\/h3>\r\nRetrieving the data and drawing the outline are <i>domain<\/i> tasks, central to the work I want to get done. Anything else, bookkeeping, data marshalling, managing the client server connection,\r\nis a distraction, an artifact created by the technologies I've chosen to implement my solution. Ideally, I'd like those technologies\r\nto manage themselves -- I'd like to concentrate on writing the code that solves the problem. And that's what deployed type\r\nsafe APIs let me do -- with a native C# interface for my MATLAB functions, I can take advantage of .NET automation and application\r\nmanagement tools that were previously inaccessible.\r\n\r\nThis JavaScript client required more effort than a WCF client generated by Visual Studio, but it is lighter weight and much\r\nmore widely usable. Does that matter to you? Will you write cross-platform clients like this one? How important is standards\r\ncompliance to your applications? <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=290#respond\">Let us know<\/a> what you think.\r\n\r\n<script>\/\/ <![CDATA[\r\nfunction grabCode_4ca699be68ee433f988589d6a3089a79() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='4ca699be68ee433f988589d6a3089a79 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 4ca699be68ee433f988589d6a3089a79';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Peter Webb';\r\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('\r\n\r\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\r\n\r\n\r\n\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }\r\n\/\/ ]]><\/script>\r\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\">\r\n<a><span style=\"font-size: x-small; font-style: italic;\">Get\r\nthe MATLAB code\r\n<noscript>(requires JavaScript)<\/noscript><\/span><\/a>\r\n\r\nPublished with MATLAB\u00ae 7.13<\/p>\r\n\r\n<\/div>\r\n<!--\r\n4ca699be68ee433f988589d6a3089a79 ##### SOURCE BEGIN #####\r\n%% Creating .NET Web Services for Firefox, IE, Chrome and Safari\r\n% Guest blogger\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660 % Peter Webb> returns with another in an\r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/ occasional % series> of postings about application deployment.\r\n\r\n%% Calling .NET Web Services from JavaScript\r\n% Our story so far: I've deployed a MATLAB-based .NET web service using\r\n% <https:\/\/www.mathworks.com\/products\/netbuilder Builder NE> and the\r\n% <http:\/\/msdn.microsoft.com\/en-us\/netframework\/aa663324 Windows % Communcation Foundation> (WCF), and I've written a .NET client\r\n% program that lets my users access that service. What happens when someone\r\n% using a Mac or a Linux box asks for access? They can't run the Windows\r\n% client REPLACE_WITH_DASH_DASH but if they've got a web browser, I can provide them a client\r\n% built with HTML and a quirky little language called\r\n% <http:\/\/en.wikipedia.org\/wiki\/JavaScript JavaScript>.\r\n%\r\n% I'll demonstrate how to build a platform-independent web service client\r\n% by extending a WCF-enabled deployed MATLAB component to support calls from\r\n% JavaScript. My application has three parts:\r\n%\r\n% # A deployed MATLAB component implementing a WCF-enabled type safe API.\r\n% # A WCF server publishing the type safe API via a service contract.\r\n% # A JavaScript client that requests service operations from the server.\r\n%\r\n% The server requires WCF and must run under Windows, but the client can\r\n% run in any browser that supports JavaScript and\r\n% <http:\/\/en.wikipedia.org\/wiki\/HTML5 HTML 5> (and nowadays\r\n% that's most of them REPLACE_WITH_DASH_DASH except, ironically, IE).\r\n%\r\n% Two words of warning here: first, this post builds on the\r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/ others> in the\r\n% type safe API series, so you'd be well-served to read them first (at the\r\n% very least, read the\r\n% <https:\/\/blogs.mathworks.com\/loren\/2011\/06\/03\/introducing-type-safe-apis-with-builder-ne\/ % initial WCF post>); and second, the complexity of\r\n% client server applications makes it impossible to fully describe how they\r\n% work in this (relatively) short article. I've included links for most of\r\n% the jargon, I hope REPLACE_WITH_DASH_DASH click on them if there's something you don't\r\n% understand. That being said, I do encourage you to keep reading.\r\n% You can likely download and build the\r\n% application without understanding all the theory behind it.\r\n\r\n%% Exchanging Data with JavaScript Object Notation\r\n% For the client and server to successfully communicate, they must\r\n% agree on a data format.\r\n% The defacto standard data format for JavaScript clients,\r\n% <http:\/\/www.json.org\/ JavaScript Object Notation>\r\n% (JSON), represents all types of data with strings of\r\n% JavaScript code, sacrificing storage efficiency for readabilty and\r\n% ease of use. Essentially, the server sends little program fragments to\r\n% the client, which executes them to recreate the data objects. Since the\r\n% client and server trust each other implicitly in this case, transmitting\r\n% executable code creates no <http:\/\/en.wikipedia.org\/wiki\/Eval#JavaScript % security risks>.\r\n%\r\n% In a\r\n% <https:\/\/blogs.mathworks.com\/loren\/2011\/08\/17\/builder-ne-and-the-windows-communication-foundation\/ % previous post>, I developed a WCF service that publishes an\r\n% |IFractal| |ServiceContract| with a single operation, |snowflake|. Here, I\r\n% extend |IFractal| to support JSON output by making two changes. First, I\r\n% add the |[WebGet]| attribute, specifying the output format\r\n% |WebMessageFormat.Json|:\r\n%\r\n%  [ServiceContract]\r\n%  public interface IFractal\r\n%  {\r\n%      [OperationContract(Name = \"snowflake\")]\r\n%      [WebGet(ResponseFormat = WebMessageFormat.Json,\r\n%              UriTemplate = \"\/?n={n}&width={width}&height={height}\")]\r\n%      FractalOutline snowflake(int n, int width, int height);\r\n%  }\r\n%\r\n% |UriTemplate| defines a pattern determining how\r\n% to map named web request parameters to |snowflake|'s inputs.\r\n%\r\n% The original |snowflake| returns two values: the first in\r\n% the function's return value and the second via\r\n% a C# |out| parameter. But my client invokes the service\r\n% through JavaScript's\r\n% <http:\/\/en.wikipedia.org\/wiki\/XMLHttpRequest |XMLHttpRequest|>\r\n% API, which only permits a single\r\n% return value. Hence, the second change: returning the two pieces of\r\n% data in a single structure. To enable WCF to automatically marshall the\r\n% sructure, I decorate the return type, |FractalOutline|, with the\r\n% |[DataContract]| attribute, and each of its fields with |[DataMember]|.\r\n%\r\n%  [DataContract]\r\n%  public struct FractalOutline\r\n%  {\r\n%      [DataMember]\r\n%      public int[][] vectors;\r\n%      [DataMember]\r\n%      public int[] bbox;\r\n%  }\r\n%\r\n% With these changes, the service will send a block of JSON code in\r\n% response to HTTP requests.\r\n\r\n%% Hosting the Service\r\n% I <http:\/\/msdn.microsoft.com\/en-us\/library\/ms730158%28v=VS.90%29.aspx % host> the |KochJSON| service in a\r\n% <http:\/\/msdn.microsoft.com\/en-us\/library\/ms731758%28v=VS.90%29.aspx % Windows console application>,\r\n% configuring its |HttpBinding| endpoint to publish the |IFractal| contract\r\n% using the |webHttpBinding| protocol. A |webHttpBinding| endpoint\r\n% listens for requests that use XML rather than the more complex SOAP,\r\n% greatly simplifying the client code. I add the new endpoint to the\r\n% application's configuration file, |App.config|:\r\n%\r\n%  <endpoint % address=\"\" % binding=\"webHttpBinding\" % bindingConfiguration=\"webHttpConfig\" % contract=\"IFractal\" % name=\"HttpBinding\" \/>\r\n%\r\n% Clients making an |XMLHttpRequest| require an |webHttpBinding| endpoint.\r\n\r\n%% A JavaScript Client\r\n% My client performs two tasks: requesting the outline of the\r\n% <http:\/\/en.wikipedia.org\/wiki\/Koch_snowflake Koch % snowflake> from the |KochJSON| web service and then drawing the snowflake\r\n% in the browser window. |IFractal|'s |[WebGet]| attribute defines the\r\n% format of the URL serving the snowflake data. To retrieve the 4th\r\n% iteration of the Koch snowflake, scaled to fit within a 300x300\r\n% rectangle, make the following request:\r\n%\r\n%  http:\/\/localhost:42017\/KochJSON\/?n=4&width=300&hieght=300\r\n%\r\n% I've configured the service host to listen for client requests on port\r\n% |42017| on my local machine. The string of parameters following the\r\n% service name match the pattern specified by the |UriTemplate| I defined\r\n% in the |[WebGet]| attribute of the |IFractal| |[ServiceContract]|. The\r\n% parameter |n| here maps to |snowflake|'s input |n|, and so on, and the\r\n% service calls |snowflake(4, 300, 300)|.\r\n%\r\n% Making this request in JavaScript requires an |XMLHttpRequest| object,\r\n% which you create with |new|:\r\n%\r\n%  var request = new XMLHttpRequest();\r\n%\r\n% Call |open| to initialize the request with the HTTP method (|GET|),\r\n% the HTTP address of the service, and |true| to specify the\r\n% request should be made asynchronously. Then call |send| to make the\r\n% request.\r\n%\r\n%  request.open(\"GET\",\r\n%     \"http:\/\/localhost:42017\/KochJSON\/?n=4&width=300&height=300\",\r\n%     true)\r\n%  request.send(null);\r\n%\r\n% The |XMLHttpRequest| object notifies me when the asynchronous request\r\n% completes by invoking a callback function I provide. I convert the\r\n% response data from its JSON text notation into a live JavaScript object\r\n% by invoking |eval|:\r\n%\r\n%  var jsonOutline = eval( '(' + request.responseText + ')' );\r\n%\r\n% My |[DataContract]| structure, |FractalOutline|, contains two\r\n% fields, |vectors| and |bbox|. Since JSON data marshalling preserves\r\n% field names, I retrieve the data from |jsonOutline| by referencing its\r\n% |vectors| and |bbox| fields.\r\n%\r\n%  var outline = jsonOutline.vectors;\r\n%  var bbox = jsonOutline.bbox;\r\n%\r\n% |vectors| and |bbox| are native JavaScript arrays, so I manipulate them\r\n% using native JavaScript syntax. I draw the outline with a for-loop, at\r\n% each step calling the HTML 5 <http:\/\/en.wikipedia.org\/wiki\/Canvas_element % |canvas|> function <http:\/\/dev.w3.org\/html5\/2dcontext\/#dfnReturnLink-1 % |lineTo|>:\r\n%\r\n%  x = x + outline[i][0];\r\n%  y = y + outline[i][1];\r\n%  context.lineTo(x, y);\r\n%\r\n% There's a bit more code in the callback to manage errors and ensure that\r\n% it doesn't start drawing until the entire outline is available, but it\r\n% can't be more than ten lines or so. One line for data marshalling (the\r\n% |eval| statement), a few lines to make and manage the request, but the\r\n% bulk of the code I had to write myself focuses on solving the problem at\r\n% hand, drawing the outline.\r\n\r\n%% Building and Running the Example\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/31295-creating-builder-ne-web-services-for-firefox--ie--chrome-and-safari % Download the code> from MATLAB Central.\r\n%\r\n% The download contains the\r\n% <https:\/\/www.mathworks.com\/products\/matlab\/ MATLAB>\r\n% function |snowflake.m|, a Visual\r\n% Studio 2008 solution |KochJSON.sln| and an HTML page,\r\n% |KochSnowflake.html|, defining the\r\n% JavaScript client. Create the server program by\r\n% following these three steps:\r\n%\r\n% # Build the |IFractal| interface DLL.\r\n% # Create the |Snowflake| .NET assembly and the |KochIFractal| type\r\n% safe interface.\r\n% # Compile the server program, |KochJSON|, after referencing |IFractal| and\r\n% |KochIFractal| in the |KochJSON| project.\r\n%\r\n% The client does not require compilation.\r\n%\r\n% The file |ReadmeWCFJSON.txt| contains detailed instructions.\r\n%\r\n% To run the example, open a DOS window for the server. Make sure the DOS\r\n% window's runtime environment supports the execution of deployed MATLAB\r\n% .NET components (you'll need the\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f12-999353.html MCR>\r\n% on your |PATH|), then run\r\n% |KochJSON\\KochJSON\\bin\\Debug\\KochJSON.exe|. When the server is ready, it\r\n% prints a short message:\r\n%\r\n%  Koch JSON Snowflake Service started.\r\n%  Press any key to terminate service...\r\n%\r\n% Activate the client by double-clicking on |KochSnowflake.html|. The first\r\n% client to contact the server causes the server to load the MCR, which\r\n% takes some time. However, subsequent requests process very rapidly.\r\n% The server supports multiple clients REPLACE_WITH_DASH_DASH try connecting from different\r\n% architectures, using different browsers. HTML 5-capable browsers should\r\n% display something like this:\r\n%\r\n% <<Snowflake.png>>\r\n%\r\n\r\n%% Doing the Right Kind of Work\r\n% Retrieving the data and drawing the outline are\r\n% _domain_ tasks, central to the work I want to get done. Anything else,\r\n% bookkeeping, data marshalling, managing the client server connection, is\r\n% a distraction, an artifact created by the technologies I've chosen to\r\n% implement my solution. Ideally, I'd like those technologies to manage\r\n% themselves REPLACE_WITH_DASH_DASH I'd like to concentrate on writing the code that solves the\r\n% problem. And that's what deployed type safe APIs let me do REPLACE_WITH_DASH_DASH\r\n% with a native C# interface for my MATLAB functions, I can take advantage\r\n% of .NET automation and application management tools that were previously\r\n% inaccessible.\r\n%\r\n% This JavaScript client required more effort than a WCF client generated\r\n% by Visual Studio, but it is lighter weight and much more widely usable.\r\n% Does that matter to you? Will you write cross-platform clients like this\r\n% one? How important is standards compliance to your applications?\r\n% <http:\/\/blogs\/mathworks.com\/loren\/?p=290#respond Let us know>\r\n% what you think.\r\n\r\n##### SOURCE END ##### 4ca699be68ee433f988589d6a3089a79\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n\r\nGuest blogger Peter Webb returns with another in an occasional series of postings about application deployment.\r\n\r\n&nbsp;\r\nContents\r\n\r\n\r\n \tCalling .NET Web Services from JavaScript\r\n \tExchanging... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/09\/30\/creating-net-web-services-for-firefox-ie-chrome-and-safari\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/290"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=290"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/290\/revisions"}],"predecessor-version":[{"id":2126,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/290\/revisions\/2126"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=290"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}