Friday, June 30, 2017

.NET Core 1.0.1 Entity Framework – Scaffolding

If you are using .NET Core version 1.0.1, you might have faced some issues to auto-generate database context and Model. There is one more option available to generate database context using command prompt.  

But you have to take care of adding supported/matched DLL reference from Nuget/Nexus.
Go to “project.json” file and make sure you have added following references

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Entityframeworkcore.Sqlserver": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0",
    "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

Now go to the folder where “project.json” file exist and open command prompt.
  1. Generate database Model for selected table only
                C:/Ritesh/EFScafoldingDemo:> dotnet ef dbcontext scaffold “Server={db server name},{port number};Database={db name};Trusted_Connection=True;” Microsoft.Entityframeworkcore.Sqlserver –t “Product”,”Order”
  1. Generate entire database Model    
C:/Ritesh/EFScafoldingDemo:> dotnet ef dbcontext scaffold “Server={db server name},{port number};Database= db name};Trusted_Connection=True;” Microsoft.Entityframeworkcore.Sqlserver

There are multiple option available to generate database model for .NET Core entity framework, you can see from Microsoft site for more detail

After above command executed successfully you can see, dbProductContext.db , Product.cs, Order.cs files.

Friday, June 23, 2017

.NET Core or .NET Framework, What is right for your application?

.NET Framework and .NET Core are two choices for building .NET server-side applications. Both share a lot of the same .NET platform components and you can share code across the two. However, there are fundamental differences between the two and based on what you want to accomplish, your requirement your choice will depend. 
You should use .NET Core for your server application when:
  • You have cross-platform needs.
  • You are targeting microservices.
  • You are using Docker containers.
  • You need high performance and scalable systems.
  • You need side by side of .NET versions by application.
You should use .NET Framework for your server application when:
  • Your application currently uses .NET Framework (recommendation is to extend instead of migrating)
  • You need to use third-party .NET libraries or NuGet packages not available for .NET Core.
  • You need to use .NET technologies that are not available for .NET Core.
  • You need to use a platform that doesn’t support .NET Core.

Thursday, April 20, 2017

Best way to understand Bubble sort and Insertion Sort Algorithm

Bubble Sort 

Below image will describe how bubble sort code work when code execute in loop, below pictures are self explanatory for algorithm steps. 
C# Code
public int[] BubbleSort(int[] val)
{
           bool flag = true;
           int temp;

           for (int i =0;(i<=val.Count()-1) && flag; i++)
           {
               flag = false;
               for (int j = 0; j < val.Count()-1; j++)
               {
                   if (val[j + 1] < val[j])
                   {
                       temp = val[j + 1];
                       val[j + 1] = val[j];
                       val[j] = temp;
                       flag = true;
                   }
               }
           }
           return val;
}

Insertion Sort

Faster than bubble sort
C# Code
public int[] InsertionSort(int[] val)
{
           for (int i = 0; i <= val.Count(); i++)
           {
               int temp = val[i];
               int j = i - 1;

               while (j >= 0 && val[j] < temp)
               {
                   val[j + 1] = val[j];
                   j--;
               }
               val[j + 1] = temp;
        }
           return val;
}

.NET Core Error: /Core and /WepApp.deps.json could not be found

When I tried to run my first .NET Core web application, I found wired issues and it took me longer time to figure out, what is actual issues was, error message was not helping at all to find out the solution

.NET Core Error: <<Project Dir Path>>/Core and <<Project Dir Path>>/WepApp.deps.json could not be found

To find out the solution, I started couple of times from scratch and finally I tried with different directory and file name to save my .NET Core project.

Issues:
Previous Project Path was:  C:\Ritesh\NET Core\Core WebAPP

Solution:
Later Project Path (works): C:\Ritesh\NETCore\CoreWebApp  (NO SPACE in dir name and file name)

It's works for me, I don't know this is the really solution or Microsoft need to release some patch to fix this.

Friday, March 10, 2017

Parameters needs to be considered before choosing REST or SOAP

There are many parameter needs to be considered before choosing REST or SOAP like

Performance & Scalability
  • REST has better Performance and Scalability features. Read operation in REST can be cached whereas SOAP based read cannot be cached.
  • REST service is good when we have limited bandwidth and have requirement to accomplish by simple CRUD based operation.
Security
  • Provide more choice for implementing security beyond the standard SSL support by implementing WS-Security standard
Transaction Support
  • SOAP can support distributed two-phase commit transactions by implementing WS-Atomic standards.
  • REST does not support transaction
Extended Client Support
  • REST allow better support for browser and mobile clients due to its support for JSON.
Extended Data Format Support
  • REST allows many data format like JSON, XML, Text, SOAP only support XML which require more bandwidth to pass data through wire
Multiple Protocol Support
  • SOAP service can use any transport protocol such as HTTP, HTTPS, TCP, SMTP, and MSMQ. REST only support standard HTTP and it is much easier to implement, simple methods to call GET, PUT, POST and DELETE.
Error Handling
  • REST support standard HTTP error handling but SOAP provide more robust error handling including user define error handling.
Summary

                   REST
                     SOAP
Expose the data
Expose the logic
Support multiple Data format, JSON, XML, HTML, Text etc.
Support only XML
Support only Http, Https protocol
Support multiple protocol; Http, Https, TCP, UDP SMTP, Messaging etc.
Support for Transaction Management but not ACID compliance or two-phase commit transaction.
Better support for transaction management Support, ACID and two-phase commit transaction by implementing WS-Atomic Standard
Need less band width
Need more band width because of XML
Suited for stateless CRUD operations
Suited for Stateful operation, Easy to configure session support
Less support for Security
Supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
SOAP WS has Better support for Security Both SSL security and WS-security
Better Support for browsers and mobile client, Because of Lightweight
Limited browser support
Read operation can be cached
Read Operation cannot be cached
Support for better performance and scalability
Performance is less as compare to REST
Support only HTTP error Handling
Support robust error handling including user define error handling
Only support Synchronous message
Can support Synchronous and Asynchronous both messages

Thursday, February 02, 2017

WCF Security, When/How to Use, Advantages and Disadvantages

Transport Security
Message Security
When using transport security, the user credentials and claims are passed by using the transport layer. In other words, user credentials are transport-dependent, which allows fewer authentication options compared to message security. Each transport protocol (TCP, IPC, MSMQ, or HTTP) has its own mechanism for passing credentials and handling message protection. The most common approach for this is to use Secure Sockets Layer (SSL) for encrypting and signing the contents of the packets sent over Secure HTTP (HTTPS).
When using message security, the user credentials and claims are encapsulated in every message using the WS-Security specification to secure messages. This option gives the most flexibility from an authentication perspective. You can use any type of security credentials you want, largely independent of transport, as long as both the client and service agree.
Use
  • You are sending a message directly from your application to a WCF service and the message will not be routed through intermediate systems.
  • Both the service and the client are located in an intranet.
Use
  • You are sending a message to a WCF service, and the message is likely to be forwarded to other WCF services or may be routed through intermediate systems.
  • Your WCF clients are accessing the WCF service over the Internet and messages may be routed through intermediate systems.
Advantage
  • It provides interoperability, meaning that communicating parties do not need to understand WS-Security specifications.
  • It may result in better performance.
  • Hardware accelerators can be used to further improve the performance.
Advantage
  • It provides end-to-end security. Because message security directly encrypts and signs the message, having intermediaries does not break the security.
  • It allows partial or selective message encryption and signing, thus improving overall application performance.
  • Message security is transport-independent and therefore can be used with any transport protocol.
  • It supports a wide set of credentials and claims, including the issue token that enables federated security.
Dis Advantage
  • Security is applied on a point-to-point basis, with no provision for multiple hops or routing through intermediate application nodes.
  • It supports a limited set of credentials and claims compared to message security.
  • It is transport-dependent upon the underlying platform, transport mechanism, and security service provider, such as NTLM or Kerberos.
Dis Advantage
  • This option may reduce performance compared to transport security because each individual message is encrypted and signed.
  • It does not support interoperability with older ASMX clients, as it requires both the client and service to support WS-Security specifications.
<netTcpBinding>
<binding name="netTcpTransportBinding">
   <security mode="Transport">
              <Transport clientCredentialType="Windows" />
   </security>
</binding>
</netTcpBinding>
<wsHttpBinding>
<binding name="wsHttpMessageBinding">
  <security mode="Message">
              <Message clientCredentialType="UserName" />
  </security>
 </binding>
</wsHttpBinding>

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