Tuesday, April 30, 2013

A class returning data in the format required by jqgrid

I got following excellent class from http://blog.prabir.me/?tag=/jqgrid
This class returns data exactly in format required by jqgrid

I have only changed the ToString method, prabir's original method uses newtonsoft lib, i have used .net's native javascript serializer.



public class PagedList
{
    IEnumerable _rows;
    int _totalRecords;
    int _pageIndex;
    int _pageSize;
    object _userData;

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
    {
        _rows = rows;
        _totalRecords = totalRecords;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _userData = userData;
    }

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
        : this(rows, totalRecords, pageIndex, pageSize, null)
    {
    }

    public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }

    public int page { get { return _pageIndex; } }

    public int records { get { return _totalRecords; } }

    public IEnumerable rows { get { return _rows; } }

    public object userData { get { return _userData; } }

    public override string ToString()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(this);
       
    }
}

You will require  following namespaces for this to work :

using System.Collections;
using System.Web.Script.Serialization;


Monday, April 29, 2013

Simple jQuery PageMethod call


Simple Ajax call :

   function aa() {
            $.ajax({
                url: "Default.aspx/GetName",
                type: "POST",
                contentType: "application/json;",
                success: function(result) {
                alert(result.d);
                 }
            });
        }

1.  Sequence is not important
2.  Not all parameters are required.

using System.Web.Services;
    [WebMethod]
    public static string GetName()
    {
        return "aabb";
    }

Calling a WCF Service from browser


NOTE : YOU WILL NOT BE ABLE TO CALL THIS FROM JAVASCRIPT.


1. using using System.ServiceModel.Web;

2. [WebGet] to operation contract

3. new endpoint behavior for webHttp

                                                <endpointBehaviors>
                                                                <behavior name="xyz">
                                                                                <webHttp/>
                                                                </behavior>
                                                </endpointBehaviors>

if i write the name of the binding incorrectly, i get the following error :

Configuration binding extension 'system.serviceModel/bindings/webHttp' could not be found. Verify that this binding extension is properly registered in system.serviceModel/extensions/bindingExtensions and that it is spelled correctly.



4. add new endpoint
<endpoint address="web" binding="webHttpBinding" behaviorConfiguration="xyz" contract="IService"></endpoint>

note that the address has been changed to "web"


this is to avoid the conflict :
A binding instance has already been associated to listen URI 'http://localhost:49706/WebSite2/Service.svc'. If two endpoints want to share the same ListenUri, they must also share the same binding object instance. The two conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of AddServiceEndpoint() and config.


4. Call the service using the url ( you need to change the localhost portno)
http://localhost:49706/WebSite2/Service.svc/web/dowork
notice the address of the function : web/dowork
"web" is what we have given in the endpoint address

Difference between regular WCF and Ajax Enabled WCF service




ASP.NET AJAX ENABLED WCF SERVICE
REGULAR ASP.NET WCF SERVICE
<system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="ServiceAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
        <services>
            <service name="Service">
                <endpoint address=""behaviorConfiguration="ServiceAspNetAjaxBehavior"
                    binding="webHttpBinding"contract="Service" />
            </service>
        </services>
    </system.serviceModel>
<system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <servicebehaviorConfiguration="ServiceBehavior"name="Service">
                <endpoint address="" binding="wsHttpBinding" contract="IService">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
1.       Ajax Enabled service does not contain mex endpoint by default.
2.       Ajax Enabled service contains an endpoint behavior, which enable webscript access ( <enableWebScript>) .
Regular service does not contain any such default endpoint behavior, instead it contains a <serviceBehavior> which states httpGetEnabled=true
3.       Binding : Ajax enabled service uses “webHttpBinding” where as regular service uses “wsHttpBinding”.

WCF : Non-Empty address cannot be accessed from javascript

I am not sure about this, but it seems that to be called from javascript, the address should be empty in endpoint configuration. When I gave some address, my service stopped working.

Following is some material I searched, but nowhere this thing is clarified
MSDN And stackoverflow links




How to: Use Configuration to Add an ASP.NET AJAX Endpoint

.NET Framework 4.5
http://i3.msdn.microsoft.com/Areas/Epx/Content/Images/ImageSprite.png
    1 out of 1 rated this helpful - Rate this topic
    Windows Communication Foundation (WCF) allows you to create a service that makes an ASP.NET AJAX-enabled endpoint available that can be called from JavaScript on a client Web site. To create such an endpoint, you can either use a configuration file, as with all other Windows Communication Foundation (WCF) endpoints, or use a method that does not require any configuration elements. This topic demonstrates the configuration approach.
    The part of the procedure that enables the service endpoint to become ASP.NET AJAX-enabled consists of configuring the endpoint to use the WebHttpBinding and to add the <enableWebScript> endpoint behavior. After configuring the endpoint, the steps to implement and host the service are similar to those used by any WCF service. For a working example, see the AJAX Service Using HTTP POST.
    For more information about how to configure an ASP.NET AJAX endpoint without using configuration, see How to: Add an ASP.NET AJAX Endpoint Without Using Configuration.

    To create a basic WCF service

    1.      Define a basic WCF service contract with an interface marked with the ServiceContractAttribute attribute. Mark each operation with the OperationContractAttribute. Be sure to set the Namespace property.
    [ServiceContract(Namespace = "MyService")]
    public interface ICalculator
    {
        [OperationContract]
         // This operation returns the sum of d1 and d2.
        double Add(double n1, double n2);
      
        //Other operations omitted…
      
    }
    2.      Implement theICalculatorservice contract with aCalculatorService.
    public class CalculatorService : ICalculator
    {
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
      
    //Other operations omitted…
    3.      Define a namespace for theICalculatorandCalculatorServiceimplementations by wrapping them in a namespace block.
    Namespace Microsoft.Ajax.Samples
    {
        //Include the code for ICalculator and Caculator here.
    }

    To create an ASP.NET AJAX endpoint for the service

    1.      Create a behavior configuration and specify the <enableWebScript> behavior for ASP.NET AJAX-enabled endpoints of the service.
    <system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="AspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
        </behaviors>
    </system.serviceModel>
    2.      Create an endpoint for the service that uses the WebHttpBinding and the ASP.NET AJAX behavior defined in the previous step.
    <system.serviceModel>
        <services>
            <service name="Microsoft.Ajax.Samples.CalculatorService">
                <endpoint address=""
                    behaviorConfiguration="AspNetAjaxBehavior" 
                    binding="webHttpBinding"
                    contract="Microsoft.Ajax.Samples.ICalculator" />
            </service>
        </services>
    </system.serviceModel> 

    To host the service in IIS

    1.      To host the service in IIS, create a new file named service with a .svc extension in the application. Edit this file by adding the appropriate @ServiceHost directive information for the service. For example, the content in the service file for theCalculatorServicesample contains the following information.
    <%@ServiceHost 
    language=c# 
    Debug="true" 
    Service="Microsoft.Ajax.Samples.CalculatorService"
    %>
    2.      For more information about hosting in IIS, see How to: Host a WCF Service in IIS.

    To call the service

    1.      The endpoint is configured at an empty address relative to the .svc file, so the service is now available and can be invoked by sending requests to service.svc/<operation> - for example, service.svc/Add for theAddoperation. You can use it by entering the endpoint URL into the Scripts collection of the ASP.NET AJAX Script Manager control. For an example, see the AJAX Service Using HTTP POST.

    WCF javascript proxy not found when endpoint address is not blank

    up vote6down votefavorite
    1
    I am trying to setup a WCF service with multiple endpoints with one of the endpoints using the enableWebScript endpoint behavior so that a Javascript proxy will be created on the client (jsdebug/js).
    When adding the Service Reference to my AJAX ScriptManager, the jsdebug file is not found unless the address of the endpoint is blank. The ScriptManager proxy seems to always generate a path of "MyService.svc/jsdebug" to look for the file even though my service has an address of "ajax". The proxy should generate the path as "MyService.svc/ajax/jsdebug".
    Is there a setting to get the Proxy generated with the right path? My service is at the root of my website.
    works:
    <endpoint address="" 
      behaviorConfiguration="ajaxBehavior" 
      binding="webHttpBinding" 
      bindingConfiguration="webBinding" 
      contract="MyTest.Web.ICustomerService" />
    want this (doesn't work):
    <endpoint address="ajax" 
      behaviorConfiguration="ajaxBehavior" 
      binding="webHttpBinding" 
      bindingConfiguration="webBinding" 
      contract="MyTest.Web.ICustomerService" />

    Fabian Steeg
    18.4k33575
    asked Nov 7 '08 at 16:29

    what is your base address? are you connecting into the right path like www.mydomain.com/service.svc/ajax ? – balexandre Jan 28 '09 at 16:35
    What settings did you use for your script manager..? – markt Mar 19 '09 at 3:24

    2 Answers

    up vote2down vote
    <enableWebScript />also known as AJAX-enabled endpoints essentially hard-codes everything to do with address so you can generate the client-side code.
    The way it's hard-coded is that everything is directly relative to the .svc file.
    The endpoint is configured at an empty address relative to the .svc file, so the service is now available and can be invoked by sending requests toservice.svc/<operation>- for example,service.svc/Addfor theAddoperation.
    For this reason, you can't mix<enableWebScript />withUriTemplate, which takes away half the fun out of WCF in my opinion. See enableWebScript, UriTemplate, and HTTP methods.
    Personally, I like to configure my URI and serve both POX and JSON, as well as SOAP. See WCF RESTful POX, JSON and SOAP Coexist.

    jQuery Visual Studio Error : Unexpected character '$' ;Unexpected character '\'


    When runat=”server” was included in the jQuery script src statement,this error was thrown.

    <script type="text/javascript" src="jquery-1.7.1.min.js" runat="server"></script>

    Error      2              Unexpected character '$'             C:\Users\rajesh.chandras\Desktop\MyProjects\WebSite5\jquery-1.7.1.min.js         2             
    Error      5              Unexpected character '\'              C:\Users\rajesh.chandras\Desktop\MyProjects\WebSite5\jquery-1.7.1.min.js         2



    Naturally, we do not want runat=”server” in any jquery code, which normally is meant to run on client.

     using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...