European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: How To Call Web API In Another Project From C#?

clock August 26, 2020 09:28 by author Peter

This article explains how to call a web API from another project using C# instead of making an Ajax call. I'm  creating a web API in MVC  in project1 and want to call this API in another project (like.MVC,Asp.net,.core etc) project but don't want to make any Ajax requests.
So let's see how to make a C# request for an Api Call.

Here I  am creating an API in MVC for getting  a statelist   in Project 1.
 public class StateController : ApiController 
   { 
[HttpGet] 
       [Route("api/State/StateList")] 
       public List<StateDto> StateList() 
       { 
           List<StateDto> StateList = new List<StateDto>(); 
           SqlConnection sqlConnection = new SqlConnection(); 
 
           string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString; 
           SqlCommand sqlCommand = new SqlCommand(); 
           sqlConnection.ConnectionString = connectionString; 
           sqlCommand.CommandType = CommandType.Text; 
           sqlCommand.CommandText = "Select * From lststate where deletedbyid is null"; 
           sqlCommand.Connection = sqlConnection; 
           sqlConnection.Open(); 
           DataTable dataTable = new DataTable(); 
           dataTable.Load(sqlCommand.ExecuteReader()); 
           sqlConnection.Close(); 
 
           if (dataTable != null) 
           { 
               foreach (DataRow row in dataTable.Rows) 
               { 
                   StateList.Add(new StateDto 
                   { 
                       Id = (int)row["id"], 
                       StateCode = row["Statecode"].ToString(), 
                       StateName = row["StateName"].ToString(), 
                       CompanyId = (int)row["Companyid"], 
                       CreatedDate = (DateTime)row["CreatedDate"] 
                   }); 
 
               } 
               return StateList; 
           } 
           else 
           { 
 
           } 
 
 
       } 


Project 2 where we want to call this API.
public List<StateDto> StateIndex() 
  { 
      var responseString = ApiCall.GetApi("http://localhost:58087/api/State/StateList"); 
      var rootobject = new JavaScriptSerializer().Deserialize<List<StateDto>>(responseString); 
      return rootobject; 
  } 


ApiCall.cs class 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace MaheApi.Dto 

    public static class ApiCall 
    { 
        public static string GetApi(string ApiUrl) 
        { 
 
            var responseString = ""; 
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl); 
            request.Method = "GET"; 
            request.ContentType = "application/json"; 
 
            using (var response1 = request.GetResponse()) 
            { 
                using (var reader = new StreamReader(response1.GetResponseStream())) 
                { 
                    responseString = reader.ReadToEnd(); 
                } 
            } 
            return responseString; 
 
        } 
 
        public static string PostApi(string ApiUrl, string postData = "") 
        { 
 
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl); 
            var data = Encoding.ASCII.GetBytes(postData); 
            request.Method = "POST"; 
            request.ContentType = "application/x-www-form-urlencoded"; 
            request.ContentLength = data.Length; 
            using (var stream = request.GetRequestStream()) 
            { 
                stream.Write(data, 0, data.Length); 
            } 
            var response = (HttpWebResponse)request.GetResponse(); 
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
            return responseString; 
        } 
  } 
}
 

Here we get data in StateIndex method



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: How To Write In Hindi (Or Another Font) In ASP.NET Core?

clock August 18, 2020 13:27 by author Peter

In this blog I am explaining how to read and write in the Hindi Language (or we can use any language as per our requirement).
 
Here I will explain how to write Hindi in an ASP.NET Core text box using Devlys_010 font. So please follow the below steps .
 
Step 1
Download Devlys_010 font in any format like .ttf , .woff, etc. You can download from here
This is a zip file so you can extract it in the folder.
 
Step 2
Open your Asp.Net core project and create a new folder under css. Give the folder a name like Fonts.
 
Under the Fonts folder paste the downloaded font which we have already exctracted. And now create one css file and give it the name font.css

Here you can see I have added a screenshot. I have pasted a ttf format font and created a font.css under a newly-created folder, Fonts.
 
Step 3
Now open font.css in your editor. Now we add font in our project using @font-face.
 
So write the css code in your font.css like below:
    @font-face { 
        font-family: 'Devlys_010'; 
        src: local('Devlys_010'),url('./Devlys_010.ttf') format('truetype'); 
    } 

Step 4

Now create a new class css in font.css below @font-face and add a font family which we have using @font-face.
    .hFont { 
        font-family: 'Devlys_010' !important; 
    } 

Now you can see all css code in font.css
    @font-face { 
        font-family: 'Devlys_010'; 
        src: local('Devlys_010'),url('./Devlys_010.ttf') format('truetype'); 
    } 
     
    .hFont { 
        font-family: 'Devlys_010' !important; 
    }
 

Here I have added .hFont class -- you can change this name.
 
Step 5
Now go to your cshtml page where you want to write your Hindi font. This means If you have used input type text then just add class hFont like below.
 
And add css in header for getting our css code.
    <link href="~/css/fonts/font.css" rel="stylesheet" /> 

Now add css class for writing Hindi font. See in the below code I have added hFont class in input type.
    <input asp-for="@Model.AdminMaster.AdminName" class="form-control hFont" id="txtAdminName" /> 

    OR
    <input type = "text" class="form-control hFont" id="txtAdminName" /> 

Note

You can use any other font also just add font in css and use it. Also use any language font like Gujarati, Marathi, Urdu or any other language.  

 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: HTTP Requests Using IHttpClientFactory

clock August 11, 2020 13:14 by author Peter

The very first time Microsoft launched the HttpClient in .NET Framework 4.5, it became the most popular way to consume a Web API HTTP request, such as Get, Put, Post, and Delete in your .NET server-side code. However, it has some serious issues, for example, disposing of the object like HttpClient object doesn’t dispose of the socket as soon as it is closed. There are also too many instances open so that it affecting the performance and private HttpClientor shared HttpClient instance not respecting the DNS Time.

When Microsoft released dotnet core 2.1, it introduced HttpClientFactory that solves all these problems.

Basically, it provides a single place (central place) for configuration and consumption HTTP Verbs Client in your application IHttpClientFactory offers the following benefits,

  Naming and configuring HttpClient instances.
  Build an outgoing request middleware to manage cross-cutting concerns around HTTP requests.
  Integrates with Polly for transient fault handling.
  Avoid common DNS problems by managing HttpClient lifetimes.

There are the following ways to use IHttpClientFactory.
  Direct HttpClientFactory
  Named Clients
  Typed Clients

We will see an example one by one for all 3 types...

Direct HttpClientFactory

In dotnet core, we have Startup.cs class, and inside this class, we have the ConfigureService method. In this method we use middleware, where we inject some inbuilt/custom pipeline.

So for HttpClientFactory we need to register HttpClient like below:
services.AddHttpClient(); 

Now the question is how to use this in our API controller.

So here is the example of Direct HttpClientFactory use in controller:
  public class HttpClientFactoryController: Controller { 
      private readonly IHttpClientFactory _httpClientFactory; 
      public HttpClientFactoryController(IHttpClientFactory httpClientFactory) { 
              _httpClientFactory = httpClientFactory; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          var client = _httpClientFactory.CreateClient(); 
          client.BaseAddress = new Uri("http://api.google.com"); 
          string result = await client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Here in this example we have pass IHttpClientFactory is a dependency injection and directly use _httpClientFactory.CreateClient();

This example is better in this situation when we need to make a quick request from a single place in the code

Named Clients
Just above I have explained how to register the middleware in startup.cs class in configureService method for HttpClient same we can use for Named Clients as well, but this is useful when we need to make multiple requests from multiple locations.

We can also do some more configuration while registering, like this:
  services.AddHttpClient("g", c => 
  { 
     c.BaseAddress = new Uri("https://api.google.com/"); 
     c.DefaultRequestHeaders.Add("Accept", "application/json"); 
  }); 


Here in this configuration, we use two parameter names and an Action delegate taking a HttpClient

We can use the named client in the API controller in this way:
  public class NamedClientsController: Controller { 
      private readonly IHttpClientFactory _httpClientFactory; 
      public NamedClientsController(IHttpClientFactory httpClientFactory) { 
              _httpClientFactory = httpClientFactory; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          var client = _httpClientFactory.CreateClient("g"); 
          string result = await client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Note
"g" indicates names client that I use in during registration and also call from the API action method

Typed Clients

A types client provides the same capabilities as named clients but without the need to use strings as keys in configuration. Due to this it also provide IntelliSense and compiler help when consuming clients. It provides a single location to configure and interact with a particular httpclient

It works with dependency injection and can be injected where required in the application.

A typed client accepts an HttpClient parameter in its constructor,

We can see here by an example that I have defined custom class for httpclient:
  public class TypedCustomClient { 
      public HttpClient Client { 
          get; 
          set; 
      } 
      public TypedCustomClient(HttpClient httpClient) { 
          httpClient.BaseAddress = new Uri("https://api.google.com/"); 
          httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); 
          httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); 
          Client = httpClient; 
      } 
  }

Now we can register this as a typed client using in this way in startup.cs clss under configureService method.

  services.AddHttpClient<TypedCustomClient>(); 

Now this time we see how we can use it in API controller,
  public class TypedClientController: Controller { 
      private readonly TypedCustomClient _typedCustomClient; 
      public TypedClientController(TypedCustomClient typedCustomClient) { 
              _typedCustomClient = typedCustomClient; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          string result = await _typedCustomClient.client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Now we have learned all three types to use.

But here is one better way to use typeclient using an interface.

We will create an interface and encapsulate all the logic here, that also helps in writing UTC as well

Here is an example:
  public interface ICustomClient 
  { 
    Task<string> GetData(); 
  } 


Now inherit this interface in custom class
  public class TypedCustomClient: ICustomClient { 
      public HttpClient Client { 
          get; 
          set; 
      } 
      public TypedCustomClient(HttpClient httpClient) { 
          httpClient.BaseAddress = new Uri("https://api.google.com/"); 
          httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); 
          httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); 
          Client = httpClient; 
      } 
  }


Register this in startup class:
  services.AddHttpClient<ICustomClient, TypedCustomClient>(); 

  public class CustomController: Controller { 
      private readonly ICustomClient _iCustomClient; 
      public ValuesController(ICustomClient iCustomClient) { 
              _iCustomClient = iCustomClient; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          string result = await iCustomClient.GetData(); 
          return Ok(result); 
      } 
  }


Here we are using the interface for the same, so it would be good to go for repository mock.

HostForLIFE.eu ASP.NET Core 3.1.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Consume OData Feed With C# Client Application

clock August 4, 2020 13:04 by author Peter

OData represents Open Data Protocol, an OASIS standard initiated by Microsoft in  2007. This defines the best practices for the consumption of data and building with quarriable REST APIs.

The difference between Odata and REST API is, Odata is a specific protocol and REST is an architectural style and design pattern. Using REST we can request and get data using HTTP calls. OData is a technology that uses REST to consume and build data.

I expect readers of this article to have some knowledge about OData queries. But, to make it simple, this protocol gives the power to the client to query the data on the database using a query string of REST API requests. It also helps to make the data more secure by not exposing any database related information as well as limiting the data to the outside world.

In general, we need to build the Odata enabled web service using any popular programming language which takes care of building URLs, verbs, and their requests and expected responses accordingly. Now, at the client end to consume these Odata REST APIs, we need to have metadata that contains the request type as well response types to build the concrete classes or we need to create a service proxy class.

This article is about how clients can consume existing Odata REST API using C#. So, let's start.

Simple.Odata.Client is a library that supports all Odata protocol versions and can be installed from the NuGet package and supports both .NET Framework and .NET Core latest versions.

Initializing Client Instance
To communicate with Odata REST API, Simple.Odata.Client library has some predefined class called ODataClient. This class accepts service URL with some optional settings to do a seamless communication with Odata service.
var client = new ODataClient("https://services.odata.org/sferp/"); 

If you want to log all the requests and responses from this client object to the Console, we can have additional optional settings as below.
var client = new ODataClient(new ODataClientSettings("https://services.odata.org/sferp/") 

    OnTrace = (x, y) => Console.WriteLine(string.Format(x, y)) 
}); 


Building the Typed Classes
This library doesn't help you to build any Typed classes of the responses (tables/views) from the given service as we do this with the entity framework. To build the typed DTO classes, we need to fetch the metadata from the configured Odata web service by appending $metadata at the end of the base URL as follows.
https://services.odata.org/sferp/$metadata

Metadata will be displayed in XML format, we need to identify the elements for the table and their columns with datatypes to create classes accordingly for each table.

Retrieving Data Collection
As we did with initializing the communication to the service, now we need to fetch some data from the service. For example, the following statement will fetch all the data in the table Articles with the help of Odata protocol.
var articles = await client      
                    .For<Article>() 
                    .FindEntriesAsync(); 

Here, the client is an object of the ODataClient class.

There is a problem with the above statement. If this Article table has millions of records, your HTTP call will block or return a timeout exception and you cannot achieve your requirement. To avoid such situations, we need to use annotations defined in this library.

Annotations will help to minimize the load on the network by limiting the records in a single fetch. Along with records it also sends the link to fetch the next set of records so that this can be fetched until all records get fetched from the Articles table.
var annotations = new ODataFeedAnnotations(); 
var article = await client 
    .For<Article>() 
    .FindEntriesAsync(annotations) 
    .ToList(); 
while (annotations.NextPageLink != null) 

    article.AddRange(await client 
        .For<Article>() 
        .FindEntriesAsync(annotations.NextPageLink, annotations) 
    ); 


In the above code, the first call will fetch a set of 8 records (by default or it can decide as per network speed to avoid timeout exception) along with nextpagelink property. Just this property will set the URL of OData web service to fetch the next page of records.

Include Associated Data Collections

So far, we fetched the table directly but we can also have the requirement to fetch or include in terms of entity framework all their constraint key records as a response to the request. To achieve it, our library provides an Expand() method to declare all included tables' information so that the OData API will associate it and map to the response object while sending the response.
var articles = await client 
    .For<Article>() 
    .Expand(x => new { x.Ratings, x.Comments }) 
    .FindEntryAsync(); 


In the above example, the system will fetch all  information along with ratings and comment data as part of each article record by joining it accordingly at the web service end.

Authentication
So far, we have understood how to configure and consume the data from the existing Odata service API. Now, in real-time to make their data secure, API should authenticate the request as well as the requested client. To do so, we need to generate a token based on the credentials shared by API services.

The following are the codebases to prepare the ODataClient object by generating the token based on given credentials.
private ODataClient GetODataClient() 
        { 
            try 
            { 
                string url = _config.GetSection("APIDetails:URL").Value; 
                String username = _config.GetSection("APIDetails:UserName").Value; 
                String password = _config.GetSection("APIDetails:Password").Value; 
 
                String accessToken = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); 
 
                var oDataClientSettings = new ODataClientSettings(new Uri(url)); 
                oDataClientSettings.BeforeRequest += delegate (HttpRequestMessage message) 
                { 
                    message.Headers.Add("Authorization", "Basic " + accessToken); 
                }; 
 
                var client = new ODataClient(oDataClientSettings); 
 
                Simple.OData.Client.V4Adapter.Reference(); 
 
                return client; 
            } 
            catch(Exception ex) 
            { 
                LogError("", $"Failed to connect API Services : {ex.Message}"); 
            } 
 
            return null; 
        } 


In the above code, we are getting URL, Username, and password from appsettings.json file and then creating a Basic token by converting the username and password strings. Once the token is generated, we are sending this token in the Authorization header by using the ODataClientSettings object and creating the ODataClient object.

Once this ODataClient object is created, we can request the data from OData web services as discussed above.

I hope this article helped you to understand how C# based client applications can be created and used to consume existing OData API services.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in