Friday, 13 May 2016

WCF Basics :

WCF basic concepts :

SOAP

  • Simple Object Access Protocol
  • HTTP/HTTPS/SMTP
  • Only XML
  • web service security (ws-security)
  • WSDL (Web Services Description Language), XSD (XML Schema definition)

REST

  • Representational State Transfer
  • HTTP/HTTPS
  • text, JSON, XML
  • No ws-security
  • No WSDL, XSD

Interface has below annotation:
[ServiceContract]
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]

Only those methods are interacted outside which has annotation [OperationContract]
[OperationContract] => methods in interface
[OperationContract(IsOneWay=true)] => not wait for response

Below annotation is used to invoke methods:
[WebInvoke(Method="GET/POST/PUT/DELETE",
RequestFormat=WebMessageFormat.Json/Xml,
ResponseFormat=WebMessageFormat.Json/Xml,
UriTemplate="MethodName/{ParameterName}")]

To return fault, use fault contract:
[FaultContract(typeof(InvalidOperationException))]

Add below annotation on your data contract class:
[DataContracrt] => data class

Only those properties are interacted outside, which has [DataMember] annotation.
[DataMember] => property in class

Message contracts are rarely used.
[MessageContract] //Message Contract
[MessageHeader]
[MessageBodyMember]


Various binding protocols:

Example of different types of bindings supported by WCF.

<add binding="basicHttpsBinding" scheme="https" /> => For SOAP service
<add binding="wsHttpsBinding" scheme="https" /> => For SOAP service (Web service security)
<add binding="webHttpBinding" scheme="http" /> => For REST service

Custom Binding configuration

Service endpoint contains 3 parameters:

  1. address: URL address of service
  2. binding: binding type
  3. contract: Interface name
Here we have created custom binding configuration "LargeWeb" for webHttpBinding.
And assign that "LargeWeb" binding configuration in services section.

<bindings>
  <webHttpBinding>
    <binding name="LargeWeb"
             maxBufferPoolSize="1500000"
             maxReceivedMessageSize="1500000"
             maxBufferSize="1500000"
    openTimeout="00:10:00"
             closeTimeout="00:10:00"
             sendTimeout="00:10:00"
             receiveTimeout="00:10:00">
      <readerQuotas
            maxArrayLength="656000"
            maxBytesPerRead="656000"
            maxDepth="32"
            maxNameTableCharCount="656000"
            maxStringContentLength="656000"
            />
    </binding>
  </webHttpBinding>
</bindings>

<services>
    <service name="--service name--" // service name
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="http://localhost:8080/people" // service address using which service can be accessed
        binding="webHttpBinding"
Contract="MyService.Contracts.Ipeople" // Interface address with namespace
bindingConfiguration="LargeWeb" /> // bindingConfiguration name defined in <bindings> section
    </service>
</services>

=====================================================

<system.web>
  <httpRuntime maxRequestLength=”4000″
    enable = “True”
    requestLengthDiskThreshold=”512
    shutdownTimeout=”90″
    executionTimeout=”110″
    versionHeader=”1.1.4128″/>
</system.web>

=====================================================
In web.config file , make includeExceptionDetailInFaults="false" to hide exception details
from user.

<serviceDebug includeExceptionDetailInFaults="false"/> // true for devloper's build and false for production build

SOAP Service Message Example

POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 299
SOAPAction: "http://www.w3.org/2003/05/soap-envelope"

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/nilav">
      <m:StockName>IBM</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

Custom JSON result class

Custom JSON result class that convert resopnse to JSON format in  Web API.

CustomJsonResult.cs


using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class CustomJsonResult : JsonResult
{

    public string FormateStr { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data != null)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(Data);
            MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
            Regex reg = new Regex(@"\\/Date\((\d+)\)\\/");
            jsonString = reg.Replace(jsonString, matchEvaluator);
            response.Write(jsonString);
        }
    }

    private string ConvertJsonDateToDateString(Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)).ToLocalTime();
        return dt.ToString(FormateStr);
    }
}

How to use class in controllers ?


1.  return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

2. return new CustomJsonResult
            {
                Data = data,
                JsonRequestBehavior = behavior,
                FormateStr = format
            };
3. return new CustomJsonResult
            {
                Data = data,
                FormateStr = format
            };
4. return new CustomJsonResult
            {
                Data = data,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

Thursday, 12 May 2016

jQuery.parseJSON vs JSON.parse


jQuery.parseJSON and JSON.parse are two functions that perform the same task.

But If the jQuery library is already loaded, would using jQuery.parseJSON be better than 
using JSON.parse.
jQuery will use the native JSON.parse method if it is available, and otherwise it will try to evaluate the data with new Function, which is kind of like eval.

So yes, you should definitely use jQuery.parseJSON. 

Split WCF service class using partial

In WCF service, If you have lots of methods in your single service then you can physically split those methods ,and arrange them as per your requirements.


Interface:  

ICalculator.cs

[ServiceContract] 
public interface ICalculator 
{ 
   [OperationContract]
   double Add(double n1, double n2);
   [OperationContract]
   double Subtract(double n1, double n2);
   [OperationContract]
   double Multiply(double n1, double n2);
   [OperationContract]
   double Divide(double n1, double n2);
}

Service Class:

1. CalculatorService.cs
public partial class CalculatorService : ICalculator
{
  double Add(double n1, double n2){}
  double Subtract(double n1, double n2){}
}

2. CalculatorService2.cs
public partial class CalculatorService : ICalculator
{
  double Multiply(double n1, double n2){}
  double Divide(double n1, double n2){}
}



Tuesday, 10 May 2016

Using Templates with Bootstrap Modal

HTML:

<button id="btnOpenPopUp">Open</button>

JavaScript:

function openModal(){

  var popUpHTML = "<div class='modal' id='test'>"+
"    <div class='modal-dialog'>"+
"        <div class='modal-content'>"+
"            <div class='modal-header'>"+
"                <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>"+
"                <h4 class='modal-title'>Title</h4>"+
"            </div>"+
"            <div class='modal-body'>"+
"                        Nilav Patel.<br>"+
"                        nilavpatel1992@gmail.com"+
"            </div>"+
"            <div class='modal-footer'>"+
"                <a href='#' data-dismiss='modal' class='btn'>Close</a><a href='#' class='btn btn-primary'>Save changes</a>"+
"            </div>"+
"      </div>"+
"   </div>"+
"</div>";

  var popUp = $.parseHTML( popUpHTML );
  $(popUp).modal();
};

$(document).ready(function(){
     $("#btnOpenPopUp").click(function(){
openModal();
});
});

Get Tree structure data from Array using JQuery :

// json data
var data = [
{
"name": "root",
"parent": 0,
"id": "root",
},
{
"name": "a1",
"parent": "root",
"id": "a1",
},
{
"name": "a2",
"parent": "a1",
"id": "a2",
},
{
"name": "a3",
"parent": "a2",
"id": "a3",
},
{
"name": "b1",
"parent": "root",
"id": "b1",
},
{
"name": "b2",
"parent": "b1",
"id": "b2",
},
{
"name": "b3",
"parent": "b1",
"id": "b3",
}
];

/**
 * get tree structure data
 * @author Nilav Patel
 * @param   {array}  data      -json data
 * @param   {string} id        -id field property name
 * @param   {string} parent    -parent field property name
 * @param   {object} rootValue -value of root
 * @returns {array}  -array with tree structure
 */
function getTreeStructure (data, id, parent, rootValue) {

var idToNodeMap = {};
var root = null;

for (var i = 0, datum; node = data[i]; i++) {
node.children = [];
idToNodeMap[node[id]] = node;
if (node[parent] === rootValue) {
root = node;
}
   else {
parentNode = idToNodeMap[node[parent]];
parentNode.children.push(node);
}
}
return root;
}

var result = getTreeStructure(data, "id", "parent", 0);
console.log(result);

Parent-Child class declaration and initialization

using System; namespace CSharpDemo {     public class A     {         public void print()         {             Console.Wr...