Consume web API in MVC or Windows Application or Console Application

Consume web API in MVC or Windows Application or Console Application

Sometime, we need to consume web API mostly in MVC or Windows Service or Windows Application or Console Application.  

Below code posts dynamic object in API call,


var url = "http://localhost/DemoWebAPIProject/api/ControllerName/Method";

Uri requestUri = new Uri(url);  
dynamic dynamicObject = new ExpandoObject();
dynamicObject.UserName = "anorathod".ToString();
dynamicObject.Password = "password";

string json = "";
json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicObject);

var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));

string responJsonText = await response.Content.ReadAsStringAsync()

I hope that this will helpful in your project.

Enjoy !!!

:)

Useful links for .Net Developer


Useful links for .Net Developer



I found some links while doing development and R & D, I feel that I have to keep these links and articles, so I have started to store it here. I will keep updated this page regularly... 



1. Consume web api in MVC or windows application or Console Application

https://www.c-sharpcorner.com/UploadFile/2b876a/consume-web-service-using-httpclient-to-post-and-get-json-da/


2. Building An ASP.NET Core Application With Web API And Code First Development

3. Unity Dependency Injection 

3.1 ASP.NET MVC 4 Dependency Injection

3.2 Dependency Injection in ASP.NET Web API 2

3.3 C# – Using Unity for Dependency Injection in an ASP.NET MVC 4 Web API
https://myadventuresincoding.wordpress.com/2013/03/27/c-using-unity-for-dependency-injection-in-an-asp-net-mvc-4-web-api/

4. Swagger
4.1 For .Net Framework
Swagger integration in ASP.NET Web API project
https://code.msdn.microsoft.com/Swagger-integration-in-da408b29

4.2 For .Net Core
Add Swagger to ASP.NET Core 2.0 Web API
http://www.talkingdotnet.com/add-swagger-to-asp-net-core-2-0-web-api/

5. SQL Cache dependency
5.1 How to implement SQL Caching in ASP.NET (Poll based SQL Cache dependency)?
https://www.youtube.com/watch?v=RxbhQy8EIzM

5.2 How to use Push SQL Cache dependency in ASP.Net?
https://www.youtube.com/watch?v=nJFTfkr-U-Y

6. Create and publish a (nuget) package using Visual Studio (.NET Standard)
https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package-using-visual-studio

7. CQRS - Command-Query Responsibility Segregation

Introduction to CQRS
https://www.codeproject.com/Articles/555855/Introduction-to-CQRS

A Beginner's Guide To Implementing CQRS ES
https://github.com/Chinchilla-Software-Com/CQRS/wiki/A-Beginner's-Guide-To-Implementing-CQRS-ES

Part-1 Implementing CQRS/ES in ASP.NET
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-1-architecting-the-application/

Part-2 Implementing CQRS in .NET Part 2: Handling Commands and Events
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-2-handling-commands-and-events/

Part-3 Implementing CQRS in .NET Part 3: The Commands Interface
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-3-the-commands-interface/

Part-4 Implementing CQRS in .NET Part 4: More Events and Summary
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-4-more-events-and-summary/

8. Dependency Injection for Multiple Concrete Implementations of an Interface
http://www.intstrings.com/ramivemula/articles/dependency-injection-for-multiple-concrete-implementations-of-an-interface/

9. How to register and use Multiple Classes Implementing Same Interface in AutoFac?
https://www.codeproject.com/Tips/870246/How-to-register-and-use-Multiple-Classes-Implement



10. Introduction To ASP.NET WebAPI And Return Result In Different Formats (as XML or JSON)
https://www.c-sharpcorner.com/UploadFile/manas1/introduction-to-Asp-Net-webapi-and-returns-result-in-differe/


11. Recursive Select in C# and LINQ
https://bitlush.com/blog/recursive-select-in-c-sharp-and-linq

Recursive Hierarchical Joins in C# and LINQ
https://bitlush.com/blog/recursive-hierarchical-joins-in-c-sharp-and-linq

12. Azure Scheduler job collection
http://fabriccontroller.net/a-complete-overview-to-get-started-with-the-windows-azure-scheduler/

 https://github.com/Azure-Samples/scheduler-dotnet-getting-started

13. ASP.NET WEBFORM: DATATABLES JQUERY PLUGIN SERVER SIDE INTEGRATION
14. Online dotnet editor and testing - https://dotnetfiddle.net




If you have good links for .net development then please add in comment or contact me.

Cheers :)


ASP.Net Core API - HTTP Error 405.0 - Method Not Allowed

ASP.Net Core API - HTTP Error 405.0 - Method Not Allowed

I have created web api for delete in ASP.Net core C#, while I execute delete method in Postman (with method = DELETE ), I got below error...

HTTP Error 405.0 - Method Not Allowed

<ul>
 <li>The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request.</li>
 <li>A request was sent to the server that contained an invalid HTTP verb.</li>
 <li>The request is for static content and contains an HTTP verb other than GET or HEAD.</li>
 <li>A request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.</li>
</ul>

I found below solution after searching on internet and it is working fine for me.

I added below configuration in web.config file.

  <system.webServer>
     <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/>
   </modules>    
  </system.webServer

Hope, this will help to resolve your issue...

Enjoy !!!

:)

Azure Service Bus - Send & Receive Message - Topic in .Net Core

Azure Service Bus - Send & Receive Message - Topic in .Net Core




I have seen many examples to send and receive message of Azure Service Bus Topic in normal .Net framework, but I couldn't find correct code for .Net Core for the same to send and receive Azure Service Bus Topic.

Finally, I got solution and here is code for .Net Core C#.

Send Message

1. Create web api project with .Net core
2. Add Service Bus NuGet package, search for "Microsoft.Azure.ServiceBus"
3. Add NuGet package for "Newtonsoft.Json"
4. Create Test API controller
5. Write below code

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json; 
using System.Collections.Generic; 
using System.Text; 

namespace Demo.WebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Test")]
    public class TestController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post(dynamic model)
        {
            try
            {
                await Task.Run(() =>
                {
                    MessageFactory.SendMessagesAsync("TestTopic",
                           "testLable", 60, model);
                });
            }
            catch (Exception ex)
            {

                return Ok(ex.Message);
            }

            return Ok("Request submitted. ");
        }
        public static async Task SendMessagesAsync(string topicName, string lable, int minsTimeToLive, dynamic model, Dictionary<string, string> properties = null)
        {
            try
            {
                ITopicClient topicClient = new TopicClient(Config.ConnectionString, topicName);

                Message message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model)))
                {
                    ContentType = "application/json",
                    Label = "test",
                    TimeToLive = TimeSpan.FromMinutes(minsTimeToLive)
                };

                await topicClient.SendAsync(message);
            }
            catch (Exception exception)
            {

            }
        }
    } 
}


Test Web API 

1. Open Postman or restclient to test web api
2. URL :http://localhost/Demo.WebAPI/api/Test
2. Content-Type = application/json
3. Type: POST
4. Body as below,

 {
  "OrderDate":"02/22/2018",
  "CustomerId": 28,
  "Amount":35.23,
  "PaymentType":"Online",
  "Products":[
   {
    "ProductId":1,
    "Quantity":2,
    "Amount":10
   },
   {
    "ProductId":3,
    "Quantity":1,
    "Amount":15
   }
   ],
   "ShippingAddress":
   {
    "ShippingBy":"BlueDart",
    "CustomerName":"Test Customer",
    "Address":"Address 1",
  "Email":"test@test.com",
  "Phone":"1234567890"
   }
}

After posting request, you should get Status = 200 OK


Receive Message

1. Create .Net Core console application
2. Add reference using nuget for "Microsoft.Azure.ServiceBus" and "Newtonsoft.Json"
3. Write below code to receive azure service bus topic message

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json; 

namespace Demo.Service
{
    class Program
    {
        const string ServiceBusConnectionString = "Endpoint=sb://[NameSpace].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[SharedAccessKey]=";
        const string TopicName = "TestTopic";
        const string SubscriptionName = "TestSubscriber";
        static ISubscriptionClient subscriptionClient;

        static void Main(string[] args)
        {
            Console.WriteLine("Service started...");

            while (true)
            {
                MainAsync().GetAwaiter().GetResult();
            }

        }

        static async Task MainAsync()
        {
            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

            RegisterOnMessageHandlerAndReceiveMessages();

            await subscriptionClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandler)
            {
                // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };

            // Register the function that processes messages.
            subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var a = new MemoryStream(message.Body);

            var body = Encoding.UTF8.GetString(message.Body);

            Order order = JsonConvert.DeserializeObject<Order>(body);

            // Process the message.
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            // Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Id = { order.OrderId}");
            // Complete the message so that it is not received again.
            // This can be done only if the subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }

        static Task ExceptionHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}



Add classes to do business process....

public class Order
{
 public Guid OrderId { get; set; }
 public int CustomerId { get; set; }
 public string InvoiceNo { get; set; }
 public DateTime OrderDate { get; set; }
 public bool Payment { get; set; }
 public string OrderStatus { get; set; }
 public string PaymentType { get; set; }
 public decimal Amount { get; set; }

 public List<OrderItems> Products { get; set; }
 public ShippingAddress ShippingAddress { get; set; }
}
public class OrderItems
{
 public int ProductId { get; set; }
 public int Quantity { get; set; }
 public decimal Amount { get; set; }
}
public class ShippingAddress
{
 public Int64 ShippingId { get; set; }
 public Guid OrderId { get; set; }
 public DateTime ShippingDate { get; set; }
 public string ShippingBy { get; set; }
 public string CustomerName { get; set; }
 public string Address { get; set; }
 public string Email { get; set; }
 public string Phone { get; set; }
 public string ShippingStatus { get; set; }

}


Run console application and you will receive azure service bus message.



Enjoy !!!

:)

How to move or change data(.mdf) file or log(.ldf) file in SQL Server

How to move or change data(.mdf) file or log(.ldf) file in SQL Server



Sometime we need to change database data (.mdf) and log(.ldf) file for maintenance purpose or server transfer purpose. There are two ways to do this.


Way 1: Using SQL Script


-- First get physical file path of data (.mdf) and log (.ldf)
-- set active database which you want to get file path, here in my case I am using Demo database

USE Demo
GO

-- This will give physical file path of current database
sp_helpfile
GO

-- Now, Set database to single user mode and detach database with disconnecting active sessions

Use MASTER
GO

-- Set database to single user mode
ALTER DATABASE demo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO

-- Detach the database
sp_detach_db 'Demo'
GO

-- This will detach databse
EXEC SP_DETACH_DB @dbname = 'Demo', @skipchecks = 'true';


-- Now move .mdf or .ldf file on your preferred location 
-- Attach database with log file at new location (Here I have moved log file only, if you want to mo

USE master
GO

-- Now Attach the database
sp_attach_DB 'Demo', 
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\Demo.mdf',
'C:\FolderName\SQL\Demo_log.ldf'




Way 2: Using SQL Management Studio user interface


1. Right click on database which you want to move data or log file
2. Select Detach option
3. Select checkbox for "Drop Connections" in opened window and then click OK button

4. Now move .mdf or .ldf file on your preferred location 
5. Now you will not see your database in Object explorer
--- Attach database
6. Right click on database and select attach option
7. It will open a popup window
8. Click on "Add..." button in "Databases to attach" 
9. It will open another popup to select database name which you want to attach, here now you have to select data (.mdf) file and click OK button 
10. Now you will see database file location in first window popup, if it is not correct file location then select correct location 
11. Finally click on "OK" button, and your database will be attached in couple of seconds.


Hope, this will help to access your database from new location.

Enjoy !!!

:)

How to exit from single-user mode in SQL Server

How to exit from single-user mode in SQL Server



SQL Server opens multiple connections to serve data to client for their application.

So, you need to kill all opened connections before changing the access mode.

First, make sure the object explorer is pointed to a system database like master.

Second, execute a sp_who2 and find all the connections to database 'my_db'. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.

Third, open a new query window.

Then, below script will help to find all current process of sql server and kill and then it will set the database in MULTI_USER mode.


USE master
GO

DECLARE @kill varchar(max) = '';
SELECT @kill = @kill + 'KILL ' + CONVERT(varchar(10), spid) + '; '
FROM master..sysprocesses 
WHERE spid > 50 AND dbid = DB_ID('<Your_DB_Name>')
EXEC(@kill);
GO

SET DEADLOCK_PRIORITY HIGH
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

Hope, this will help to access your database.

Enjoy !!!

:)

Find row count of all tables in SQL

Find row count of all tables in SQL


Sometimes as a developer or application owner or management team wants to analyse database records, to easily identify database performance first we need to check that how many no of rows stored in database table. The after we can see other things for database performance like index, joins, outer join, conditions etc....

Below is the query which provides no of rows count of all tables of current database.

SELECT T.name AS [TABLE NAME], 
       I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
       INNER JOIN sys.sysindexes AS I 
               ON T.object_id = I.id 
                  AND I.indid < 2 
ORDER  BY I.rows DESC 

SELECT T.name      AS [TABLE NAME], 
       I.row_count AS [ROWCOUNT] 
FROM   sys.tables AS T 
       INNER JOIN sys.dm_db_partition_stats AS I 
               ON T.object_id = I.object_id 
                  AND I.index_id < 2 
ORDER  BY I.row_count DESC 


SELECT 
    t.NAME AS TableName,
    i.name as indexName,
    p.[Rows],
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%' AND
    i.OBJECT_ID > 255 AND   
    i.index_id <= 1
GROUP BY 
    t.NAME, i.object_id, i.index_id, i.name, p.[Rows]
ORDER BY 
     p.[Rows] desc 

Hope, this will help to review database and then you can take action for performance.

Enjoy !!!

:)