Wednesday, 17 January 2018

ASP.NET Core 2 Web API and Entity Framework Core 2 using Visual Studio Code for beginners


What is ASP.NET Core?

ASP.NET Core is a cross platform,high performance,open source framework for building modern,cloud based, Internet connected applications. With ASP.NET Core, you can:

  • Build web apps and services, IoT apps, and mobile backends.
  • Use your favorite development tools on Windows, macOS, and Linux.
  • Deploy to the cloud or on-premises.
  • Run on .NET Core or .NET Framework.


Let's see how to integrate ASP.NET Core 2 and Entity Framework Core 2 with an example. First set up your development by following the below steps.

1) Download and install

  • .NET Core 2.00 SDK
  • Visual Studio Code C# extension
2) Restart your PC/Device to apply the changes.

3) From the command prompt (cmd) run the following commands to create the project
  • mkdir Product
  • cd Product
  • dotnet new ProductApi
4) Open the ProductApi folder in Visual Studio Code and select the Startup.cs file.
  • Select Yes to the Warn message "Required assets to build and debug are missing from 'ProductApi'. Add them?"
  • Select Restore to the Info message "There are unresolved dependencies".
5) Create new controller and name it as 'ProductController'


Add new class


Add Controller
6) From the command prompt (cmd) run the below commands to create a class library for data access logic and database context.

  • cd ..
  • dotnet new classlib -n Product.Service -o Product.Service
  • cd Product.Service
  • mkdir Data
  • mkdir Logic
  • mkdir Models
7) Open the Product.Service.csproj file and add the following references.

Sample csproj file
8) From the command prompt,navigate to Models folder and create a class called Products and define properties as shown below.

public class Products
{ public int Id { get; set; } public string GuProductId { get; set; } public string Code { get; set; } public string Name { get; set; } public double UnitPrice { get; set; } public string PaymentOption { get; set; } public string Description { get; set; } }


9) From the command prompt, navigate to Data folder and create a class called ProductContext and inherit DbContext class of Microsoft.EntityFrameworkCore namespace as shown below.


using Microsoft.EntityFrameworkCore; 
using Product.Service.Models;

public class ProductContext : DbContext {      public ProductContext(DbContextOptions<ProductContext> options): base(options)      {      } public DbSet<Products> Products { get; set; } }


We have successfully created the DbContext and Model classes to interact with the database. Now We are going to implement the Repository pattern in DAL Project to interact with the database and communicate with the API project .
10) From the command prompt,navigate to the Logic folder in DAL Project and run the following commands.

  • cd ..
  • cd Logic
  • mkdir Repository
  • cd Repository

11) Create an interface called IProductLogicAPI to define methods and then create a class called ProductLogicAPI and inherit the interface created before to implement the methods as shown below.

using System.Collections.Generic; using System.Threading.Tasks; using Product.Service.Models;
public interface IProductLogicAPI { Task<IEnumerable<Products>> GetAll(); Task AddProducts(Products product); Task<Products> FindProduct(string key); }

using System.Collections.Generic; using System.Threading.Tasks; using Product.Service.Data; using Product.Service.Logic.Repository; using Product.Service.Models; using System.Linq; using Microsoft.EntityFrameworkCore;

public class ProductLogicAPI : IProductLogicAPI { ProductContext _context; public ProductLogicAPI(ProductContext context) { _context = context; } public async Task<IEnumerable<Products>> GetAll()
{ return await _context.Products.ToListAsync(); } public async Task AddProducts(Products product) { await _context.Products.AddAsync(product); await _context.SaveChangesAsync(); } public async Task<Products> FindProduct>(string key) { return await _context.Products .Where(e => e.GuProductId.Equals(key)) .SingleOrDefaultAsync(); } }


12) Open the ProductApi.csproj file and add the following reference to it.

<ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.1" /> </ItemGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.2" /> <DotNetCliToolReference Include="Microsoft.En
tityFrameworkCore.Tools.DotNet"
Version="2.0.0"/> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Product.Service\Product.Service.csproj" /> </ItemGroup>


13) Open the ProductController and add the code shown below.

[Route("api/[Controller]")]
public class ProductController : Controller { public IProductLogicAPI ProductRepo { get; set; } public ProductController(IProductLogicAPI _repo) { ProductRepo = _repo; } // GET api/values [HttpGet] public async Task<IActionResult> GetAll() { var productList=await ProductRepo.GetAll(); return Ok(productList); } [HttpGet("{id}", Name = "GetProduct")] public async Task<IActionResult> GetById(string id) { var item = await ProductRepo.FindProduct(id); if (item == null) { return NotFound(); } return Ok(item); } [HttpPost] public async Task<IActionResult> AddProduct([FromBody] Products product) { if (product == null) { return BadRequest(); } await ProductRepo.AddProducts(product);
return CreatedAtRoute("GetProduct", new { Controller = "Product",
id = product.GuProductId }, product); } }

14) Open the startup.cs file and add the following commands.

services.AddDbContext<ProductContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //using Dependency Injection services.AddScoped<IProductLogicAPI, ProductLogicAPI>();

15) Open the appsettings.json and add the connection string as shown below.

{
"Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "ConnectionStrings": { "DefaultConnection": "Data Source=SERVER-LAP;Initial Catalog=NComDB;
Integrated Security=True;MultipleActiveResultSets=True" } }

16) From the command prompt, navigate to Product.Service (DAL) project and then run the following commands to migrate model to database.

dotnet ef --startup-project ../ProductApi migrations add init

Note - add init migrations command will create c# class for model snapshot.

After this run the following command to create the database in SQL Server.

dotnet ef --startup-project ../ProductApi database update


Now we have come to the end where now we can run the project and insert data to SQL Server database using Entity Framework. I hope this article is helpful for beginners.




Monday, 25 September 2017

Setup SendGrid email gateway in Azure to send emails

SendGrid is an email API which is used vastly in lots of web applications and other third party APIs in order to send customized mails. SendGrid has lots of customizable features which gives full freedom to developers where developers can add their own email content,email theme,email attachments and so on. Let's see how to integrate SendGrid email API with Azure in detail. First of all, you have to create azure account, go to https://azure.microsoft.com/en-in/free/ to create a free account which can be used for 30 days.

Create Azure Account
Once you are logged in with the azure portal, click New search for SendGrid and create a SendGrid account with mandatory fields as shown below.


Search SendGrid



Create SendGrid Account


Now click on the account you have created,it will open a extended window where you can see the pricing information of your account and other essential details. You are almost come to the end of configuration. Now in order to access the email API with PHP code you need to generate API keys of SendGrid, in order to do that click "Manage" at the top of your SendGrid account. It will redirect to the below page where you can see the overall API requests and lots of other stuffs.

Manage SendGrid


Now select "Settings" at the bottom of the navigation bar to expand the options where you can see the API keys option listed. Select it and create API keys based on your requirements.

Create API Keys
 
Now let's see how to use SendGrid with PHP. First of all download the below folder, unzip and keep it inside your project folder.


Then, require the sendgrid.php file as shown below to access the methods and properties of the SendGrid API.

require("path/to/sendgrid-php/sendgrid-php.php");

Then add the below code to send email via SendGrid API.

$mail = new SendGrid\Mail();
$subject="Test Mail";
$mail->setSubject($subject);
$email = new SendGrid\Email("MyCompany", "no-reply@mycompany.com");
$mail->setFrom($email);
$personalization = new SendGrid\Personalization();
$email = new SendGrid\Email("toMail","tomail@example.com");
$personalization->addTo($email);
$email = new SendGrid\Email("ccMail","ccmail@example.com");
$personalization->addCc($email);
$email = new SendGrid\Email("bccMail","bccmail@example.com");
$personalization->addBcc($email);
$mail->addPersonalization($personalization);
$apiKey = APIKEY;                           
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());

Note:
Subject is mandatory to send email using SendGrid API where as Cc, Bcc are optional.

For more options to be added to the mail content such as attachments, images refer the example mentioned below.


For finding errors based on the status code refer the document mentioned below.




Sunday, 24 September 2017

Remove non printable and non UTF8 characters url encoded json string in PHP/C#

I have been working on an API (Invitation) which is used to invite external users to a web application. According to invitation API, user gets an invitation where he receives an email with a hyperlink for setup the account and confirmation as shown below.

Invitation Email

The above Get started link contains some necessary details of the invited user which is encrypted and encoded. Once the link is clicked it will redirect to another page where all the decode and decryption process will be done. Sample url encoded json is shown below

https://testdemo.com/entry/Form.html?lPz2ijUnk5wmYMzUYdB40XJie0lkntq9aloNbpyF%2Bp9Hb2FIpMW1aQb9CO9avq0BE5YNjeDuU%2B

Now let's come to decode process. Most of us have experienced with a tricky problem when it comes to json decode. Once the decryption is done u will see there are some non printable characters appended with json which won't allow json string to be decoded.

json with special characters

In order to fix this issue in PHP, once the decryption is done we can remove the special characters using below code.

Code for removing special characters
Once we remove the special characters now we can decode without any problem. Likewise, we can remove the special characters in C# using below code.

string output = Regex.Replace(input, @"[^\u0009^\u000A^\u000D^\u0020-\u007E]", "*");
  • ^\u0009 means if not TAB
  • ^\u000A means if not Line Feed
  • ^\u000D means if not Carriage Return
  • ^\u0020-\u007E means if not fall into space to ~
refer ascii table if you like to make changes, remember it would strip off each non ascii character.

Integrating SonarQube with Jenkins for PHP

SonarQube  is a quality management tool popularly used among 85000 companies around the world. It has four editions. Community Edition ( ...