Friday, November 5, 2021

PHP Redirect based on geolocation and use Proxy for location detection

 As we discussed how to use proxy with http requests made, here is a complete solution to make a dynamic request redirection based on client's country.

 <?php  
 try {  
   if (session_status() === PHP_SESSION_NONE) {  
     session_start();  
   }   
 $q='';  
 $redirectUrl='';  
 $country = '';  
 $country = $_SESSION["country"];  
 if (isset($_GET['q'])) {  
   $q = $_GET['q'];  
 } else {  
   header("https://yoursite.com");   
 }  
 if($country=='' || $country == null){  
   $url="http://ip-api.com/json/".getUserIP();  
   $auth = base64_encode('username:password');  
   $aContext = array(  
     'http' => array(  
       'proxy'      => 'tcp://yourproxyserver.io:31112',  
       'request_fulluri' => true,  
       'header'     => "Proxy-Authorization: Basic ".$auth,  
     ),  
   );  
   $cxContext = stream_context_create($aContext);  
   $sFile = file_get_contents($url, False, $cxContext);  
   $arrIpInfo=json_decode($sFile);  
   $country = strtolower($arrIpInfo->country);  
   $_SESSION["country"] = $country;  
 }  
   if($country=="argentina") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="armenia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="australia") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="austria") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="azerbaijan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="belarus") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="belgium") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="brazil") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="canada") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="chile") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="columbia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="denmark") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="finland") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="france") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="georgia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="germany") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="hong kong") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="india") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="indonesia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="ireland") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="italy") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="japan") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="kazakhstan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="kyrgyzstan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="luxemburg") $redirectUrl = "https://redirectionsite.com/s706?q=".$q;  
   else if($country=="malaysia") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="mexico") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="moldova") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="netherlands") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="new zealand") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="norway") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="peru philippines") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="russia") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="singapore") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="spain") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="sweden") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="switzerland") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="taiwan") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="tajikistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="thailand") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="turkmenistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="uk") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="united kingdom") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="united states") $redirectUrl = "https://redirectionsite.com/s533?q=".$q;  
   else if($country=="uzbekistan") $redirectUrl = "https://redirectionsite.com/s564?q=".$q;  
   else if($country=="venezuela") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else if($country=="vietnam") $redirectUrl = "https://redirectionsite.com/s545?q=".$q;  
   else $redirectUrl = "https://redirectionsite.com/s901?q=".$q;  
      header("Location: ".$redirectUrl);    
 }  
 catch(Exception $e) {  
   echo 'Message: ' .$e->getMessage();  
  }  
 function getUserIP() {  
   $ipaddress = '';  
   if (isset($_SERVER['HTTP_CLIENT_IP']))  
     $ipaddress = $_SERVER['HTTP_CLIENT_IP'];  
   else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))  
     $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];  
   else if(isset($_SERVER['HTTP_X_FORWARDED']))  
     $ipaddress = $_SERVER['HTTP_X_FORWARDED'];  
   else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))  
     $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];  
   else if(isset($_SERVER['HTTP_FORWARDED_FOR']))  
     $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];  
   else if(isset($_SERVER['HTTP_FORWARDED']))  
     $ipaddress = $_SERVER['HTTP_FORWARDED'];  
   else if(isset($_SERVER['REMOTE_ADDR']))  
     $ipaddress = $_SERVER['REMOTE_ADDR'];  
   else  
     $ipaddress = 'UNKNOWN';  
   return $ipaddress;  
 }  
 ?>  
redirectionsite.com

This is where the actual redirection happens. based on it's s code (ex: s564) it redirects to the country specific location.

Happy coding....


Wednesday, November 3, 2021

PHP - How to use proxy to send http requests

 Sometimes we send http requests and need to send it through a proxy server. Here is the way how we can do it in PHP

 $url="http://ip-api.com/json/1.1.1.1";  
 $auth = base64_encode('username:password');  
 $aContext = array(  
   'http' => array(  
     'proxy'      => 'tcp://proxy.server.io:31112',  
     'request_fulluri' => true,  
     'header'     => "Proxy-Authorization: Basic ".$auth,  
   ),  
 );  
 $cxContext = stream_context_create($aContext);  
 $sFile = file_get_contents($url, False, $cxContext);  
 echo $sFile;  

Happy coding...


Thursday, October 28, 2021

Getting Geo Location free of charge.. in C# ASP.

 Sometimes we need to check the users geolocation from server side for various purposes. Such as link building for region wise. 

This is a free service that you can use for your application which isn't commercial.

you can browse more info here http://ip-api.com

lets see how we implement it.


 string jsonCountry = Session["country"] != null ? Session["country"].ToString() : string.Empty;  
         if (!string.IsNullOrEmpty(jsonCountry))  
         {  
           location = new JavaScriptSerializer().Deserialize<Location>(jsonCountry);  
         }  
         else  
         {  
           string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
           if (string.IsNullOrEmpty(ipAddress))  
           {  
             ipAddress = Request.ServerVariables["REMOTE_ADDR"];  
           }  
           string urlLocation = "http://ip-api.com/json/" + ipAddress;  
           using (WebClient client = new WebClient())  
           {   
             string json = client.DownloadString(urlLocation);  
             Session["country"] = json;  
             location = new JavaScriptSerializer().Deserialize<Location>(json);              
           }  
         }  


Here you can see we use session to store location data to prevent unwanted http calls to the service provider. Location is a class that we use to deserialize the object.

   public class Location  
   {  
     public string status { get; set; }  
     public string country { get; set; }  
     public string countryCode { get; set; }  
     public string region { get; set; }  
     public string regionName { get; set; }  
     public string city { get; set; }  
     public string zip { get; set; }  
     public double lat { get; set; }  
     public double lon { get; set; }  
     public string timezone { get; set; }  
     public string isp { get; set; }  
     public string org { get; set; }  
     public string @as { get; set; }  
     public string query { get; set; }  
   }  

If you want you can add a proxy to your webclient as below

             WebProxy wp = new WebProxy();
             wp.Address = new Uri(string.Format("{0}:{1}", "http://proxy.something.io", "22222"));  
             wp.Credentials = new NetworkCredential("username", "password");  
             client.Proxy = wp;  

Hopefully this works.

Happy coding.

Thursday, September 9, 2021

Wordpress Rest API and C#

Wordpress has introduced it's rest API for developers to create posts and many more... you can visit their documentation from here.

https://developer.wordpress.org/rest-api/

Today let's see how we can work with it. We use postman to do the work. 

First we need to install the JSON Basic Authentication plugin. (https://github.com/WP-API/Basic-Auth)

And then we can call the API normally. The authentication has to be provided with the format of username:password and it has to be base64 encrypted.

Lets see how we can list posts.


 var client = new RestClient("https://wordpress-ASDASD90809.com/wp-json/wp/v2/posts");  
 client.Timeout = -1;  
 var request = new RestRequest(Method.GET);  
 request.AddHeader("Authorization", "Basic BASE64ENC(UNAME:PASSWORD)");  
 request.AddHeader("Content-Type", "application/x-www-form-urlencoded");  
 request.AddParameter("page", "1");  
 request.AddParameter("per_page", "100");  
 IRestResponse response = client.Execute(request);  
 Console.WriteLine(response.Content);  

You can get the results as follows.


Also you can create categories, create posts list posts and do many more things with the API.

Let's see a bit more details in next post. 

Until that, happy coding...



Friday, July 9, 2021

Blazor cache management using IMemoryCache

Hi Guys, In depth article about Blazor caching can be found here. We here, will look how to implement it.

Suppose you have a service called CardService that delivers a set of card objects as requested. So we need to cache the data on that methods. Let's see how we can do it.

Here we use the IMemoryCache interface in CardService constructor.

     private IMemoryCache _memoryCache;  
     public CardService(IMemoryCache memoryCache)  
     {  
       _memoryCache = memoryCache;        
     }  

Now we can use the _memoryCache to deal with the cache as below;

     public Task<Keyword[]> GetCardSimilarAskKeywords(string url,string tablePrefix)  
     {  
       string key = "GetCardSimilarAskKeyword"+ url;  //cache key
       var encodedCache = _memoryCache.Get(key);  //get value 
       if (encodedCache == null)  // if value null then get it from DB
       {  
         var options = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(365)).SetAbsoluteExpiration(TimeSpan.FromDays(365));  
         List<Keyword> caList = new List<Keyword>();  
         //Get Keyword list from the data of yours.  
         _memoryCache.Set(key, caList, options);  
         GC.Collect();  
         return Task.FromResult(caList.ToArray());  
       }  
       else  
       {  //if value is in cache, convert and return
         var o = _memoryCache.Get(key);  
         IEnumerable e = o as IEnumerable;  
         var ka = e.OfType<Keyword>().ToList();  
         GC.Collect();  
         return Task.FromResult(ka.ToArray());  
       }  
     }  

In your razor page, inject the service on top

 @inject CardService service  

And now we use the method,

 var kwd = await service.GetCardSimilarAskKeywords("url","prefix");  

Now you need to add the following code to the startup.cs

 services.AddSingleton<CardService>();  

It's done. Lets look at some important options of "MemoryCacheEntryOptions"

We can set the expiration of cache as below;

// keep item in cache as long as it is requested at least
// once every 5 minutes...
// but in any case make sure to refresh it every hour
new MemoryCacheEntryOptions()
  .SetSlidingExpiration(TimeSpan.FromMinutes(5))
  .SetAbsoluteExpiration(TimeSpan.FromHours(1))

In above example, I have set the cache expiration to 365 days. Which means it will recycle once a year. 

Hope you can enjoy the coding...

Anything to know? Post a comment. Thanks.

Tuesday, July 6, 2021

Getting country of the user without navigator object

 Getting the country in browser require user to approve. But what if the user doesn't approve. Here is a way to get users location using JQuery.

       $.ajax({          
         url: "https://geolocation-db.com/jsonp/ee33e930-db78-11eb-9218-377a93e0222e",  
         jsonpCallback: "callback",  
         dataType: "jsonp",  
         success: function (location) {  
           $('#country').html(location.country_name);  
           $('#state').html(location.state);  
           $('#city').html(location.city);  
           $('#latitude').html(location.latitude);  
           $('#longitude').html(location.longitude);  
           $('#ip').html(location.IPv4);  
         }  
       });  

More details : https://geolocation-db.com/documentation

Happy coding..

Friday, July 2, 2021

C# ASP.Net Playing with HTML - Automatic Tag Closer

 When we have to deal with HTML strings and sometimes have to split it for Read More text. So, there is a posibility to have open tags which result the total page to collapse. Therefore we might need an automatic tag closer for a splitted HTML string. The following class would do the needful.


   public class TagCloser  
   {  
     private Stack<string> _openTags = new Stack<string>();  
     private string _html;  
     private int _currentCharIndex;  
     private bool Eof  
     {  
       get { return _currentCharIndex == _html.Length - 1; }  
     }  
     private int _pendingTagNameStartIndex;  
     private string _pendingTagName;  
     private int _currentEndTagStartIndex;  
     private State _state;  
     public string CloseTags(string html)  
     {  
       if (string.IsNullOrEmpty(html))  
         return html;  
       _html = html;  
       _currentCharIndex = -1;  
       while (!Eof)  
       {  
         var ch = ReadNext();  
         if (_state == State.InTagName)  
         {  
           // Self closing  
           if (ch == '/' && PeekNext() == '>')  
           {  
             ReadNext();  
             _state = _openTags.Count > 0 ? State.InsideTag : State.None;  
             continue;  
           }  
           if (ch == ' ' || ch == '>')  
           {  
             _pendingTagName = _html.Substring(_pendingTagNameStartIndex, _currentCharIndex - _pendingTagNameStartIndex);  
           }  
           if (ch == ' ')  
           {  
             _state = State.InAttributes;  
           }  
           else if (ch == '>')  
           {  
             _openTags.Push(_pendingTagName);  
             _state = State.InsideTag;  
           }  
         }  
         else if (_state == State.InsideTag)  
         {  
           if (ch == '<' && PeekNext() == '/')  
           {  
             _currentEndTagStartIndex = _currentCharIndex;  
             ReadNext();  
             _state = State.InEndTag;  
             continue;  
           }  
           if (ch == '<')  
           {  
             _state = State.InTagName;  
             _pendingTagNameStartIndex = _currentCharIndex + 1;  
             continue;  
           }  
         }  
         else if (_state == State.InEndTag)  
         {  
           if (ch == '>')  
           {  
             _openTags.Pop();  
             _state = _openTags.Count > 0 ? State.InsideTag : State.None;  
           }  
         }  
         else  
         {  
           if (ch == '<')  
           {  
             _state = State.InTagName;  
             _pendingTagNameStartIndex = _currentCharIndex + 1;  
             continue;  
           }  
         }  
       }  
       // Broken start tag  
       if (_state == State.InTagName || _state == State.InAttributes)  
       {  
         _html = _html.Substring(0, _pendingTagNameStartIndex - 1);  
       }  
       // Broken end tag  
       else if (_state == State.InEndTag)  
       {  
         _html = _html.Substring(0, _currentEndTagStartIndex);  
       }  
       var sb = new StringBuilder();  
       sb.Append(_html);  
       while (_openTags.Count > 0)  
       {  
         var tag = _openTags.Pop();  
         sb.Append("</" + tag + ">");  
       }  
       return sb.ToString();  
     }  
     private char ReadNext()  
     {  
       return Eof ? '\0' : _html[++_currentCharIndex];  
     }  
     private char PeekNext()  
     {  
       return Eof ? '\0' : _html[_currentCharIndex + 1];  
     }  
     enum State  
     {  
       None, InTagName, InAttributes, InsideTag, InEndTag  
     }  
   }  

And you may refer it as below;

 new TagCloser().CloseTags(c.headerLinkDisplay160.Trim())  

Happy coding...

Thursday, July 1, 2021

Autocomplete with Large Dataset - ASP.Net

 Friends, You might have used jquery autocomplete to a search field in your website. But have you ever wondered to deal with large datasets? JQuery auto complete makes the page unresponsive with it's search if there are lot of data to filter. Below is the solution to that. 

Original post for this can be found here


     function autocomplete(inp, arr) {  
       /*the autocomplete function takes two arguments,  
       the text field element and an array of possible autocompleted values:*/  
       var currentFocus;  
       /*execute a function when someone writes in the text field:*/  
       inp.addEventListener("input", function (e) {  
         var a, b, i, val = this.value;  
         /*close any already open lists of autocompleted values*/  
         closeAllLists();  
         if (!val) { return false; }  
         currentFocus = -1;  
         /*create a DIV element that will contain the items (values):*/  
         a = document.createElement("DIV");  
         a.setAttribute("id", this.id + "autocomplete-list");  
         a.setAttribute("class", "autocomplete-items");  
         /*append the DIV element as a child of the autocomplete container:*/  
         this.parentNode.appendChild(a);  
         /*for each item in the array...*/  
         for (i = 0; i < arr.length; i++) {  
           /*check if the item starts with the same letters as the text field value:*/  
           if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {  
             /*create a DIV element for each matching element:*/  
             b = document.createElement("DIV");  
             /*make the matching letters bold:*/  
             b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";  
             b.innerHTML += arr[i].substr(val.length);  
             /*insert a input field that will hold the current array item's value:*/  
             b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";  
             /*execute a function when someone clicks on the item value (DIV element):*/  
             b.addEventListener("click", function (e) {  
               /*insert the value for the autocomplete text field:*/  
               inp.value = this.getElementsByTagName("input")[0].value;  
               /*close the list of autocompleted values,  
               (or any other open lists of autocompleted values:*/  
               closeAllLists();  
             });  
             a.appendChild(b);  
           }  
         }  
       });  
       /*execute a function presses a key on the keyboard:*/  
       inp.addEventListener("keydown", function (e) {  
         var x = document.getElementById(this.id + "autocomplete-list");  
         if (x) x = x.getElementsByTagName("div");  
         if (e.keyCode == 40) {  
           /*If the arrow DOWN key is pressed,  
           increase the currentFocus variable:*/  
           currentFocus++;  
           /*and and make the current item more visible:*/  
           addActive(x);  
         } else if (e.keyCode == 38) { //up  
           /*If the arrow UP key is pressed,  
           decrease the currentFocus variable:*/  
           currentFocus--;  
           /*and and make the current item more visible:*/  
           addActive(x);  
         } else if (e.keyCode == 13) {  
           /*If the ENTER key is pressed, prevent the form from being submitted,*/  
           e.preventDefault();  
           if (currentFocus > -1) {  
             /*and simulate a click on the "active" item:*/  
             if (x) x[currentFocus].click();  
           }  
         }  
       });  
       function addActive(x) {  
         /*a function to classify an item as "active":*/  
         if (!x) return false;  
         /*start by removing the "active" class on all items:*/  
         removeActive(x);  
         if (currentFocus >= x.length) currentFocus = 0;  
         if (currentFocus < 0) currentFocus = (x.length - 1);  
         /*add class "autocomplete-active":*/  
         x[currentFocus].classList.add("autocomplete-active");  
       }  
       function removeActive(x) {  
         /*a function to remove the "active" class from all autocomplete items:*/  
         for (var i = 0; i < x.length; i++) {  
           x[i].classList.remove("autocomplete-active");  
         }  
       }  
       function closeAllLists(elmnt) {  
         /*close all autocomplete lists in the document,  
         except the one passed as an argument:*/  
         var x = document.getElementsByClassName("autocomplete-items");  
         for (var i = 0; i < x.length; i++) {  
           if (elmnt != x[i] && elmnt != inp) {  
             x[i].parentNode.removeChild(x[i]);  
           }  
         }  
       }  
       /*execute a function when someone clicks in the document:*/  
       document.addEventListener("click", function (e) {  
         closeAllLists(e.target);  
       });  
     }  

And you will have to apply the following CSS.



 /*the container must be positioned relative:*/  
 .autocomplete {  
   position: relative;  
   display: inline-block;  
 }  
 .autocomplete-items {  
   position: absolute;  
   border: 1px solid #d4d4d4;  
   border-bottom: none;  
   border-top: none;  
   z-index: 99;  
   /*position the autocomplete items to be the same width as the container:*/  
   top: 100%;  
   left: 0;  
   right: 0;  
   max-height: 300px;  
   /*height: 300px;*/  
   overflow-y: auto;  
   margin-left: 20px;  
 }  
   .autocomplete-items div {  
     padding: 5px 15px;  
     cursor: pointer;  
     background-color: #fff;  
     border-bottom: 1px solid #d4d4d4;  
   }  
     /*when hovering an item:*/  
     .autocomplete-items div:hover {  
       background-color: #e9e9e9;  
     }  
 /*when navigating through the items using the arrow keys:*/  
 .autocomplete-active {  
   background-color: DodgerBlue !important;  
   color: #ffffff;  
 }  

Then the reference can be made as below;

 autocomplete(document.getElementById("txtSearch"), keywords);  

Keywords are the array of strings to search. So, it will look like below eventually,


Unlike jquery autocomplete, this doesn't slowdown your page. 

Happy coding..


Tuesday, May 25, 2021

Base64 - Encoding and Decoding s String

The following class can be used to encode a string or decode an encoded string. 


   public static class Base64  
   {  
     public static string Encode(this System.Text.Encoding encoding, string textValue)  
     {  
       if (textValue == null)  
       {  
         return null;  
       }  
       try  
       {  
         byte[] textAsBytes = encoding.GetBytes(textValue);  
         return System.Convert.ToBase64String(textAsBytes);  
       }  
       catch (Exception)  
       {  
         return textValue;  
       }        
     }  
     public static string Decode(this System.Text.Encoding encoding, string encodedTextValue)  
     {  
       if (encodedTextValue == null)  
       {  
         return null;  
       }  
       try  
       {  
         byte[] textAsBytes = System.Convert.FromBase64String(encodedTextValue);  
         return encoding.GetString(textAsBytes);  
       }  
       catch (Exception)  
       {  
         return encodedTextValue;  
       }        
     }  
   }  

So, you can refer this as below;



 EncodingForBase64.DecodeBase64(Encoding.UTF8, yourtextvalue);  

Happy coding...

Convert an Image to Base64

Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.

Link to the Question

However we may still need to convert an image to base64 on the way to display our data on HTML page. Assuming you have a class that represent all the necessary details, here is how you can have an additional property to the class that converts images to base64.




     public string imageBase64  
     {  
       get  
       {  
         using (var client = new WebClient())  
         {  
           byte[] dataBytes = client.DownloadData(new Uri(image));  
           string encodedFileAsBase64 = Convert.ToBase64String(dataBytes);  
           return "data:image/jpeg;base64," + encodedFileAsBase64;  
         }  
       }  
     }  

Copy this and try it in your code. it will generate your html image tag as below.


Happy Coding...


Sunday, February 14, 2021

Writing a class to access mongo db end points in C#

Not knowing MongoDB? Read it here: 

https://en.wikipedia.org/wiki/MongoDB

"MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. "

Today we talk about how to write a common class to access end points ( Hosted seperately) that allow us to access MongoDB collection. You can read / write collections through this.

Lets go straight to the code:


   public class MongoService  
   {  
     public XmlDocument Select(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       foreach (var p in Parameter)  
         request.AddParameter(p.Key, p.Value);  
       IRestResponse response = client.Execute(request);  
       if (string.IsNullOrEmpty(response.Content))  
         return null;  
       var node = JsonConvert.DeserializeXNode(response.Content, "Root");  
       string xml = node.ToString();  
       XmlDocument doc = new XmlDocument();  
       doc.LoadXml(xml);  
       return doc;  
     }  
     public string Select<T>(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       foreach (var p in Parameter)  
         request.AddParameter(p.Key, p.Value);  
       IRestResponse response = client.Execute(request);  
       return response.Content;  
     }  
     public string Select<T>(Method method, string ServiceAddress, Dictionary<string, string> Header)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       IRestResponse response = client.Execute(request);  
       return response.Content;  
     }  
     public string Save<T>(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       foreach (var p in Parameter)  
         request.AddParameter(p.Key, p.Value);  
       IRestResponse response = client.Execute(request);  
       return response.Content;  
     }  
     public string Update<T>(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       foreach (var p in Parameter)  
         request.AddParameter(p.Key, p.Value);  
       IRestResponse response = client.Execute(request);  
       return response.Content;  
     }  
     public string Delete<T>(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  
     {  
       var client = new RestClient(ServiceAddress);  
       client.Timeout = -1;  
       var request = new RestRequest(method);  
       foreach (var h in Header)  
         request.AddHeader(h.Key, h.Value);  
       foreach (var p in Parameter)  
         request.AddParameter(p.Key, p.Value);  
       IRestResponse response = client.Execute(request);  
       return response.Content;  
     }  
   }  


The MongoService class has the following methods.

public XmlDocument Select(Method method, string ServiceAddress, Dictionary<string, string> Header, Dictionary<string, object> Parameter)  

This return the result as an xml document.

The parameters contain;

  • Method
  • ServiceAddress
  • Header
  • Parameter

The method is the restsharp method as it is GET or POST or any other.

Service address is the service address.

Header is the Dictionary of strings for headers.

Parameter is the Dictionary of string and object values for the parameters.

Using this class will help to ease with dealing the end points.

Happy coding.





Tuesday, February 9, 2021

Creating country flag emoji from country code - c#

Sometimes you might need to show the country flag as an icon or imoji in your webpage. But we don't need to host images of country flags anywhere which we can create images from the code itself. look at the below code.

 public static string CountryCodeToFlag(this string country)  
     {  
       return string.Concat(country.ToUpper().Select(x => char.ConvertFromUtf32(x + 0x1F1A5)));  
     }  

This is an extension method. so we can use it as below.

 "us".CountryCodeToFlag()  

The result will look like below,

Happy coding...