Saturday, 26 September 2020

                                    Rabbit MQ Single Producer and multiple Consumer



Step 1: first install the rabbit mq in your local system ,then create a console application for pushing

the messages in Rabbit MQ.

Name -RabbitMQProducer ,then  install the dependencies as showing here such as newtonsoft and rabbitMQ Client.




Now create a class by name QueueProducer and write the below code as mention below,

using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RabbitMQProducer{
   public static class QueueProducer
 {
        public static void publish(IModel  channel)
        {

           channel.QueueDeclare("demo-queue",
            durable: true,
            exclusive: false,
            autoDelete: false,
            arguments: null);
            int count = 0;
            while (true)
            {
                var message = new { Name = "Producer", Message = $"Hello Count:+{count}"};
                var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
                channel.BasicPublish("", "demo-queue", null, body);
                count++;
                //Thread.Sleep(1000);
            }

        }
    }
}

===================================================================
Program .cs

using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace RabbitMQProducer
{
    class Program
    {
        static void Main(string[] args {
            var factory = new ConnectionFactory
        {
                Uri = new Uri("amqp:guest:guest@localhost:5672")
            };
            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();
            QueueProducer.publish(channel);

        }
    }
}

now run the program ,in this way we are able to push data in rabbit mq.
as you can see we have queued the lakhs of records in rabbit mq.




here you can see there is no consumer.

now we are activating two consumers by clicking on exe  2 times.









Friday, 18 September 2020

                                  Using CQRS And MediatR pattern in micro service



Step1  first create  the solution  by any name as i have taken CQRS.WEB API

Step2 : Create Models folder and create model class by name product.  as below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;


namespace CQRS.WebApi.Models

{

    public class Product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Barcode { get; set; }

        public bool IsActive { get; set; } = true;

        public string Description { get; set; }

        public decimal Rate { get; set; }

        public decimal BuyingPrice { get; set; }

        public string ConfidentialData { get; set; }

    }

}

Step 3: install the below package using package manager console

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Relational
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package MediatR
Install-Package MediatR.Extensions.Microsoft.DependencyInjection
Install-Package Swashbuckle.AspNetCore
Install-Package Swashbuckle.AspNetCore.Swagger

once install it will display like below.



Step 4 now create a folder Context and under this create interface and its implementation.


interface -IApplicationContext

using System.Threading.Tasks;
using CQRS.WebApi.Models;
using Microsoft.EntityFrameworkCore;

namespace CQRS.WebApi.Context
{
    public interface IApplicationContext
    {
        DbSet<Product> Products { get; set; }

        Task<int> SaveChanges();
    }
}

Now create it implementation as below by name ApplicationContext

using CQRS.WebApi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CQRS.WebApi.Context
{
    public class ApplicationContext : DbContext, IApplicationContext
    {
        public DbSet<Product> Products { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options)
            : base(options)
        { }
        public async Task<int> SaveChanges()
        {
            return await base.SaveChangesAsync();
        }
    }
}


Step 5:create connection string in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=developmentDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AllowedHosts": "*"
}

step 6 : configuring the api services to support entity framework core

used name spaces 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CQRS.WebApi.Context;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;




 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
          //  services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddDbContext<ApplicationContext>(options =>
               options.UseSqlServer(
                   Configuration.GetConnectionString("DefaultConnection"),
                   b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));


            #region Swagger
            services.AddSwaggerGen(c =>
            {
             //   c.IncludeXmlComments(string.Format(@"{0}\CQRS.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "CQRS.WebApi",
                });

            });
            #endregion


            services.AddScoped<IApplicationContext>(provider => provider.GetService<ApplicationContext>());

            services.AddMediatR(Assembly.GetExecutingAssembly());
            services.AddControllers();

         //   services.AddValidatorsFromAssembly(typeof(Startup).Assembly);


        }


configure swagger in pipeline

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "CQRS.WebApi");
            });
            #endregion


        }


Step 7 now Create product controller  and 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CQRS.WebApi.Features.ProductFeatures.Commands;
using CQRS.WebApi.Features.ProductFeatures.Queries;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace CQRS.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private IMediator _mediator;

        protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();

        [HttpPost]
        public async Task<IActionResult> Create(CreateProductCommand command)
        {
            return Ok(await Mediator.Send(command));
        }
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            return Ok(await Mediator.Send(new GetAllProductsQuery()));
        }
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            return Ok(await Mediator.Send(new GetProductByIdQuery { Id = id }));
        }
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await Mediator.Send(new DeleteProductByIdCommand { Id = id }));
        }
        [HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, UpdateProductCommand command)
        {
            if (id != command.Id)
            {
                return BadRequest();
            }
            return Ok(await Mediator.Send(command));
        }
    }

}

Step 9 : mandatory package should be installed before doing migration in database 


now do the migration so open the package manager console and run the below command


add-migration "initial"

update-database

when you will run the above command below database and product table will create in database.



now micro service is ready to use on swagger



when fetch the data using get it will display the records like below





















Thursday, 10 September 2020

Crud operations with MongoDB in asp.net core


1. First thing we need to install the mongodb set up in local machine.

so you can download the setup from here,

https://www.mongodb.com/try/download/community,once you installed at the last you need to select the mongoDB compass option,so that it will give you the UI for mongoDB.







you can create database and collection there.


now comes to asp.net core.

dependency need to install ,means below nuget packages need to install,





Step 1  First create the web api solution in .net core with the name ASP_MongoDB,under this solution create folder for model and same for rest such as services,configurations


under configurations ,

Create class DeveloperDatabaseConfiguration and put the property as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ASP_MongoDB.Configurations
{
    public class DeveloperDatabaseConfiguration
    {
        public string CustomerCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }
}






Step 2. Create model 

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ASP_MongoDB.Model
{
    public class Customer
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [Required(ErrorMessage = "First name is required")]
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [BsonElement("PhoneNumber")]
        public string Contact { get; set; }
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }
    }
}


Step 3. Create Service  Folder and create  class as below,


using ASP_MongoDB.Configurations;
using ASP_MongoDB.Model;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ASP_MongoDB.Services
{
    public class CustomerService
    {
        private readonly IMongoCollection<Customer> _customer;
        private readonly DeveloperDatabaseConfiguration _settings;

        public CustomerService(IOptions<DeveloperDatabaseConfiguration> settings)
        {
            _settings = settings.Value;
            var client = new MongoClient(_settings.ConnectionString);
            var database = client.GetDatabase(_settings.DatabaseName);
            _customer = database.GetCollection<Customer>(_settings.CustomerCollectionName);
        }

        public async Task<List<Customer>> GetAllAsync()
        {
            return await _customer.Find(c => true).ToListAsync();
        }

        public async Task<Customer> GetByIdAsync(string id)
        {
            return await _customer.Find<Customer>(c => c.Id == id).FirstOrDefaultAsync();
        }

        public async Task<Customer> CreateAsync(Customer customer)
        {
            await _customer.InsertOneAsync(customer);
            return customer;
        }

        public async Task UpdateAsync(string id, Customer customer)
        {
            await _customer.ReplaceOneAsync(c => c.Id == id, customer);
        }

        public async Task DeleteAsync(string id)
        {
            await _customer.DeleteOneAsync(c => c.Id == id);
        }
    }
}

Step 4. Create the appsettings as below,on mongo DB i have created the database with the name
    DevelopmentDatabase  and also given the name of collection Customers.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "DeveloperDatabaseConfiguration": {
    "CustomerCollectionName": "Customers",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "DevelopmentDatabase"
  },
  "AllowedHosts": "*"


Step 5.         Now Create the Controller as below ,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ASP_MongoDB.Model;
using ASP_MongoDB.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ASP_MongoDB.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly CustomerService _customerService;

        public CustomerController(CustomerService customerService)
        {
            _customerService = customerService;
        }

        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            return Ok(await _customerService.GetAllAsync());
        }

        [HttpGet("{id:length(24)}")]
        public async Task<IActionResult> Get(string id)
        {
            var customer = await _customerService.GetByIdAsync(id);
            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

        [HttpPost]
        public async Task<IActionResult> Create(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            await _customerService.CreateAsync(customer);
            return Ok(customer.Id);
        }

        [HttpPut("{id:length(24)}")]
        public async Task<IActionResult> Update(string id, Customer customerIn)
        {
            var customer = await _customerService.GetByIdAsync(id);
            if (customer == null)
            {
                return NotFound();
            }
            await _customerService.UpdateAsync(id, customerIn);
            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public async Task<IActionResult> Delete(string id)
        {
            var customer = await _customerService.GetByIdAsync(id);
            if (customer == null)
            {
                return NotFound();
            }
            await _customerService.DeleteAsync(customer.Id);
            return NoContent();
        }
    }
}


Step 6: Now comes to startup file and put the dependency as below.


 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<DeveloperDatabaseConfiguration>(Configuration.GetSection("DeveloperDatabaseConfiguration"));
            services.AddScoped<CustomerService>();
            services.AddControllers();
        }



now the service is ready to use ,so you can use 

get ,post,put,delete verbs operations on postman


Get all data like below,


For posting data  like below


we can also check the post data in mongo db as below.



Get Specific data as below,