1. #1
    Sencha User
    Join Date
    Jun 2012
    Posts
    11
    Vote Rating
    0
    kulothungan is on a distinguished road

      0  

    Default Connect WCF service from Sencha

    Connect WCF service from Sencha


    Hi,

    I have created a WCF sevice using Visual Studio 2010.

    We can browse the WCF service from browser
    http://localhost:35798/RestServiceImpl.svc/json/Hello
    Where "json" is method name and "Hello" is a parameter. The output will be {"JSONDataResult":"Hello"}
    It will works well through browser.

    I need to connect this web service from Sencha Touch.
    I have write the following code in "tab" event of an "Button"

    onMybutton4Tap: function(button, e, options) {

    Ext.util.JSONP.request({
    url: 'http://localhost:35798/RestServiceImpl.svc/json',
    callbackKey: 'callback',
    params: {id: '555'},
    callback: function(result, request) {
    fn_AKExt("SADRONYX",result);
    }
    });

    function fn_AKExt( title,result ){
    Ext.Msg.alert(title, result);
    }



    But it wont connect. Please help me ASAP.

    Thanks & Regards,
    Kulothungan

  2. #2
    Sencha Premium Member
    Join Date
    May 2010
    Location
    Guatemala, Central America
    Posts
    1,261
    Vote Rating
    79
    ssamayoa is a jewel in the rough ssamayoa is a jewel in the rough ssamayoa is a jewel in the rough ssamayoa is a jewel in the rough

      0  

    Default


    1. Use Chrome or WebKit based browser for development, their developer tools are the best.
    2. Why just dont put the Ext.Msg.alert() in the callback? I suspect that you have a function scoping problem.

    Regards.
    UI: Sencha Architect 3.x / ExtJS 4 & 5
    Server side: JEE / EJB 3.x / CDI / JPA 2.x/ JAX-RS / JasperReports
    Application Server: Glassfish / WildFly
    Databases: Oracle / DB2 / MySQL / Firebird

    If you like my answer please vote!

  3. #3
    Sencha User
    Join Date
    Jun 2012
    Posts
    11
    Vote Rating
    0
    kulothungan is on a distinguished road

      0  

    Default


    1. I have tried by using Ex.Msg.Alert() directly on callback, for this also it wont connect.
    2. I have used Safari(webkit based) browser

  4. #4
    Sencha User
    Join Date
    May 2010
    Location
    Las Vegas, NV
    Posts
    133
    Vote Rating
    2
    billtricarico is on a distinguished road

      0  

    Default


    It took me a while to get this working. I am using the online template "AJAX-Enabled WCF Service" be sure to download and install that into Visual Studio 2010. When you create one of these in your Visual Studio solution, make sure your new services are set up like this:

    Code:
    using System;using System.Collections;
    using System.Collections.Generic;
    using System.Reflection;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Web;
    using System.Text;
    
    
    namespace MyNameSpace
    {
        [ServiceContract(Namespace = "")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class MyService
        {
            [WebInvoke(
                Method = "GET",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
                BodyStyle = WebMessageBodyStyle.WrappedRequest
            )]
            public Message MyGetMethod()
            {
                IDictionary<string, string> queryString = HttpUtil.GetQueryString();
                string id;
    
    
                queryString.TryGetValue("id", out id);
    
    
            // your code here    
    
    
                string json = JsonHelper.Serialize(<some object>);
                return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", Encoding.UTF8);
            }
       }
    }
    And use this pattern in your web.config:

    Code:
      <system.serviceModel>
    
    
          <behaviors>
              <endpointBehaviors>
                  <behavior name="MyNameSpace.MyServiceAspNetAjaxBehavior">
                      <enableWebScript />
                  </behavior>
    
    
            .... more behaviors...one for each service
              </endpointBehaviors>
          </behaviors>
        
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
          multipleSiteBindingsEnabled="true" />
    
    
        <bindings>
          <webHttpBinding>
            <binding name="AjaxBinding">
              <security mode="TransportCredentialOnly">
                <transport clientCredentialType="Windows" />
              </security>
            </binding>
          </webHttpBinding>
        </bindings>
    
    
        <services>
          <service name="MyNameSpace.MyService">
            <endpoint address="" behaviorConfiguration="MyNameSpace.MyServiceAspNetAjaxBehavior"
              binding="webHttpBinding" bindingConfiguration="AjaxBinding"
              contract="MyNameSpace.MyService" />
          </service>
    
    
        ... more services
    
    
        </services>
        
      </system.serviceModel>

    In addition, I created some helper methods for extracting HTTP query parameters:

    Code:
    using System.Collections.Generic;using System.ServiceModel;
    using System.ServiceModel.Channels;
    
    
    namespace MyNameSpace.Util
    {
        public class HttpUtil
        {
            /**
             * This is used for HTTP GET
             */
            public static IDictionary<string, string> GetQueryString()
            {
                MessageProperties message = OperationContext.Current.IncomingMessageProperties;
                object value;
                message.TryGetValue("httpRequest", out value);
                HttpRequestMessageProperty httpRequestMessageProperty = (HttpRequestMessageProperty)value;
    
    
                string[] queryStringParameters = httpRequestMessageProperty.QueryString.Split('&');
                Dictionary<string, string> queryStringDictionary = new Dictionary<string, string>();
    
    
                // this IF will catch URL calls are missing query string parameters
                if (queryStringParameters.Length > 1)
                {
                    for (int i = 0; i < queryStringParameters.Length; i++)
                    {
                        string[] parameter = queryStringParameters[i].Split('=');
    
    
                        queryStringDictionary.Add(parameter[0], parameter[1]);
                    }
                }
    
    
                return queryStringDictionary;
            }
    }
    And serializing/deserializing JSON:

    Code:
    namespace MyNameSpace.Util{
        public class JsonHelper
        {
            public static string Serialize<T>(T obj, int total = 1)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, obj);
                string retVal = Encoding.Default.GetString(ms.ToArray());
    
    
                // wrap object in brackets (a json array) even if it's just one element
                if (!retVal.StartsWith("["))
                {
                    retVal = "[" + retVal + "]";
                }
                ms.Dispose();
    
    
                int returnTotal = total;
    
    
                if (total > 1)
                {
                    returnTotal = total;
                }
                else if (obj.GetType().FullName.Contains("List"))
                {
                    returnTotal = ((IList)obj).Count;
                }
    
    
                string json = "{" + "\"Success\":true" + "," + "\"Total\":" + returnTotal + "," + "\"Message\":\"\"" + "," + "\"Results\":" + retVal + "}";
                return json;
            }
    
    
            public static T Deserialize<T>(string json)
            {
                T obj = Activator.CreateInstance<T>();
                MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
                ms.Dispose();
                return obj;
            }
    }
    So in ExtJS you can call like this:

    Code:
    Ext.Ajax.request({    method:'GET',
        url: 'MyService.svc/MyGetMethod',
        params: {
            param1: 0,
            param2: 'test'
        },
        success: function (response) {
            var obj = Ext.decode(response.responseText);
        },
        failure: function (response) {
            var obj = Ext.decode(response.responseText);
            Ext.Msg.show({
                title: 'Error',
                msg: 'An error has occurred:\n\n' + obj.Message,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
        }
    });
    Incidentally, once I complete this project I'm working on, I"m going to go back and replace all this Ext.Ajax.request stuff with ExtDirectMVC. It's a much cleaner way of passing data between client and server. I've done a test projects and had excellent results.

  5. #5
    Sencha User
    Join Date
    Jun 2012
    Posts
    11
    Vote Rating
    0
    kulothungan is on a distinguished road

      0  

    Default


    Hi,

    Please follow my instruction. And tell me how i can call this web methods(XMLData,JSONData) from WCF

    I have developed sample WCF service and trying to connect it via Sencha tool application.
    I have created a WCF Web Service through Visual Studio 2010. It expose two web method "XMLData" and "JSONData"
    I have attached the source code "RestService.rar"
    Unrar this. and open the "RestService.sln" and build the application.
    To see the WSDL browse this link http://localhost:35798/RestServiceImpl.svc

    To see the output of the web methods, browse the following links from browser
    http://localhost:35798/RestServiceIm...ml/12_XML_Test
    http://localhost:35798/RestServiceIm...n/12_JSON_Test

    Then i have tried to call web method "json" from Button Click of the Sencha Application.
    I have using "Ext.util.JSON.Request" to call web service.
    Set url as 'http://localhost:35798/RestServiceImpl.svc/json' and set parameter id='555' (see the image Sencha1.PNG)
    But it wont connect. I am trying to connect it and get the output.

    Please help me

    1. What i need to change in WCF application
    2. What i need to change in Sencha application?



    Thanks
    Kulohthungan




    Attached Files

Thread Participants: 2

Tags for this Thread