Friday, October 28, 2016

Quick coding excersice to learn Angular

I have created one simple user interface with MVC Controller to understand AngularJS directive, controller, module, GET and PUT method. This will help at beginner level, one single code will let you know many things.

User Interface Code














































































MVC C#.NET Controller Code

namespace AngularTutorial.Controllers
{
    public class Emp
    {
        public string Name {get; set;}
        public string City {get; set;}
    }

    public class AngularController : Controller
    {
         public ActionResult Angular()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetEmpData()
        {
            List empList = new List();

            for (int i = 0; i <= 5; i++)
            {
                Emp emp = new Emp();
                emp.Name = "Ritesh - " + i;
                emp.City = "Jbp - " + i*i;
                empList.Add(emp);
            }
            return Json(empList, JsonRequestBehavior.AllowGet);
         }

        [HttpPost]
        public ActionResult Employee(Emp emp)
        {
            if (ModelState.IsValid)
            {
                // Add data insert/update logic here
            }
            return View();
        }
}
}

User Interface Run time


 

Referencehttp://www.w3schools.com/angular/

Friday, July 08, 2016

Understand Action, Func and Delegate, workflow, calls with Lambda & Anonymous method etc.

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does NOT return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and DOES returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Action does not return value. Func and Action take up to 16 parameters, Func take one extra parameter for Return, so total parameter for Func is 17.

C#.NET Example to use Func & Action 

public static double CalculateSomething(int i, int j)
{
   return  new double();
}

public static void DoSomething(int i, int j)
{
    Console.WriteLine("we are here...");
}

//Call
Func<intintdouble> myFunc = (CalculateSomething);

Action<intint> myAction = (DoSomething);

double is return.output parameter

How Delegate works, just to compare with Action & Func

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

//Delegate declare
public delegate int MyOwnDelegate(int i, int j);

private int ShowAddition(int i, int j) { return i + j; }

private int ShowMultipy(int i, int j) { return i * j; }

//Call
MyOwnDelegate dele = new MyOwnDelegate(ShowAddition);
dele(10, 20); //Output 30

//If it hold reference of more then one method then it called MultiCast Delegate
dele += new MyOwnDelegate(ShowMultipy);
dele(10, 20);  //Output  30 and 200
  
Then the Delegate is added using the += operator and removed using the -= operator.  
                 

How Func works

public sealed class emp
{
   public double Calculate(Func<doubledouble> op)
   {
        return op(20);
   }
}

public class Program
   public static double Display(double i)
   {
       return i*9;
   }
   private static void Main(string[] args)
   {
            //Call
     emp e = new emp();
     double d1 = e.Calculate(Display);

    //Another way to call this function, with inline function
     double d1 = e.Calculate(r => 2*Math.PT*r);
    }
}
  1. ‘Calculate’ function takes input parameter as function name ‘Display’ to execute
  2. First control goes inside ‘Calculate’ function and convert op(20) into Display(20).
  3. Then control go to ‘Display’ function, which is taking ‘20’ as an input parameter and convert i*9 into 20*9 and
  4. Final Output of d1 is 180;

Action uses for Lambda & Anonymous method

public class Base
{
  public void Foo(Action action)
  {
     Console.WriteLine("Action with No Param...");
  }

  public void Foo(Action<int> action)
  {
     Console.WriteLine("Action with ONE param...");
  }
  
  public void Foo(Action<int, int> action)
  {
     Console.WriteLine("Action with TWO param...");
  }
}

//Call
Base d = new Base();
int x = 0;

//lambda expression
d.Foo(() => { x = 0; });       // Call Foo with No param in Action
d.Foo((i) => { x = 0; });      // Call Foo with ONE  param in Action
d.Foo((i, j) => { x = 0; });  // Call Foo with TWO param in Action

//Anonymous Method
d.Foo(delegate() { x = 0; });               // Call Foo with No param in Action
d.Foo(delegate(int i) { x = 1; });          // Call Foo with ONE  param in Action
d.Foo(delegate(int i, int j) { x = 2; });   // Call Foo with TWO param in Action

Func uses for Lambda & Anonymous method

public class Base
{ 
 public int Foo(Func<int> action)
 {
    Console.WriteLine("Func with No Param...");
    return 1;
  }

  public int Foo(Func<int,int> action)
  {
    Console.WriteLine("Func with No Param...");
    return 2;
  }

  public int Foo(Func<int, int,int> action)
  {
    Console.WriteLine("Func with TWO param...");
    return 3;
  }
}

//Call
Base d = new Base();
int x = 0;

//lambda expression
d.Foo(() => 0);                  // Call Foo with No param in Func
d.Foo((int i) => 10);            // Call Foo wit ONE  param in Func
d.Foo((int i, int j) => 20);     // Call Foo with TWO param in Func

//Anonymous Method
d.Foo(delegate() { return 1; });          // Call Foo with No param in Func
d.Foo(delegate(int i) { return 1; });     // Call Foo with ONE param in Func
d.Foo(delegate(int i, int j) { return 1; }); // Call Foo with TWO param in Func

Friday, May 20, 2016

Support high volume data transfer by WCF service

Sometime the requirement is send big data to WCF service from client, basically looking for option to send high data through the wire.

WCF can support up to 2 GB data through the wire; even though it is not recommended.

To enable this we need to set some attributes to binding tags in Server and Client side config file

Server Config File
<bindings>
   <wsHttpBinding>
     <binding name="wsHttpBindingSettings" maxReceivedMessageSize="2147483647">
       <readerQuotas
              maxDepth="2147483647"
              maxStringContentLength="2147483647"
              maxArrayLength="2147483647"
              maxBytesPerRead="2147483647"
              maxNameTableCharCount="2147483647"/>
      </binding>
   </wsHttpBinding>
</bindings>

<endpoint
address=""
binding="wsHttpBinding"
contract="WcfService1.IService1"
bindingConfiguration="wsHttpBindingSettings">      

Client Config File 

<bindings>
  <wsHttpBinding>
     <binding
name="WSHttpBinding_IService1"
maxBufferPoolSize="2147483647"
              maxReceivedMessageSize="2147483647">
      <readerQuotas
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
              maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
     </binding>
  </wsHttpBinding>

</bindings>
   <endpoint
address="http://localhost:59284/Service1.svc"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" 
contract="ServiceReference1.IService1"
       name="WSHttpBinding_IService1">

Thursday, May 19, 2016

The client certificate is not provided. specify a client certificate in clientcredentials.

I have done all the setup; require to setup WCF message security and tried calling service from client, is working fine without any issues.
later I made few changes on the service and again use 'Update Service Reference' to update my service. suddenly service stop working and gave below error
 "The client certificate is not provided. specify a client certificate in clientcredentials."

Cause
As soon as I did service update; client side config file updated with new endpoint section, that removed (custom) one attribute 'behaviorConfiguration'.

Solution
After updating the service reference add 'behaviorConfiguration' attribute to endpoint section like below

<endpoint 
address="http://localhost:65514/Service1.svc" 
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" 
contract="ServiceReference1.IService1"

name="WSHttpBinding_IService1"
behaviorConfiguration="CustomBehavior">

If you have added any kinds of attributes; that will be removed after you update service using 'Update Service Reference'.

The caller was not authenticated by the service. WCF with Certificate Credential

After setting all section in the config file everything works, but when I tried to call service from client then I got error "The caller was not authenticated by the service.

Cause

The problem was Client and Server Certificates (WcfServer & WcfClient) was on

In MMC
Console Root à Certificate Current User à Personal à Certificates
But NOT in
Console Root à Certificate Current User à Trusted People à Certificates

Solution
  • In MMC
  • Copy both certificates 
  • From: Console Root à Certificate Current User à Personal à Certificates
  • TO:    Console Root à Certificate Current User à Trusted People à Certificates

After done this it’s solve my problem.

How to set Security (Certificate) in WCF service, 9 simple steps are here

Create certificate by using makecert.exe
  • makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfServer -sky exchange -pe
  • makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfClient -sky exchange -pe

Mostly we have to set following sections in Server and Client Config files
  • services
  • behaviors
  • bindings
  • endpointBehaviors

 WCF Server Config
<services>
  <service name="WcfService1.Service1" behaviorConfiguration="wsHttpServices">
          <endpoint address=""
                    binding="wsHttpBinding"
                    bindingConfiguration="wsHttpBinding_config"
                    contract="WcfService1.IService1">
          </endpoint>
        </service>
</services>

<behaviors>
      <serviceBehaviors>
        <behavior name="wsHttpServices">
>
  <clientCertificate>
         <authentication certificateValidationMode="PeerTrust"/>
  </clientCertificate>
        <serviceCertificate
findValue="WcfServer"
storeLocation="CurrentUser"
storeName="My" 
x509FindType="FindBySubjectName" >
</serviceCertificate>
 </serviceCredentials>
      </behavior>
   </serviceBehaviors>
</behaviors>

<bindings>
      <wsHttpBinding>
        <binding name="wsHttpBinding_config">
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
</bindings>

WCF Client Config
<client>
      <endpoint address="http://localhost:65514/Service1.svc"
              binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
contract="ServiceReference1.IService1" behaviorConfiguration="CustomBehavior"
              name="WSHttpBinding_IService1">
        <identity>
<dns value="WcfServer"/>         
        </identity>
      </endpoint>
</client>

<endpointBehaviors>
        <behavior name="CustomBehavior">
          <clientCredentials>
            <clientCertificate
findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My"/>
            <serviceCertificate>
              <authentication certificateValidationMode="PeerTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
</endpointBehaviors>

<bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService1">
          <security>
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </wsHttpBinding>
 </bindings>