Thursday, June 07, 2018

Error: 'IApplicationBuilder' does not contain a definition for 'UseIdentityServerAuthentication' and...

When I was trying to implement security to one of my .net core Web API, I encountered below error

'IApplicationBuilder' does not contain a definition for 'UseIdentityServerAuthentication' and no extension method 'UseIdentityServerAuthentication' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

After long struggle, I found that .Net Core 2.0 does not support the security the way .NET Core 1.0 used to support, Code need to rewritten in different way, actually need to follow the steps to migrate your Web API to .NET Core 2.0 using Microsoft.AspNetCore.Authentication.JwtBearer; 

Please follow migration steps to resolve this issues

Saturday, September 09, 2017

$'url') directs to currenthost + url instead of just url in AngularJS

Issues:When I am trying following code in AngularJS, it works but opening new window with url like below 


JS File
  $scope.OpenWindow = function (url, _blank) {, '_blank', 'heigth=600,width=600');

 img class="FacebookIcon" ng-click="OpenWindow('')"

Solution: Add 'http://' in the url

JS File
  $scope.OpenWindow = function (url, _blank) { "http://" + url, '_blank', 'heigth=600,width=600');

It will work and open

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

Steps require to host your application into the Pivotal Cloud Foundry

Host your application into the Pivotal Cloud Foundry PCF

Register in Pivotal and go to “Pivotal Web Services”, you will get free trial upto 2 GB

 If you already have an account in PCF then Login using With User Id: Email Id and Pwd: Password

You will need a workspace where app can be hosted, for that you need to create Organization and then Workspace
Go to Given/Created Org >> Click Add Space >> create new space for you

For CF push to work, you will need manifest.yml file to be a part of your app’s output folder.
Sample manifest.yml file content

.NET Framework aAps, yml file 

- name: RiteshWebAPI
  memory: 512m
  disk_quota: 512m  
  buildpack: binary_buildpack
  stack: windows2012R2
    ConnectionString: @SQLConnectionString@
    App_Log: @AppLogConnection@
   - syslog-drain
   - route: @route@
instances: @instances@

.NET Core Apps,  buildpack and stack will be changed , run > cf buildpacks or > cf stacks to see available buildpack and stack in PCF environment.
        buildpack: dotnet_core_buildpack
        stack: cflinuxfs2

Build your App, WebAPI, WebApp etc. Following things needs to be taken care while code, Code need to follow 12 factor app
Best Practices for ASP.Net application Application Types: MVC, WebForm, WebAPI, WCF

  • Avoid Integrated Windows Authentication
  • Avoid the Global Access Cache (GAC)
  • Avoid custom IIS handlers
  • Avoid anything that uses the Windows registry
  • Avoid using local disk for storing application state. Any data that needs to persist needs to be stored in backing service. Ex.  Database (SQL Server,Mongo DB)
  • Avoid in process session state.
  • For ASP.NET override MachineKey in web.config and on ASP.NET Core
  • Avoid persisting keyring to filesystem
  • On ASP.NET avoid environment specific configuration in web.config      
  • Avoid using any Windows specific or disk based logging
  • Avoid any 32-bit specific libraries or libraries that cannot be bin deployable.
Once your App is ready you can publish it in some folder let’s say “C:\Ritesh\WebAPIPublish\”
First steps to start your deployment into the PCF, you need Common Language Interface (CLI) Download CLI from below

Now, Open Command Prompt (cmd), type following commands to login
Login By Browser URL:
Login By CLI URL:

Start Login by command prompt, Go to the directory where you have published your source code (make sure this folder has all required files to run the app, including “.yml” file

C:\Ritesh\ WebAPIPublish> cf login -a
Email> UserId
Password> Password
Space> 1        // if multiple space available, you need to choose desire space

Now you are ready to start the deployment
C:\Ritesh\WebAPIPublish> cf push

If error pops up go and see the log
C:\Ritesh\WebAPIPublish> cf log   - recent

If log shows that health check fail than turn off health check up
C:\Ritesh\WebAPIPublish> cf push --health-check-type=none

Let’s wait till you see application started message
1 of 1 instance running

After successfully deployed you can login online and get the URL and you can use it to access your app like:


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];
               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.

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

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.
  • 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.

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.
  • 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.
  • 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.
  • 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.
  • 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.
<binding name="netTcpTransportBinding">
   <security mode="Transport">
              <Transport clientCredentialType="Windows" />
<binding name="wsHttpMessageBinding">
  <security mode="Message">
              <Message clientCredentialType="UserName" />

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();

        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;
            return Json(empList, JsonRequestBehavior.AllowGet);

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

User Interface Run time



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...");

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; }

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)
     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...");

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;

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