Category Archives: C#

No executable found matching command dotnet-ef

If you try to run the dotnet ef command from powershell and see the following error.

No executable found matching command dotnet-ef

You need to do the following steps to fix it.

  • Add the Microsoft.EntityFrameworkCore.Tools and/or the Microsoft.EntityFrameworkCore.Tools.DotNet package libraries, depending if you want to use the PowerShell command or the CLI version. I personally do always install both of them.
<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0" />
</ItemGroup>

it will add PackageReference like this

  • We also need to add the reference as DotNetCliToolReference which will add the following references
<ItemGroup>
   <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
   <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
   <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

Don’t forget to change the version as per your current version of the .net Core

Advertisements

API Versioning in .net Core 2.0 via URL

Version is helpful when we want to roll out new features without breaking the functionality of the existing ones. . It can also help to provide additional functionalities to selected customers. API versioning can be done in different ways like appending the version in the URL or as a query string parameter, via custom header and via Accept-header.

In this post, let’s find how to support multiple version ASP.NET Core Web API by appending the version in URL.

Let’s create an ASP.NET Core web API application and first thing to do is to include the Microsoft.AspNetCore.Mvc.Versioning package (Install the latest package or what is suitable to your project from the nuget.org). At the point of writing this article .net Core 2.0 is out and also the final 2.0.0 version of this nuget package.

Once the package is restored, we need to configure it. Next open Startup.cs, add the highlighted lines of code in ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddApiVersioning(option =&gt; {
      option.ReportApiVersions = true;
      option.AssumeDefaultVersionWhenUnspecified = true;
      option.DefaultApiVersion = new ApiVersion(1, 0);
    });
}

As you can see, there are 3 different options configured.

  • ReportAPIVersions: This is optional. But when set to true, API returns supported versions information in the response header.
  • AssumeDefaultVersionWhenUnspecified: This option will be used to serve the request without a version. The assumed API version by default would be 1.0.
  • DefaultApiVersion: This option is used to specify the default API version to be used when no version is specified in the request. This will default the version to 1.0.

That’s all for the configuration and setup. Now we will see how to access the versions of the API via the URL path segment.

Query string parameters are useful, but it can be painful in case of long URL and other query string parameters. Instead, the better approach would be to add version in the URL path. Like,

  • api/v1/values
  • api/v2/values

So to do this, we need to put the version in the route attribute. Like,

namespace ValuesController
{
   [ApiVersion("1.0")]
   [Route("api/v{version:apiVersion}/[controller]")]
   public class ValuesController : Controller
   {
     [HttpGet]
     public IActionResult Get() => Ok(new string[] { "value1" });
   }
}

With this change, the API endpoints always need to have the version number. You can navigate to version 1.0 via api/v1/values and to access version 2.0, change the version number in the URL. Simple and looks more clean now.

Deprecated:When multiple API versions are supported, some versions will eventually be deprecated over time. To mark one or more API versions have been deprecated, simply decorate your controller with the deprecated API versions. This doesn’t mean that the API version is not supported. One can still call the endpoint/version. It just a way to make API users aware that following version will be deprecated in future.


[ApiVersion("1.0", Deprecated = true)]

ApiVersionNeutral: attribute defines that this API is version-neutral. This is useful for APIs that behaves the exact same way, regardless of API version or a legacy API that doesn’t support API versioning. So, you can add ApiVersionNeutralattribute to opt out from versioning.

[ApiVersionNeutral]
[RoutePrefix( "api/[controller]" )]
public class SharedController : Controller
{
    [HttpGet]
    public IActionResult Get() => Ok();
}

MapToApiVersion: attribute allows to map a single API action to any version. In other words, a single controller which supports multiple versions say 1 and 3. The controller may have an API action method supported by version 3 only. In such case, you can use MapToApiVersion. Take a look at below code.

namespace ValuesController
{
  [ApiVersion("1.0")]
  [ApiVersion("2.0")]
  [Route("api/v{version:apiVersion}/[controller]")]
  public class ValuesController : Controller
  {
     [HttpGet]
     public IActionResult Get() => Ok(new string[] { "value1" });

     [HttpGet, MapToApiVersion("2.0")]
     public IActionResult GetV3() => Ok(new string[] { "value2" });
  }
}

ASP.NET Core logging with NLog and Elasticsearch

Software Engineering

This article shows how to Log to Elasticsearch using NLog in an ASP.NET Core application. NLog is a free open-source logging for .NET.

Code:VS2017 RC3 csproj | VS2015 project.json

2017.02.08 Updated to NLog.Web.AspNetCore 4.3.0 and VS2017 RC3
17.12.2016 Updated to ASP.NET Core 1.1

NLog posts in this series:

  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. ASP.NET Core logging with NLog and Elasticsearch
  3. Settings the NLog database connection string in the ASP.NET Core appsettings.json
  4. .NET Core logging to MySQL using NLog
  5. .NET Core logging with NLog and PostgreSQL

NLog.Extensions.Logging is required to use NLog in an ASP.NET Core application. This is added to the dependencies of the project. NLog.Targets.ElasticSearch is also added to the dependencies. This project is at present NOT the NuGet package from ReactiveMarkets, but the source code from ReactiveMarkets and updated to dotnetcore. Thanks to ReactiveMarkets for this library, hopefully the NuGet package will…

View original post 181 more words

Sisense SSO implementation in MVC .net core

We can find a documentation regarding what needs to be done in Sisense BI Elastic cube manager in relation to SSO using JWT.  They also have C# code to use for SSO but one may be scratching his head if he/she wants to use that sample code in MVC .net Core application.

So for that purpose I’ld suggest to make one controller with one action in it, Use that URL of that controller action to configure in Sisense SSO configuration page. The sample code would be

 

public IActionResult Index([FromQuery]string return_to)
{
   TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
   int timestamp = (int)t.TotalSeconds;
   var payload = new System.Collections.Generic.Dictionary<string, object>() {
     { "iat", timestamp},
     { "sub", CurrentUser() },
     { "jti", Guid.NewGuid() }
     // Optional properties
     // { "exp", (int)t.Add(TimeSpan.FromMinutes(30)).TotalSeconds } // Expiration time
    };

   string token = Jwt.JsonWebToken.Encode(payload, "secret key from sisense sso                 configuration", Jwt.JwtHashAlgorithm.HS256);
   string redirectUrl = "http://URL_of_your_sisense_web_app_with_port/jwt?jwt=" + token;
   if (return_to != null)
   {
    redirectUrl += "&return_to=" + UrlEncoder.Default.Encode(return_to);
   }
  return Redirect(redirectUrl)
 }
}

Building Single Page Applications using Web API and angularJS (Free e-book)

chsakell's Blog

Single Page Applications are getting more and more attractive nowadays for two basic reasons. Website users have always preferred a fluid user experience than one with page reloads and the incredible growth of several JavaScript frameworks such as angularJS. This growth in conjunction with all the powerful server side frameworks makes Single Page Application development a piece of cake. This post is the online version of the free e-book and describes step by step how to build a production-level SPA using ASP.NET Web API 2 and angularJS. You have two choices. Either grab a coffee and keep going on with this version or simply download the e-book and enjoy it whenever and wherever you want.
spa-webapi-angular-28
There are a lot of stuff to build in this application so I will break this post in the following sections:

View original post 9,862 more words

An element with id ‘form1’ could not be found. Script error on page load

When you use Jquery and AJAX on the same form and you included the jQuery file with the <script /> this error will be thrown by VS (specially VS 2010).  To solve this issue just replace the <script /> with <script><script/> tag and it will solve your problem.

Note: This error will only come when you use IE, with every other browser this error will not come, but the thing common on all browsers is that design view is corrupted and the events will not fire as expected or not fire at all

How to set Icon for application .exe file

We have to follow the simple steps when changing an application’s exe file icon.

  • Go to Solution Explorer
  • Right Click on the Primary Project
  • Go to Properties
  • Go to Application tab
  • In Resources groupbox select the desired icon
This will set the application icon for you.
But if you create a setup of your project and there’s a shortcut of your primary .exe file on user’s desktop, you will find that the icon of that is not changed. For that you have to do the following steps.
  • Go to setup project in Solution Explorer
  • Open File System Editor
  • Go to your User’s Desktop folder
  • Select the shortcut of the primary .exe file (if you didn’t find any file here, then you have to create a shortcut of primary .exe file and put it here)
  • Go to properties of this shortcut
  • Select the desired icon for your application.
Now compile and install the application you will find the changed icon of your shortcut file too

How To Create an ASP.NET HTTP Handler by Using Visual C# .NET

From: microsoft support

Implement the Handler

  1. Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new Class Library project named MyHandler.
  2. Set a reference to the System.Web.dll assembly.
  3. Add the following directive to the class:
    Using System.Web
  4. Rename the class SyncHandler.cs, and then change the class definition to reflect this.
  5. Implement the IHttpHandler interface. Your class definition should appear as follows:
    Public Class SyncHandler: IHttpHandler
  6. Implement the IsReusable property and the ProcessRequest method of theIHttpHandler interface. Because this is a synchronous handler, return False for theIsReusable property so that the handler is not pooled.
    public bool IsReusable
    {
    get {return true;}
    }

    public void ProcessRequest(HttpContext context)
    {
    context.Response.Write(“Hello from custom handler”);
    }

  7. Compile the Project

Deploy the Handler

  1. Create a new directory named Handler under the C:\Inetpub\Wwwroot directory.
  2. Create a subdirectory named Bin in the newly created Handler directory. The resultant path is C:\Inetpub\Wwwroot\Handler\Bin.
  3. Copy MyHandler.dll from your project’s Bin\Debug directory to the C:\Inetpub\Wwwroot\Handler\Bin directory.
  4. Follow these steps to mark the new Handler directory as a Web application:
    1. Open Internet Services Manager.
    2. Right-click the Handler directory, and then click Properties.
    3. On the Directory tab, click Create.
  5. Follow these steps to create an application mapping for the handler. For this handler, create a mapping to the Aspnet_isapi.dll file for the *.sync extension. Whenever a .sync file is requested, the request is routed to ASP.NET, and ASP.NET executes the code in the handler.
    1. Right-click on the Handler Web application, and then click Properties.
    2. On the Directory tab, click Configuration.
    3. Click Add to add a new mapping.
    4. In the Executable text box, type the following path: Microsoft Windows 2000:
      C:\WINNT\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll

      Microsoft Windows XP:

      C:\WINDOWS\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
    5. In the Extension text box, type .sync.
    6. Make sure that the Check that file exists check box is cleared, and then clickOK to close the
      Add/Edit Application Extension Mapping dialog box.
    7. Click OK to close the Application Configuration and the Handler Propertiesdialog boxes.
  6. Close Internet Services Manager.

Configure the System

  1. In the C:\Inetpub\Wwwroot\Handler directory, create a new file named Web.config.
  2. Add the following code to Web.config: <configuration> <system.web> <httpHandlers> <add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" /> </httpHandlers> </system.web> </configuration> In the verb="*" attribute, we instruct the handler to process a request that uses any verb (for example, POST, HEAD, GET, and so on). If you want this handler to process only the POST request, change this to verb="POST". In the path="*.sync" attribute, we instruct the handler to process any incoming requests for files with the .sync extension. In the type="MyHandler.SyncHandler, MyHandler" attribute, we instruct the handler that processes the request to implement in the MyHandler.SyncHandlernamespace, and this class resides in the MyHandler assembly. 

 

How to implement a WCF Service Contract

As I described how to create a Service Contract in the previous post now I will move forward and implement the Service Contract. For this I need to define a class which implements the Interface created for the service Contract.

In the previous post I created a console application for defining a service contract and in Program.cs I defined the service contract. So I am using the same file to write a class code which implements the interface.

The Interface created for the service contract in previous post is as follows.

// Define a service contract.
  [ServiceContract()]
  public interface ICalculator
  {
    // Create the method declaration for the contract.
    [OperationContract]
    double Add(double d1, double d2);
    [OperationContract]
    double Subtract(double d1, double d2);
    [OperationContract]
    double Multiply(double d1, double d2);
    [OperationContract]
    double Divide(double d1, double d2);
  }

Now I will create a class with the name of Calculator which will implement the above mentioned interface.

// Create a class that implements the service contract.
public class Calculator : ICalculator
{
     // Implement functionality for the service operations(methods).
     public double Add(double d1, double d2)
        {
            return d1 + d2;
        }

        public double Subtract(double d1, double d2)
        {
            return d1 - d2;
        }

        public double Multiply(double n1, double n2)
        {
            return d1 * d2;
        }

        public double Divide(double n1, double n2)
        {
            return d1 / d2;
        }
}