Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Monday, May 27, 2013

Jquery Ajax post Custom Object as Json to Wcf Service


function LoadMore() {

    var myData =
    {
        arguments : {
            Category: "Main",
            SearchText: "",
        }
    };


    var jsonedArguments = JSON.stringify(myData);

    $.ajax({
        type: "POST",
        url: "/PublicService.svc/LoadMore",
        contentType: "application/json; charset=utf-8",
        cache: false,
        data: jsonedArguments,
        dataType: "json",
        processdata: true,
        success: function (data) {
         
            debugger;
            var xx = data;

        },
        error: function (msg) {
            alert('CallFiles failed!!!!');
        }
    });
}



 [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public GetFilesResult LoadMore(GetFilesArguments arguments)
        {
            return new GetFilesResult() { TotalCount = 100 };
        }

Thursday, May 2, 2013

jquery ajax enabled wcf Service call sample



    <script language="javascript" type="text/javascript">

        $(function () {
            CallSiblingMenu();
        });

        function getUrlParts(url) {
            var a = document.createElement('a');
            a.href = url;

            return {
                href: a.href,
                host: a.host,
                hostname: a.hostname,
                port: a.port,
                pathname: a.pathname,
                protocol: a.protocol,
                hash: a.hash,
                search: a.search
            };
        }

        function getNavigationUrl()
        {
            var url = window.location.href;
            var navigationUrl = getUrlParts(url).pathname;
            return navigationUrl;
        }

     

        function CallSiblingMenu() {

            var relativeUrl = getNavigationUrl();
            var baseControl = "#siblingsMenu";
            var html = '';

            //clear
            $(baseControl).html('');

            //add loading
            html = html + '<div id="loading" style="margin-left:50px;margin-top:50px;">';
            html = html + '<img src="/App_Themes/Common/Images/loading.gif"  /></div>';
            $(baseControl).append(html);

            $.ajax({
                type: "POST",
                url: "/PublicService.svc/GetSiblings",
                data: '{"relativeUrl": "' + relativeUrl + '"}',
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processdata: true,
                success: function (data) {
                   
                    //remove loading
                    $('#loading').remove();

                    $.each(data.d, function (i, item) {

                        $(baseControl).append('<a class="" href="' + item.Url + '" ><div>' + item.Title + '</div></a>');
                    });

                },
                error: function (msg) {
                    $(baseControl).html('');

                    alert('CallSiblingMenu failed!!!!');
                }
            });
        }



    </script>



</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="LeftNavigationContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <div id="dynamic-wrapper">
        <div id="siblingsMenu"></div>

        <div id="content" runat="server" clientidmode="static">
        </div>

        <div class="clearfix"></div>

    </div>
</asp:Content>

Wednesday, May 1, 2013

Parse WCF Service Date with Javascript


function ToShortDate(dateAsFromServerSide) {

    var parsedDate = new Date(parseInt(dateAsFromServerSide.substr(6)));

    var jsDate = new Date(parsedDate); //Date object
    var day = jsDate.getDate() < 10 ? '0' + jsDate.getDate() : jsDate.getDate();
    var month = jsDate.getMonth() < 10 ? '0' + jsDate.getMonth() : jsDate.getMonth();
    var year = jsDate.getFullYear();

    var result = day + '.' + month + '.' + year

    return result;
}

Sunday, July 22, 2012

command prompt svcutil.exe user defined custom generic list


does not work
C:\_SVC_OUT>svcutil http://localhost:9000/privateservice.svc /out:proxy.cs /ct:System.Collections.Generic.List`1
public PlayerScout.Domain.ReportResponseOfSuccessReportResultDTO_S9iOAnmJ Dashboard_DrillTrend()
    {
        return base.Channel.Dashboard_DrillTrend();
    }
You should reference the custom domain assembly to be able to generate the proxy.

C:\_SVC_OUT>svcutil http://localhost:9000/privateservice.svc /out:proxy.cs /ct:S
ystem.Collections.Generic.List`1 /r:"D:\PlayerScout Project\Main\v4.0\PlayerScou
t\PlayerScout.Domain\bin\Debug\PlayerScout.Domain.dll"

public PlayerScout.Domain.ReportResponse Dashboard_DrillTrend()
    {
        return base.Channel.Dashboard_DrillTrend();
    }

Thursday, July 5, 2012

WCF Json Service Method Argument null Problem

Do NOT use "url" as a argument name.

Wcf Service Method

 [OperationContract]
 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json,
         RequestFormat= WebMessageFormat.Json)]
PageDTO PageByUrl(String url,String language);  --> PageDTO PageByUrl(String title,String language); 


-----------------------------------------------------------------------

Requested Url:

http://localhost:2222/tr-TR/test-page-1
-----------------------------------------------------------------------


Jquery Ajax Call


<script type="text/javascript">

    $(document).ready(function () {
     
        data = window.location.pathname.split("/");
        urlStr = data[data.length -1];
        languateStr = data[data.length - 2];

        var data = new Object();
        data.url = urlStr;   ---> data.title=urlStr;
        data.language = languateStr;

        //var xxx = $.toJSON(data);
        //result: {"url":" test-page-1","language":"tr-TR"}

        caller_dynamic(data);
    });


    var menuUrl = "http://localhost:9000/PublicService.svc/PageByUrl";

    function caller_dynamic(mydata) {
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: menuUrl,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: $.toJSON(mydata),
            success: function (data) {
                $("#content").html(data.Content);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }

        });
    }
     < /script>

---------------------------------------------------------------------

public PageDTO PageByUrl(String url, String language) --> (String title, String language)
        {
            try
            {
                var publicBS = unityContainer.Resolve();
                var page = publicBS.PageByUrl(title);
                return page;
            }
            catch (Exception ex)
            {
                throw DynFaultException.Instance.CreateFault(ex);
            }
        }



Conclusion

if url is null, do NOT panic. just change the name of the argument name url to title.





Monday, July 2, 2012

WCF Method not Allowed

Check type of the method call.

GET - It must be uppercase

        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        String Test();
     
$.ajax({
                     cache: false,
                     type: "GET",
                     async: false,
                     dataType: "json",
                     url: "PublicService.svc/Test",
                     success: function (data) {
                         debugger;
                         $("#containerDiv").html(data);
                     },
                     error: function (xhr) {
                         debugger;
                         alert(xhr.responseText);
                     }

                 });


POST - It must be uppercase



  [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        String Test2();


$.ajax({
                     cache: false,
                     type: "POST",
                     async: false,
                     dataType: "json",
                     url: "PublicService.svc/Test2",
                     success: function (data) {
                         debugger;
                         $("#containerDiv").html(data);
                     },
                     error: function (xhr) {
                         debugger;
                         alert(xhr.responseText);
                     }

                 });



Tuesday, June 26, 2012

WCF ServiceHost Definition


<%@ServiceHost language="C#" debug="true"
Service="CoreNX.DynamicWebManagement.PublicService"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%>

Tuesday, May 29, 2012

How to Get rid of __type and d in wcf json response

How to Get rid of __type and d in wcf json response


Change <enableWebScript /> to <webHttp /> in the web.config



Web.config 

<system.serviceModel>
    <behaviors>
       <serviceBehaviors>
         <behavior name="MyServiceTypeBehaviors" >
           <serviceMetadata httpGetEnabled="true" />
         </behavior>
       </serviceBehaviors>
       <!-- endpoint behavior -->
       <endpointBehaviors>
         < behavior>
           < webHttp />                   <-- add this
       <enableWebScript />    <-- remove that
         < /behavior>
       < /endpointBehaviors>
     < /behaviors>
   < /system.serviceModel>


Results:

with <enableWebScript />

{"d":[{"__type":"MethodName:#TestNamespace.Domain.ClassName","Date":"01","Name":"Tackling","Value":172},{"__type":"MethodName:#TestNamespace.Domain.ClassName","Date":"04","Name":"Tackling","Value":761},{"__type":"MethodName:#TestNamespace.Domain.ClassName","Date":"07","Name":"Tackling","Value":687},{"__type":"MethodName:#TestNamespace.Domain.ClassName","Date":"10","Name":"Tackling","Value":401}]}


with <webHttp />

[{"Date":"01","Name":"Tackling","Value":136},{"Date":"04","Name":"Tackling","Value":697},{"Date":"07","Name":"Tackling","Value":694},{"Date":"10","Name":"Tackling","Value":56}]

PS: The "__type" is some information given to the ASP.NET AJAX library to allow for round-tripping of objects from WCF to Javascript and back to WCF again.

PS: The d prefix is part of the response for the ASP.NET AJAX library to prevent attack

PS !Important:  you cannot use  if you are passing array's of objects through a parameter. Instead, add the  element to the binding.



Monday, May 28, 2012

WCF Service json enabled

Step 1 - Create Interface

[ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebInvoke(Method="GET", ResponseFormat = WebMessageFormat.Json)]
        String Test();
     }




Step 2 - Create Class, Implement Interface


    public class TestService : ITestService
    {
        public string Test()
        {
            return String.Format("This is the test: {0}" , DateTime.Now.ToLongDateString());
        }
    }



Step 3 - Enable Json - Option 1

The WebScriptServiceHostFactory (http://msdn.microsoft.com/en-us/library/bb336135.aspx) class is indicated for the factory. This class allows the use of web protocols and adds the JSON serialization
<%@ ServiceHost Language="C#" Debug="true" Service="TestApplicationNamespace.TestService" CodeBehind="TestService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>



Step 3 - Enable Json - Option 2

  <system.serviceModel>
     < behaviors>
       < serviceBehaviors>
         < behavior>
           < serviceMetadata httpGetEnabled="true"/>
            < serviceDebug includeExceptionDetailInFaults="true"/>
         < /behavior>
       < /serviceBehaviors>

       < !-- endpoint behavior -->
       < endpointBehaviors>
         < behavior>
           < webHttp />
           < enableWebScript />
         < /behavior>
       < /endpointBehaviors>
      
     < /behaviors>
     < serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
   < /system.serviceModel>


Result;

http://localhost:9999/TestService.svc/Test

{"d":"This is the test: 28 Mayıs 2012 Pazartesi"}