热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> AJAX编程>>正文内容

示例在AJAX应用中访问ADO.NET Data Service

发布时间:2010年05月15日点击数: 佚名

下面这个例子演示了如何使用ASP.NET AJAX的技术访问到ADO.NET Data Service,并且实现了数据的增删改查等常规操作

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %> 
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  4. <html xmlns="http://www.w3.org/1999/xhtml"> 
  5. <head runat="server"> 
  6.     <title></title> 
  7.  
  8.     <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script> 
  9.  
  10.     <script src="MicrosoftAjax.js" type="text/javascript"></script> 
  11.  
  12.     <script src="DataService.js" type="text/javascript"></script> 
  13.  
  14.     <script type="text/javascript" language="javascript"> 
  15.         function GetService() { 
  16.             return new Sys.Data.DataService("/NorthwindService.svc"); 
  17.         } 
  18.  
  19.         $(function() { 
  20.             $("#query").click(function() { 
  21.                 //发起一个异步查询 
  22.                 var proxy = GetService(); 
  23.                 var query = "/Customers()"; //这里构造的查询字符串可以很复杂 
  24.                 proxy.query(query, function(result, context) { 
  25.                     for (idx in result) { 
  26.                         var customer = result[idx]; 
  27.                         $("<li>" + customer.CustomerID + "," + customer.CompanyName + "</li>").appendTo("#result"); 
  28.                     } 
  29.                 }); 
  30.  
  31.             }); 
  32.  
  33.  
  34.             $("#insert").click(function() { 
  35.                 //插入一个新的客户 
  36.                 var proxy = GetService(); 
  37.                 var customer = { 
  38.                     CustomerID: "ABCDE", 
  39.                     CompanyName: "Thinker Inc" 
  40.                 }; 
  41.  
  42.                 proxy.insert(customer, "/Customers", function(result) { 
  43.                     alert("操作已经成功"); 
  44.                 }); 
  45.  
  46.             }); 
  47.  
  48.  
  49.  
  50.             $("#update").click(function() { 
  51.                 //更新一个客户 
  52.                 var proxy = GetService(); 
  53.                 var customer; 
  54.                 proxy.query("/Customers('ABCDE')", function(result) { 
  55.                     customer = result
  56.  
  57.                     //修改这个customer 
  58.                     customer.CompanyName = "Changed"
  59.                     proxy.update(customer, null, function(result) { 
  60.                         alert("更新成功"); 
  61.                     }); 
  62.                 }); 
  63.  
  64.  
  65.             }); 
  66.  
  67.  
  68.             $("#delete").click(function() { 
  69.                 //删除一个客户 
  70.                 var proxy = GetService(); 
  71.                 var customerID = "ABCDE"
  72.                 proxy.remove(null, "/Customers('" + customerID + "')", function(result) { 
  73.                     alert("删除成功"); 
  74.                 }); 
  75.             }); 
  76.  
  77.         }); 
  78.     </script> 
  79.  
  80. </head> 
  81. <body> 
  82.     <form id="form1" runat="server"> 
  83.     <div> 
  84.         <input type="button" value="查询" id="query" /> 
  85.         <input type="button" value="插入" id="insert" /> 
  86.         <input type="button" value="更新" id="update" /> 
  87.         <input type="button" value="删除" id="delete" /> 
  88.     </div> 
  89.     <ol id="result"> 
  90.     </ol> 
  91.     </form> 
  92. </body> 
  93. </html> 

注意,这个DataService.js是单独的,它实际上是封装了四个操作

  1. //------------------------------------------------------------------------------ 
  2. // <copyright file="DataService.js" company="Microsoft"> 
  3. //     Copyright (c) Microsoft Corporation.  All rights reserved. 
  4. // </copyright> 
  5. //------------------------------------------------------------------------------ 
  6.  
  7. Type.registerNamespace('Sys.Data'); 
  8.  
  9. Sys.Data.ActionResult = function(result, error, actionContext, operation) { 
  10.     /// <summary>Represents the result of a single operation in an action sequence batch.</summary> 
  11.     /// <param name="result" mayBeNull="true">Result (if any) of the operation.</param> 
  12.     /// <param name="error" mayBeNull="true" type="Sys.Data.DataServiceError">Error that occurred during the operation.</param> 
  13.     /// <param name="actionContext" mayBeNull="true">Context object passed to the executor.</param> 
  14.     /// <param name="operation" type="String">Short description of the operation performed.</param> 
  15.     this._result = result; 
  16.     this._error = error; 
  17.     this._actionContext = actionContext; 
  18.     this._operation = operation; 
  19.  
  20. Sys.Data.ActionResult.prototype = { 
  21.  
  22.     /* 
  23.      * PROPERTIES 
  24.      */ 
  25.  
  26.     get_result: function() { 
  27.         /// <summary>Gets the result (if any) of the operation.</summary> 
  28.         /// <value mayBeNull="true">Operation result.</value> 
  29.         return this._result; 
  30.     }, 
  31.     get_error: function() { 
  32.         /// <summary>Gets the error that occurred during the operation.  Returns null if no error occurred.</summary> 
  33.         /// <value mayBeNull="true" type="Sys.Data.DataServiceError">Operation error.</value> 
  34.         return this._error; 
  35.     }, 
  36.     get_actionContext: function() { 
  37.         /// <summary>Gets the context object passed to the executor.</summary> 
  38.         /// <value mayBeNull="true">Operation context object.</value> 
  39.         return this._actionContext; 
  40.     }, 
  41.     get_operation: function() { 
  42.         /// <summary>Gets a short description of the operation performed.</summary> 
  43.         /// <value type="String">Operation description.</value> 
  44.         return this._operation; 
  45.     } 
  46.      
  47. }; 
  48.  
  49. Sys.Data.ActionResult.registerClass("Sys.Data.ActionResult"); 
  50.  
  51. Sys.Data.ActionSequence = function(dataService) { 
  52.     /// <summary>Exposes methods for performing batch operations against a web-based data service.</summary> 
  53.     /// <param name="dataService" type="Sys.Data.DataService">The DataService object against which to perform operations.</param> 
  54.     this._dataService = dataService; 
  55.     this._actionQueue = new Array(); 
  56.  
  57. Sys.Data.ActionSequence.prototype = { 
  58.  
  59.     /* 
  60.      * PROPERTIES 
  61.      */ 
  62.       
  63.     get_service: function() { 
  64.         /// <summary>Gets the DataService object against which operations are performed.</summary> 
  65.         /// <value type="Sys.Data.DataService">The DataService.</value> 
  66.         return this._dataService; 
  67.     }, 
  68.      
  69.     /* 
  70.      * METHODS 
  71.      */ 
  72.  
  73.     addInsertAction: function(item, resourceSetUri, actionContext) { 
  74.         /// <summary>Adds an insertion to the execution queue.</summary> 
  75.         /// <param name="item" type="Object">Item to insert.</param> 
  76.         /// <param name="resourceSetUri" type="String" mayBeNull="true">Resource set into which the item should be inserted.</param> 
  77.         /// <param name="actionContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  78.          
  79.         var dataService = this._dataService; 
  80.         Array.enqueue(this._actionQueue, function(o) { dataService.insert( 
  81.             item, 
  82.             resourceSetUri, 
  83.             Sys.Data.ActionSequence._genSuccessCallback(o), 
  84.             Sys.Data.ActionSequence._genFailureCallback(o), 
  85.             actionContext // userContext (per-action) 
  86.         )}); 
  87.     }, 
  88.      
  89.     addUpdateAction: function(item, resourceUri, actionContext) { 
  90.         /// <summary>Adds an update to the execution queue.</summary> 
  91.         /// <param name="item" type="Object">Item to update.</param> 
  92.         /// <param name="resourceUri" type="String" mayBeNull="true" optional="true">Resource set in which the item should be updated.</param> 
  93.         /// <param name="actionContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  94.          
  95.         var dataService = this._dataService; 
  96.         Array.enqueue(this._actionQueue, function(o) { dataService.update( 
  97.             item, 
  98.             resourceUri, 
  99.             Sys.Data.ActionSequence._genSuccessCallback(o), 
  100.             Sys.Data.ActionSequence._genFailureCallback(o), 
  101.             actionContext // userContext (per-action) 
  102.         )}); 
  103.     }, 
  104.  
  105.     addRemoveAction: function(item, resourceUri, actionContext) { 
  106.         /// <summary>Adds a removal to the execution queue.</summary> 
  107.         /// <param name="item" type="Object" mayBeNull="true">Item to remove.</param> 
  108.         /// <param name="resourceUri" type="String" mayBeNull="true" optional="true">Resource set from which the item should be removed.</param> 
  109.         /// <param name="actionContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  110.          
  111.         var dataService = this._dataService; 
  112.         Array.enqueue(this._actionQueue, function(o) { dataService.remove( 
  113.             item, 
  114.             resourceUri, 
  115.             Sys.Data.ActionSequence._genSuccessCallback(o), 
  116.             Sys.Data.ActionSequence._genFailureCallback(o), 
  117.             actionContext // userContext (per-action) 
  118.         )}); 
  119.     }, 
  120.      
  121.     clearActions : function() { 
  122.         /// <summary>Clears the action queue.</summary> 
  123.         Array.clear(this._actionQueue); 
  124.     }, 
  125.      
  126.     executeActions: function(actionsCallback, userContext) { 
  127.         /// <summary>Executes operations in the action queue.</summary> 
  128.         /// <param name="actionsCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon completion of all operations.</param> 
  129.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this batch.</param> 
  130.      
  131.         // state object for internal callback methods 
  132.         var o = { 
  133.             actionResultQueue: new Array(), 
  134.             hasError: false
  135.             remainingActions: this._actionQueue 
  136.         }; 
  137.          
  138.         // break reference to array so user can't modify after kickoff 
  139.         this._actionQueue = new Array(); 
  140.          
  141.         // kickoff - ensure final callback is asynchronous so as not to break method contract 
  142.         Array.enqueue(o.remainingActions, function(o) { 
  143.             if (actionsCallback) { 
  144.                 window.setTimeout(function() { actionsCallback(o.actionResultQueue, o.hasError, userContext); }, 0); 
  145.             } 
  146.         }); 
  147.         Array.dequeue(o.remainingActions)(o); 
  148.     } 
  149.      
  150.  
  151. /* 
  152.  * STATIC INTERNAL HELPER METHODS 
  153.  */ 
  154.  
  155. // generates an onSuccess callback 
  156. Sys.Data.ActionSequence._genSuccessCallback = function(o) { 
  157.     return function(result, actionContext, operation) { 
  158.         var newAR = new Sys.Data.ActionResult(result, null, actionContext, operation); 
  159.         Array.enqueue(o.actionResultQueue, newAR); 
  160.         Array.dequeue(o.remainingActions)(o); // kickoff next function 
  161.     }; 
  162. }; 
  163.  
  164. // generates an onFailure callback 
  165. Sys.Data.ActionSequence._genFailureCallback = function(o) { 
  166.     return function(error, actionContext, operation) { 
  167.         o.hasError = true
  168.         var newAR = new Sys.Data.ActionResult(null, error, actionContext, operation); 
  169.         Array.enqueue(o.actionResultQueue, newAR); 
  170.         Array.dequeue(o.remainingActions)(o); // kickoff next function 
  171.     }; 
  172. }; 
  173.  
  174. Sys.Data.ActionSequence.registerClass("Sys.Data.ActionSequence"); 
  175.  
  176. Sys.Data.DataService = function(serviceUri) { 
  177.     /// <summary>Exposes methods for interacting with a web-based data service.</summary> 
  178.     /// <param name="serviceUri" type="String">URI (absolute or relative) of the data service.</param> 
  179.     this._serviceUri = serviceUri; 
  180.     this._timeout = 0; 
  181.     this._defaultUserContext = null
  182.     this._defaultSucceededCallback = null
  183.     this._defaultFailedCallback = null
  184.  
  185. Sys.Data.DataService.prototype = { 
  186.  
  187.     /* 
  188.      * PROPERTIES 
  189.      */ 
  190.  
  191.     get_serviceUri: function() { 
  192.         /// <summary>Gets the URI of the data service.</summary> 
  193.         /// <value type="String">The URI of the data service.</value> 
  194.         return this._serviceUri; 
  195.     }, 
  196.      
  197.     get_timeout: function() { 
  198.         /// <summary>Gets the timeout period of each operation.</summary> 
  199.         /// <value type="Number" integer="true">The timeout period (in milliseconds) for each operation.</value> 
  200.         if (this._timeout === 0) { 
  201.             return Sys.Net.WebRequestManager.get_defaultTimeout(); 
  202.         } 
  203.         return this._timeout; 
  204.     }, 
  205.     set_timeout: function(value) { 
  206.         this._timeout = value; 
  207.     }, 
  208.      
  209.     get_defaultUserContext: function() { 
  210.         /// <summary>Gets the default user context (state object) of each operation.</summary> 
  211.         /// <value mayBeNull="true">The default user context for each operation.</value> 
  212.         return this._defaultUserContext; 
  213.     }, 
  214.     set_defaultUserContext: function(value) { 
  215.         this._defaultUserContext = value; 
  216.     }, 
  217.      
  218.     get_defaultSucceededCallback: function() { 
  219.         /// <summary>Gets the default callback executed after each successful operation.</summary> 
  220.         /// <value type="Function" mayBeNull="true">The default success callback for each operation.</value> 
  221.         return this._defaultSucceededCallback; 
  222.     }, 
  223.     set_defaultSucceededCallback: function(value) { 
  224.         this._defaultSucceededCallback = value; 
  225.     }, 
  226.  
  227.     get_defaultFailedCallback: function() { 
  228.         /// <summary>Gets the default callback executed after each unsuccessful operation.</summary> 
  229.         /// <value type="Function" mayBeNull="true">The default failure callback for each operation.</value> 
  230.         return this._defaultFailedCallback; 
  231.     }, 
  232.     set_defaultFailedCallback: function(value) { 
  233.         this._defaultFailedCallback = value; 
  234.     }, 
  235.      
  236.     /* 
  237.      * METHODS 
  238.      */ 
  239.      
  240.     query: function(query, succeededCallback, failedCallback, userContext, webRequest) { 
  241.         /// <summary>Performs a query (read) against the data service.</summary> 
  242.         /// <param name="query" type="String" mayBeNull="true" optional="true">Path to query.</param> 
  243.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  244.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  245.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  246.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  247.          
  248.         var wRequest = this._prepWebRequest(null, query, "GET", succeededCallback, failedCallback, userContext, query, webRequest); 
  249.         wRequest.invoke(); 
  250.     }, 
  251.      
  252.     loadProperty: function(item, property, succeededCallback, failedCallback, userContext, webRequest) { 
  253.         /// <summary>Populates the property of a given item.</summary> 
  254.         /// <param name="item" type="Object">Item containing the property to be populated.</param> 
  255.         /// <param name="property" type="String">Name of the property which should be populated.</param> 
  256.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  257.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  258.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  259.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  260.          
  261.         var succeededHelper = function(result, context, operation) { 
  262.             item[operation] = result; 
  263.             if (!succeededCallback) { 
  264.                 succeededCallback = this._defaultSucceededCallback; 
  265.             } 
  266.             if (succeededCallback) { 
  267.                 succeededCallback(item, context, operation); 
  268.             } 
  269.         }; 
  270.          
  271.         var uri; 
  272.         if (item[property] && item[property].__metadata && item[property].__metadata.uri) { 
  273.             uri = item[property].__metadata.uri; 
  274.         } 
  275.         else if (item.__metadata && item.__metadata.uri) { 
  276.             uri = item.__metadata.uri + '/' + property; 
  277.         } 
  278.         else { 
  279.             throw Error.create(Sys.Data.Res.dataServiceLoadPropertyUriNotPresent); 
  280.         } 
  281.          
  282.         var wRequest = this._prepWebRequest(null, uri, "GET", succeededHelper, failedCallback, userContext, property, webRequest); 
  283.         wRequest.invoke(); 
  284.     }, 
  285.      
  286.     insert: function(item, resourceSetUri, succeededCallback, failedCallback, userContext, webRequest) { 
  287.         /// <summary>Performs an insertion against the data service.</summary> 
  288.         /// <param name="item" type="Object">Item to insert.</param> 
  289.         /// <param name="resourceSetUri" type="String" mayBeNull="true">Resource set into which the item should be inserted.</param> 
  290.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  291.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  292.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  293.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  294.          
  295.         var wRequest = this._prepWebRequest(null, resourceSetUri, "POST", succeededCallback, failedCallback, userContext, "insert", webRequest); 
  296.          
  297.         // moved serialization logic out since we ignore metadata 
  298.         wRequest.set_body(Sys.Serialization.JavaScriptSerializer.serialize(item));                 
  299.         wRequest.get_headers()["Content-Type"] = "application/json"
  300.         wRequest.invoke(); 
  301.     }, 
  302.  
  303.     update: function(item, resourceUri, succeededCallback, failedCallback, userContext, webRequest) { 
  304.         /// <summary>Performs an update against the data service.</summary> 
  305.         /// <param name="item" type="Object">Item to update.</param> 
  306.         /// <param name="resourceUri" type="String" mayBeNull="true">Resource set in which the item should be updated.</param> 
  307.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  308.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  309.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  310.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  311.  
  312.         var wRequest = this._prepWebRequest(item, resourceUri, "PUT", succeededCallback, failedCallback, userContext, "update", webRequest); 
  313.         wRequest.get_headers()["Content-Type"] = "application/json"
  314.         wRequest.invoke(); 
  315.     }, 
  316.      
  317.     remove: function(item, resourceUri, succeededCallback, failedCallback, userContext, webRequest) { 
  318.         /// <summary>Performs a removal against the data service.</summary> 
  319.         /// <param name="item" type="Object" mayBeNull="true">Item to remove.</param> 
  320.         /// <param name="resourceUri" type="String" mayBeNull="true" optional="true">Resource set from which the item should be removed.</param> 
  321.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  322.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  323.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  324.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  325.          
  326.         if (!((item && item.__metadata && item.__metadata.uri) || resourceUri)) { 
  327.             // must specify URI in item metadata or as parameter 
  328.             throw Error.create(Sys.Data.Res.dataServiceRemoveUriNotPresent); 
  329.         } 
  330.          
  331.         var wRequest = this._prepWebRequest(item, resourceUri, "DELETE"
  332.             this._cbReplaceResult(succeededCallback, null/* don't return any object to success callback */
  333.             failedCallback, userContext, "remove", webRequest); 
  334.          
  335.         // we can't actually serialize an item when we perform a removal 
  336.         delete wRequest.get_headers()["Content-Type"]; 
  337.         wRequest.set_body(null); 
  338.          
  339.         wRequest.invoke(); 
  340.     }, 
  341.      
  342.     invoke: function(operationUri, httpVerb, parameters, succeededCallback, failedCallback, userContext, webRequest) { 
  343.         /// <summary>Invokes a method exposed by the data service.</summary> 
  344.         /// <param name="operationUri" type="String">Path to the service operation to invoke.</param> 
  345.         /// <param name="httpVerb" type="String" maybeNull="true" optional="true">HTTP verb to be used for this service call.</param> 
  346.         /// <param name="parameters" type="Object" maybeNull="true" optional="true">Dictionary of parameters to be passed to the service method.</param> 
  347.         /// <param name="succeededCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon successful completion of the operation.</param> 
  348.         /// <param name="failedCallback" type="Function" mayBeNull="true" optional="true">Callback to execute upon unsuccessful completion of the operation.</param> 
  349.         /// <param name="userContext" mayBeNull="true" optional="true">A context object associated with this operation.</param> 
  350.         /// <param name="webRequest" type="Sys.Net.WebRequest" mayBeNull="true" optional="true">A WebRequest object to use for this operation.</param> 
  351.          
  352.         var qb = new Sys.Data.QueryBuilder(operationUri); 
  353.         for (key in parameters) { 
  354.             qb.get_queryParams()[encodeURIComponent(key)] = encodeURIComponent(parameters[key]); 
  355.         } 
  356.          
  357.         var wRequest = this._prepWebRequest(null, qb.toString(), httpVerb, succeededCallback, failedCallback, userContext, operationUri, webRequest); 
  358.         if (httpVerb == "POST") { 
  359.             // prevents CSRF (SQLBUDT 554530) 
  360.             wRequest.get_headers()["X-Service-Post"] = "true"
  361.         } 
  362.         wRequest.invoke();         
  363.     }, 
  364.      
  365.     createActionSequence: function() { 
  366.         /// <summary>Creates a new action sequence for execution against this data service.</summary> 
  367.         /// <returns type="Sys.Data.ActionSequence">An ActionSequence object.</returns> 
  368.         return new Sys.Data.ActionSequence(this); 
  369.     }, 
  370.      
  371.     /* 
  372.      * INTERNAL HELPER FUNCTIONS 
  373.      */ 
  374.      
  375.     // common code for preparing a WebRequest 
  376.     _prepWebRequest: function(item, relUri, verb, onSuccess, onFailure, context, operation, wRequest) { 
  377.      
  378.         if (!relUri) { 
  379.             relUri = ""
  380.         } 
  381.         if (!wRequest) { 
  382.             wRequest = new Sys.Net.WebRequest(); 
  383.         } 
  384.      
  385.         wRequest.set_url(Sys.Data.DataService._concatUris(this._serviceUri, relUri)); 
  386.         wRequest.set_httpVerb(verb); 
  387.         wRequest.set_timeout(this.get_timeout()); 
  388.          
  389.         var headers = wRequest.get_headers(); 
  390.         headers["Accept"] = "application/json"
  391.          
  392.         if (item) { 
  393.             wRequest.set_body(Sys.Serialization.JavaScriptSerializer.serialize(item));                 
  394.             headers["Content-Type"] = "application/json"
  395.             if (item.__metadata && item.__metadata.uri) 
  396.                 wRequest.set_url(item.__metadata.uri); 
  397.         } 
  398.          
  399.         // set defaults 
  400.         if (!onSuccess) { 
  401.             onSuccess = this._defaultSucceededCallback;     
  402.         } 
  403.         if (!onFailure) { 
  404.             onFailure = this._defaultFailedCallback; 
  405.         } 
  406.         if (!context) { 
  407.             context = this._defaultUserContext; 
  408.         } 
  409.          
  410.         wRequest.add_completed(function(executor, eventArgs) { 
  411.             Sys.Data.DataService._callbackHelper(executor, eventArgs, onSuccess, onFailure, context, operation); 
  412.         }); 
  413.          
  414.         return wRequest; 
  415.      
  416.     }, 
  417.      
  418.     // helper to replace the result object for callbacks 
  419.     _cbReplaceResult: function(cb, retVal) { 
  420.         if (!cb) { 
  421.             cb = this._defaultSucceededCallback; 
  422.         } 
  423.         return (cb) 
  424.             ? function(result, context, operation) { cb(retVal, context, operation); } 
  425.             : null
  426.     } 
  427.  
  428.  
  429. /* 
  430.  * STATIC INTERNAL HELPER FUNCTIONS 
  431.  */ 
  432.  
  433. // concatenation of URIs 
  434. Sys.Data.DataService._concatUris = function(serviceUri, resourceUri) { 
  435.  
  436.     if (serviceUri.endsWith('/')) { 
  437.         serviceUri = serviceUri.substr(0, serviceUri.length - 1); 
  438.     } 
  439.          
  440.     if (resourceUri.startsWith('/')) { 
  441.         resourceUri = resourceUri.substr(1); 
  442.     } 
  443.      
  444.     return serviceUri + '/' + resourceUri; 
  445.  
  446. }; 
  447.  
  448. // heavily modified preexisting WebServiceProxy code handles deserialization of data service responses 
  449. Sys.Data.DataService._callbackHelper = function(executor, eventArgs, onSuccess, onFailure, userContext, operation) { 
  450.     if (executor.get_responseAvailable()) { 
  451.         var statusCode = executor.get_statusCode(); 
  452.         // works around an IE bug where 204 responses to PUT requests get turned into 1223 errors. 
  453.         if (statusCode == 1223) { 
  454.             statusCode = 204; 
  455.         } 
  456.         var result = null
  457.         
  458.         try { 
  459.             var contentType = executor.getResponseHeader("Content-Type"); 
  460.             if (contentType.startsWith("application/json")) { 
  461.                 result = executor.get_object(); 
  462.             } 
  463.             else if (contentType.startsWith("text/xml")) { 
  464.                 result = executor.get_xml(); 
  465.             } 
  466.             // Default to the executor text 
  467.             else { 
  468.                 result = executor.get_responseData(); 
  469.             } 
  470.         } catch (ex) { 
  471.         } 
  472.  
  473.         var error = executor.getResponseHeader("jsonerror"); 
  474.         var errorObj = (error === "true"); 
  475.         if (errorObj) { 
  476.             if (result) { 
  477.                 result = new Sys.Data.DataServiceError(false, result.Message, result.StackTrace, result.ExceptionType); 
  478.             } 
  479.         } 
  480.         else if (contentType.startsWith("application/json")) { 
  481.             if (!result || typeof(result.d) === "undefined") { 
  482.                 throw Sys.Data.DataService._createFailedError(operation, String.format("The data operation '{0}' returned invalid data. The JSON wrapper is incorrect.", operation)); 
  483.             } 
  484.             result = result.d; 
  485.         } 
  486.         if (((statusCode < 200) || (statusCode >= 300)) || errorObj) { 
  487.             if (onFailure) { 
  488.                 if (!result || !errorObj) { 
  489.                     result = new Sys.Data.DataServiceError(false /*timedout*/, String.format("The data operation '{0}' failed.", operation), """"); 
  490.                 } 
  491.                 result._statusCode = statusCode; 
  492.                 onFailure(result, userContext, operation); 
  493.             } 
  494.             // #if DEBUG 
  495.             else { 
  496.                 // In debug mode, if no error was registered, display some trace information 
  497.                 if (result && errorObj) { 
  498.                     // If we got a result, we're likely dealing with an error in the method itself 
  499.                     error = result.get_exceptionType() + "-- " + result.get_message(); 
  500.                 } 
  501.                 else { 
  502.                     // Otherwise, it's probably a 'top-level' error, in which case we dump the 
  503.                     // whole response in the trace 
  504.                     error = executor.get_responseData(); 
  505.                 } 
  506.                 throw Sys.Data.DataService._createFailedError(operation, String.format("The data operation '{0}' failed with the following error: {1}", operation, error)); 
  507.             } 
  508.             // #endif 
  509.         } 
  510.         else if (onSuccess) { 
  511.             onSuccess(result, userContext, operation); 
  512.         } 
  513.     } 
  514.     else { 
  515.         var msg; 
  516.         if (executor.get_timedOut()) { 
  517.             msg = String.format("The data operation '{0}' timed out.", operation); 
  518.         } 
  519.         else { 
  520.             msg = String.format("The data operation '{0}' failed.", operation) 
  521.         } 
  522.         if (onFailure) { 
  523.             onFailure(new Sys.Data.DataServiceError(executor.get_timedOut(), msg, """"), userContext, operation); 
  524.         } 
  525.         // #if DEBUG 
  526.         else { 
  527.             // In debug mode, if no error was registered, display some trace information 
  528.             throw Sys.Data.DataService._createFailedError(operation, msg); 
  529.         } 
  530.         // #endif 
  531.     } 
  532. }; 
  533.  
  534. //#if DEBUG 
  535. Sys.Data.DataService._createFailedError = function(operation, errorMessage) { 
  536.     var displayMessage = "Sys.Data.DataServiceFailedException: " + errorMessage; 
  537.     var e = Error.create(displayMessage, { 'name''Sys.Data.DataServiceFailedException''operation': operation }); 
  538.     e.popStackFrame(); 
  539.     return e; 
  540. //#endif 
  541.  
  542. Sys.Data.DataService.registerClass("Sys.Data.DataService"); 
  543.  
  544. Sys.Data.DataServiceError = function(timedOut, message, stackTrace, exceptionType) { 
  545.     /// <summary>Represents a web-based data service error.</summary> 
  546.     /// <param name="timedOut" type="Boolean">Whether the operation failed because of a timeout.</param> 
  547.     /// <param name="message" type="String" mayBeNull="true">The error message.</param> 
  548.     /// <param name="stackTrace" type="String" mayBeNull="true">The stack trace of the error.</param> 
  549.     /// <param name="exceptionType" type="String" mayBeNull="true">The server exception type.</param> 
  550.     this._timedOut = timedOut; 
  551.     this._message = message; 
  552.     this._stackTrace = stackTrace; 
  553.     this._exceptionType = exceptionType; 
  554.     this._statusCode = -1; 
  555.  
  556. Sys.Data.DataServiceError.prototype = { 
  557.  
  558.     /* 
  559.      * PROPERTIES 
  560.      */ 
  561.  
  562.     get_timedOut: function() { 
  563.         /// <summary>True if the data service operation failed due to timeout.</summary> 
  564.         /// <value type="Boolean">Whether the operation failed due to timeout.</value> 
  565.         return this._timedOut; 
  566.     }, 
  567.  
  568.     get_statusCode: function() { 
  569.         /// <summary>HTTP status code of the response if any, defaults to -1 otherwise</summary> 
  570.         /// <value type="Number">Int representing the status of the response.</value> 
  571.         return this._statusCode; 
  572.     }, 
  573.  
  574.     get_message: function() { 
  575.         /// <summary>Error message</summary> 
  576.         /// <value type="String">Error message</value> 
  577.         return this._message; 
  578.     }, 
  579.  
  580.     get_stackTrace: function() { 
  581.         /// <summary>Stack trace of the error</summary> 
  582.         /// <value type="String">Stack trace of the error.</value> 
  583.         return this._stackTrace; 
  584.     }, 
  585.  
  586.     get_exceptionType: function() { 
  587.         /// <summary>Exception type of the error</summary> 
  588.         /// <value type="String">Exception type of the error.</value> 
  589.         return this._exceptionType; 
  590.     } 
  591.  
  592. Sys.Data.DataServiceError.registerClass("Sys.Data.DataServiceError"); 
  593.  
  594. Sys.Data.QueryBuilder = function(uri) { 
  595.     /// <summary>Allows construction of ADO.NET Data Service queries.</summary> 
  596.     /// <param name="uri" type="String">The URI (absolute or relative) to parse.</param> 
  597.     this._queryparams = new Object(); 
  598.     this._uri = uri; 
  599.      
  600.     var idxQuery = uri.indexOf('?'); 
  601.     if (idxQuery >= 0) { 
  602.         // split query string if already exists 
  603.         this._uri = uri.substr(0, idxQuery); 
  604.         var params = uri.substr(idxQuery + 1).split('&'); 
  605.         for (var i in params) { 
  606.             param = params[i]; 
  607.             var idxValue = param.indexOf('='); 
  608.             if (idxValue >= 0) { 
  609.                 this._queryparams[param.substr(0, idxValue)] = param.substr(idxValue + 1); 
  610.             } 
  611.             else { 
  612.                 this._queryparams[param] = ""
  613.             } 
  614.         } 
  615.     } 
  616.  
  617. Sys.Data.QueryBuilder.prototype = { 
  618.  
  619.     /* 
  620.      * PROPERTIES 
  621.      */ 
  622.       
  623.     get_skip: function() { 
  624.         /// <summary>Gets the starting index at which elements should be returned.</summary> 
  625.         /// <value type="Number" integer="true" mayBeNull="true">The number of elements to skip when returning results, 
  626.         /// or null if no skip value is specified.</value> 
  627.         return this._getIntParam("$skip"); 
  628.     }, 
  629.     set_skip: function(value) { 
  630.         this._setParam("$skip", value); 
  631.     }, 
  632.      
  633.     get_top: function() { 
  634.         /// <summary>Gets the maximum number of elements to return.</summary> 
  635.         /// <value type="Number" integer="true" mayBeNull="true">The maximum number of elements to return, 
  636.         /// or null if no maximum is specified.</value> 
  637.         return this._getIntParam("$top"); 
  638.     }, 
  639.     set_top: function(value) { 
  640.         this._setParam("$top", value); 
  641.     }, 
  642.      
  643.     get_orderby: function() { 
  644.         /// <summary>Gets the ordering string that should be applied to the result set.</summary> 
  645.         /// <value type="String" mayBeNull="true">The ordering applied to the result set, 
  646.         /// or null if no ordering is specified.</value> 
  647.         return this._getStringParam("$orderby"); 
  648.     }, 
  649.     set_orderby: function(value) { 
  650.         this._setParam("$orderby", value); 
  651.     }, 
  652.      
  653.     get_filter: function() { 
  654.         /// <summary>Gets the filter string that should be applied to the result set.</summary> 
  655.         /// <value type="String" mayBeNull="true">The filter applied to the result set, 
  656.         /// or null if no filter is specified.</value> 
  657.         return this._getStringParam("$filter"); 
  658.     }, 
  659.     set_filter: function(value) { 
  660.         this._setParam("$filter", value); 
  661.     }, 
  662.      
  663.     get_expand: function() { 
  664.         /// <summary>Gets the property expansion string that should be applied to the result set.</summary> 
  665.         /// <value type="String" mayBeNull="true">The property expansion applied to the result set, 
  666.         /// or null if no property expansion is specified.</value> 
  667.         return this._getStringParam("$expand"); 
  668.     }, 
  669.     set_expand: function(value) { 
  670.         this._setParam("$expand", value); 
  671.     }, 
  672.      
  673.     get_resourcePath: function() { 
  674.         /// <summary>Gets the resource path (without query parameters) originally passed as an argument to 
  675.         /// this object's constructor.</summary> 
  676.         /// <value type="string">The resource path of this QueryBuilder object.</value> 
  677.         return this._uri; 
  678.     }, 
  679.     /* setter temporarily removed until we can figure out how to spec it 
  680.     set_resourcePath: function(value) { 
  681.         var idxQuery = value.indexOf('?'); 
  682.         this._uri = (idxQuery >= 0) ? value.substr(0, idxQuery) : value; 
  683.     }, */ 
  684.      
  685.     get_queryParams: function() { 
  686.         /// <summary>Gets the dictionary of query parameters for the current QueryBuilder.</summary> 
  687.         /// <value type="Object">A dictionary of query parameters.  This object will be non-null but may 
  688.         /// contain no fields if no query parameters have been set.</value> 
  689.         return this._queryparams; 
  690.     }, 
  691.      
  692.     /* 
  693.      * METHODS 
  694.      */ 
  695.      
  696.     toString: function() { 
  697.         /// <summary>Generates a complete query string based on this object's resource path and parameter dictionary.</summary> 
  698.         /// <returns type="string">The complete query string.</returns> 
  699.         var params = new Array(); 
  700.         for (var key in this._queryparams) { 
  701.             if (!Array.contains(Sys.Data.QueryBuilder._queryOptions, key)) { 
  702.                 var value = this._queryparams 

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作