Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, November 20, 2022

Resilient HTTP client with Polly and Flurl

Having a resilient HTTP client is a huge benefit if your application depends on third-party API calls. This will helps to avoid transient errors. These errors may be temporary and will be solved quickly. Most of the time these errors occurred due to network issues. 

The below example demonstrates how to implement a HttpClient with multiple retries using Polly and Flurl

Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, Rate-limiting, and Fallback in a fluent and thread-safe manner.

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library.

Creating the Retry Policy 

This IsWorthRetrying method will check returned HTTP status is worth of retry.

And I used  OnRetryAsyncFunc to log the retry information. 


Use the Retry Policy

Example usage and results

var result = await apiClient.GetAsync("https://httpstat.us/503").ConfigureAwait(false);
Console.WriteLine($"Hello, World! {result}");
 

Full implementation 

Friday, December 31, 2021

Configure HttpClient to consume windows authenticated NTLM service in ASP.NET Core

Recently I migrated a system to Linux based docker platform from IIS environment. I had a service call to some other API that has NTLM authentication.

That was working fine by just setting Credentials to HttpClient when hosted in IIS. 

But when you run dotnet app in Linux you do not have that windows authentication fancy feature. 

Below is how I managed to configure HttpClient with NTLM Authentication using CredentialCache.


Monday, May 24, 2021

How to update only one field using EF Core?

This method is useful When you are trying to update some record in the table while you are not tracking that entity. 

If you are using tracking then EF is smart enough to update only certain fields. 

Below is the code.


Thursday, December 31, 2020

Run Docker With Visual Studio in Corporate Machine with VPN or Firewall

I was trying to run some API using docker with visual studio docker tools. 

Idea behind that is I will able to attach docker process to visual studio and do some tweaks very easily using visual studio docker tools. (Haha I am lazy).

But unfortunately, my company laptop is heavily protected with no Administrator, a bunch of security tools, and a VPN also. 

Some errors I got with various tries.

Debugger path 'C:\User\...\vs2017u5' for DockerFile is invalid. 

One or more errors occurred.

Failed to launch debug adapter. Additional information may be avaliable in the output window.

Building the project is successful but errors out on launch.

The program '' has exited with code -1 (0xffffffff).

\vsdbg\vs2017u5' for Dockerfile.... Container.targets Dockerfile is invalid

In order to work this normally, there is a power shell script provided by Microsoft to download software, .NET Core Debugger from Microsoft, aka vsdbg.

https://aka.ms/getvsdbgsh

This will download a zip file and will be created in the below directory with debugger files. 

C:\Users\Chathuranga\vsdbg\vs2017u5.


With the firewall and VPN, my laptop couldn't be able to do this in a proper way. 


Time to read what is inside of getvsdbg.sh.


You will find a method like this download_and_extract()

This method constructs the download URL.


url="https://vsdebugger.azureedge.net/vsdbg-${target}/${vsdbgCompressedFile}"


Time to determine parameters.


Check this method in SH file, 


set_vsdbg_version

        latest)

            __VsDbgVersion=16.8.11013.1

            ;;

        vs2019)

            __VsDbgVersion=16.8.11013.1

            ;;

        vsfm-8)

            __VsDbgVersion=16.8.11013.1

            ;;

        vs2017u5)

            __VsDbgVersion=16.8.11013.1

            ;;

        vs2017u1)

            __VsDbgVersion="15.1.10630.1"


Decide what is the version you want from this. 


I selected 16.8.11013.1 because I have vs 2109 16.8.3


Next, decide which vsdbg configuration you want. 

ex: debian.8-x64, linux-musl-x64, linux-x64.


In this case, I selected linux-x64, the reason is I wanted to debug. 

If you just want to run then select linux-musl-x64, it is the runtime


The final URL will be like below

https://vsdebugger.azureedge.net/vsdbg-16-8-11013-1/vsdbg-linux-x64.zip


Download this and extract it to C:\Users\XXX\vsdbg\vs2017u5.

Create vsdbg folder if it does not exist. and keep in mind that do not extract to a subfolder.


Ok, that is it. Enjoy debugging.

Saturday, February 22, 2020

Dynamic dependency injection .NET Core WebAPI

It is being a long time after my last blog post here. I already moved to .NET Core from .NET Framework almost two years ago. And I must say it has been made my life easier. Well I can say I am intrigued with in build dependency injection. Recently I got a requirement that needs two different implementations for single interface.

Classes : ProcessExcelFiles.cs
               ProcessCsvFiles.cs

Interface : IFileUploadContentProcess.cs

Purpose of this two classes are process uploaded xlsx file or csv file.

First register class files as your desired way.

Then use a lambda function to parameterize interfaces to implementation register.

How to use:

Tuesday, March 11, 2014

Clone objects C#

Cloning is a matter between copy object and copy its references. There are two types of cloning, deep clone and shallow clone. If you copy only references it’ll call shallow copy. If you copy referenced objects it’ll call deep copy.
Shallow copy:

Deep copy:
There are two ways of doing this.
1. Use the copy constructor (a good practice)
2. Using ICloneable interface
Manual way Using memberwiseclone

Wednesday, March 6, 2013

Convert object into DataTable C#

Recently I got a requirement in a project to convert own type of object to DataTable. Here I am sharing my code with you.

Steps

1. Create datatable and give a name
2. Create Column Names
3. Create a Data Row
4. Add Data in to DataRow
5. Add DataRow to DataTable
Thats it...
Here some Extended Method to how to use this method
https://github.com/cbjpdev/DataTableX

Tuesday, June 5, 2012

Canny and Sobel Edge Detection in C#

Sobel and Canny are major edge detection algorithms in Image Processing. Here I have implemented those algorithms using c#.

Download the source code from here.

Canny Edge Detection (click to zoom)

Sobel Edge Detection (click to zoom)




You can improve the program by using optimization methods such as threading and loop optimization.

Wednesday, August 17, 2011

Running an Executable and Collecting the Output using C#

Sometimes you may need in the middle of a C# application you want to run an executable and collect the output.  Below sample of code will do what you want.. 

1. Simple method:

 

Process P = Process.Start("eyeDetect.exe", "hello1.jpg haarcascade_frontalface_alt.xml haarcascade_eye.xml");
P.StartInfo.UseShellExecute = false;
P.WaitForExit();
int result = P.ExitCode;
Console.WriteLine("Here is my result " + result);
Console.ReadLine(); 

2. Descriptive Method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {         
        static void Main(string[] args)
        { 
            StringBuilder Output = new StringBuilder(); 
            using (Process proc = new Process())
                {
                    proc.StartInfo.FileName = "eyeDetect.exe";
                    proc.StartInfo.Arguments = "hello1.jpg haarcascade_frontalface_alt.xml haarcascade_eye.xml";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.OutputDataReceived += (o, e) => Output.Append(e.Data).Append(Environment.NewLine);
                    proc.Start();
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();
                    proc.WaitForExit();
                    int ExitCode = proc.ExitCode;
                }
                Console.WriteLine(Output);
                Console.ReadLine();
        }
    }
}