JS calls the SOA of WCF

Source: Internet
Author: User
Tags tojson

jquery calls the SOA architecture of WCF, applying a three-tier architecture to the SOA architecture

After 3 days of study, I think we should have a preliminary understanding of the SOA architecture, in fact, SOA and the three-tier architecture does not conflict, but the three-tier architecture of the upgraded version.

Take a look at the traditional three-tier architecture! Total can be divided into 4 layers: Model layer (optional), client, server, public layer.

Based on our original three-tier architecture, we have added a service transfer layer! The client then relays through the call service and then calls the service layer, because the client can have multiple, can be Android, can be iOS,

It can be a computer, it can be Linux, because this, regardless of the language and system, they all support JSON and XML.

such as: (Common: Public tier, DataServer service layer, WCF service staging layer, webClient Web client)

Next we look at the key code: (below the corresponding source code download)

See how the process of querying data through a generic query:

First, the foreground accesses our Svc file via Ajax:

1. It is important to note that when Ajax uses get and post, the format of the incoming JSON is not the same.

  var s = ' {' AA ': ' ' + $ (' #txt_data '). Val () + ' "} ';
View Code
$.POSTWCF = function (Database,      method,     //operation by name of    SQL,         //sql statement or incoming data    success,     // Method returned by execution succeeded    err) {       //The method returned by execution failure    = var url = $.getrooturl () + "/webservice.svc/operate";    var data;    if (Sql.indexof ("{") >0 && sql.indexof (' "') >0 && sql.indexof ("} ") >0) {        data = {            " Database ": Database,"            method ": Method,            " SQL ": Json.stringify (SQL),        };    } else {        data = {            "Database": Database,            "method": Method,            "SQL": SQL,        };    }         $.ajax ({        url:url,        contentType: "Application/json;charset=utf-8",        data:JSON.stringify (data),        type: "Post",        success:function (data) {            success (data);        },        error:function (error) {            ERR (Error);}}    );

Above this post method, the JSON format requires ' {' AA ': ' 123 '} '
West This is the Get method, the JSON format is {"AA": "123"}

Obviously, an incoming JSON format is required for quotation marks to be recognized, and one that does not require quotation marks.

View Code
$.GETWCF = function (Database,    method,     //operation by name of    SQL,         //sql statement or incoming data    success,     // Method returned by execution succeeded    err) {       //The method returned by execution failure    = var url = $.getrooturl () + "/webservice.svc/operatebyget";    var data;    if (Sql.indexof ("{") > 0 && sql.indexof (' "') > 0 && sql.indexof ("} ") > 0) {        data = {            " D Atabase ": Database,            " method ": Method,            " SQL ": Json.stringify (SQL),        };    } else {        data = {            "Database": Database,            "method": Method,            "SQL": SQL,        };    }    $.ajax ({        url:url,        contentType: "Application/json;charset=utf-8",        data:data,        type: "Get",        success:function (data) {            success (data);        },        error:function (Error) {            err (error);        }    });}

2. In addition to our backstage, the corresponding contract, that is, the interface needs to be noted is:
We can see that we can see that we've written 2 interfaces, one that needs to be POST

Called, one is required to be called with get, in fact, 2 of the methods executed are the same. The webinvoke corresponds to the call of the post,webget corresponding to the get.

View Code
[ServiceContract]    Interface Isqlserver    {        //<summary>///This refers to the action performed (where the SQL statement is guaranteed)///</summary>//        <param name= "Database" > Databases name </param>//        <param name= "operate" > Actions performed, select, Insert,delete </param>//        <param Name= "Method" > Methods name </param>//        <param name= "SQL" >sql statement </ Param>        //<returns> return data type is in JSON format </returns>       [OperationContract]            [WebInvoke ( Responseformat = Webmessageformat.json, bodystyle = webmessagebodystyle.wrappedrequest)]        string Operate (string Database, string method, String sql);       [WebGet (Responseformat = Webmessageformat.json, bodystyle = webmessagebodystyle.wrappedrequest)]       String Operatebyget (String database, string method, String sql);       }

3. Implement method extensions for the original class, such as adding a. Tojson method on the basis of a DataTable: How to write?

public static class Extend {//<summary>////This is the way to convert a        DataTable to JSON///        </summary> //        <param name= "PData" ></param>///        <returns></returns> public        static string ToJson (This DataTable pData)        {            //Here you can write your code       }

Note must be a static method in a static class with the This keyword in the parameter


4. Implement a reflection can execute the corresponding method (both static and non-static) by specifying the namespace, class name, method name, parameter.

View Code
  <summary>///////</summary>//<param name= "path" > Namespace </param&        Gt <param name= "ClassName" > class name </param>//<param name= "MethodName" > method name </param>// <param name= "dic" > Incoming parameters </param>//<returns> return object type </returns> public static Obje                       CT Execute (string path, String className, String MethodName, dictionary<string,object> dic) {            Object[] Parameters=new object[1];            Parameters[0] = dic; Dynamically finds the desired class from the assembly and uses the system activator to create the instance and finally gets its type type type = Assembly.Load (path). CreateInstance (Path + "." + ClassName).            GetType ();            Define the number of parameters, order and type of storage space;            Type[] Parameterslength; if (Parameters! = NULL)//indicates that the parameter of the method is not null to execute {parameterslength = new type[parameters.                Length];                int i = 0;          foreach (object obj in Parameters)      {Parameterslength.setvalue (obj.                    GetType (), i);                i++;            }} else {//no parameters are null parameterslength = new TYPE[0]; }//Then we'll find the method MethodInfo MethodInfo = type.            GetMethod (MethodName, parameterslength); if (MethodInfo. IsStatic) {return methodinfo.            Invoke (null, parameters);                } else {Object obj = Activator.CreateInstance (type); Represents a call to return MethodInfo that is not part of a static method.            Invoke (obj, parameters); }        }

Note that you see the execution method is static and non-static, static without instantiating the object, otherwise you have to instantiate the object.

5. I also enclose the conversion between JSON and the dictionary method:

View Code
 <summary>///This is the way to convert JSON to dictionary///</summary>//<param name= "Jsondat A "></param>///<returns></returns> public static dictionary<string, object> ToDi          Ctionary (This string jsondata) {object Data = null;            dictionary<string, object> Dic = new dictionary<string, object> (); if (Jsondata.startswith ("[")}) {//If the target is an array type directly, a list<dictionary<string with a key of list will be output, obje                Ct>> Collection 21. Using example list<dictionary<string, object>> listdic = (list<dictionary<string, object>>) Di              c["List"];                      list<dictionary<string, object>> List = new list<dictionary<string, object>> (); MatchCollection Listmatch = regex.matches (Jsondata, @ "{[\s\s]+]}");                   /use a regular expression to match the JSON array 24. foreach (Match ListItem in Listmatch{List.add (ToDictionary ()) (listitem.tostring ());//Recursive Call}             Data = List;           Dic.add ("List", Data); } else {MatchCollection Match = regex.matches (Jsondata, @ "" "(. +?) "": {0,1} (\[[\s\s]+?\]|null| "".) +?""|                                                        -{0,1}\d*);//use regular expressions to match the key and value in the JSON data foreach (Match item in match) { if (item. GROUPS[2]. ToString (). StartsWith ("[")) {//If the target is an array, it will output a key that is the current JSON list<dict Ionary<string, object>> collection list<dictionary<string, Object>&gt ;                                           Listdic = (list<dictionary<string, object>>) dic["key in JSON"]; list<dictionary<string, object>> List = new List<dictionary<string, Object>> (); MatchCollection Listmatch = regex.matches (item. GROUPS[2]. ToString (), @ "{[\s\s]+}");                                            /use regular expression to match JSON array foreach (Match ListItem in Listmatch)                                   {List.add (ToDictionary (listitem.tostring ()));//Recursive call                                        } Data = List; } else if (item. GROUPS[2]. ToString (). ToLower () = = "NULL") data = null;//If it is null (string type), convert directly to null else Dat A = Item. GROUPS[2]. ToString (); The data is written directly to the Dic.add (item) in numbers, a class of strings. GROUPS[1].                                 ToString (), Data);             }} return Dic;             }

6. Other things have been said in the previous chapters, but the principles of WCF look at a simple introduction:
First, the WCF service is requested through Ajax and then into the WCF service backend to verify that the method name exists and executes the method name directly if it exists.

Otherwise the method is found to be executed by reflection. Returns the JSON format of the string. Transfer directly to the front desk. This allows the front and back office to interact directly, and remove the complex

C # calls a method behind the scenes.

Essays Archive-April 2015 jquery invokes the SOA architecture of WCF, applying the three-tier architecture to the SOA Architecture (fourth day) 2015-04-20 16:16 by Liu, 349 reading, collection, compilationAfter 3 days of study, I think we should have a preliminary understanding of the SOA architecture, in fact, SOA and the three-tier architecture does not conflict, but the three-tier architecture of the upgraded version. Take a look at the traditional three-tier architecture! Total can be divided into 4 layers: Model layer (optional), client, server, public layer. Based on our original three-tier architecture, we have added a service transfer layer! The client then relays by invoking the service ...
    • 3 Comment
jquery calls WCF directly, service-oriented SOA architecture (third day) 2015-04-17 11:15 by Liu, 53 reading, collection, compilationThe so-called everything has, only owes the East wind!! The next step is the WCF call, which begins with the client, writing an HTML page, and then writing to the following method:---must first import the jquery plugin//The following method is to get the relative path of the site $.getrooturl = function () {Retu RN WINDOW.L ...
    • 0 Comment
jquery calls WCF directly, service-oriented SOA architecture (next day) 2015-04-14 19:15 by Liu, 177 reading, collection, compilationOn top of that, we're going to start writing the client on the next day, but before I do, I want to tell you this: This simple SOA architecture, which we call directly into the background via WCF, is not using C # code, significantly reducing our client code, and more flexible than the traditional three-tier architecture, More convenient. Someone's going to say that? The foreground does not use C # code at all to invoke ...
    • 2 Comment
Building a simple SOA architecture for BS (the schema of WCF services that invoke the backend directly through jquery) (first day) 2015-04-13 17:45 by Liu, 95 reading, collection, compilationCome on, guys! Are you still using the traditional three-tier architecture? Are you still not aware of the SOA architecture? Then come and learn the next simple SOA architecture. I will teach you how to build this simple SOA architecture. The technical points used to ensure that wcf,ajax, JSON, Reflection, ADO, and so on, if you do not understand what I said, or this ...
    • 0 Comment
. NET control development How to use the code written on the first day in. NET for the next day 2015-04-07 10:26 by Liu, 40 reading, collection, compilationThe first day before we see all is JS code, although the framework of the BS is Java or PHP, reusability is particularly high, but it is difficult to write, how to do, we can be more simple? Of course, we'll be using. NET custom controls at this time. First we will review the first day's code (we have an initial change below)//this ...
    • 0 Comment

Also attach the source code of VS2012:

Http://files.cnblogs.com/files/liujing379069296/MySOA.rar

JS calls the SOA of WCF

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.