Imaging on C#

There are many possibilities to process graphical information in .Net.image
Microsoft has Graphics Device Interface for imaging. Its functionality is provided by System.Drawing.Common namespace in .Net Core and Framework.
By means of C# imaging it is possible:

  • to create images
  • to edit images
  • to create 2D animations
  • to create math graphics
  • to draw formatted text

Intro of imaging on C#

Adding imaging namespaces

First of all, System.Drawing.Common should be installed. It is downloadable from nuget.

using System.Drawing;
using System.Drawing.Imaging;
Some classes
  • Image – an abstract class that provides basic functionality of GDI
  • Bitmap – inherits Image, represents pixel image
  • Graphics – inherits Image, represent drawing surface
Load image from file and save to file
...
   Image image = Image.FromFile("path");  //constructor with string parameter (path to file)

   image.Save("otherpath");  // saving image
...
Codec
mime typeextension
image/apng.apng
image/bmp.bmp
image/jpeg.jpg, .jpeg
image/png.png
image/webp.webp

System.Drawing.Common only works with Bitmap images. When image is opened GDI uses decoder to transform it to Bitmap. When image is saved GDI uses encoder to prepare image to be saved with a needed extension. Encoder and decoder are called Codec. If Codec is not specified the default one will be used.

Method for getting encoder

...
   public static ImageCodecInfo GetEncoder(string mimetype)
   {
      return ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.MimeType == mimetype);
   }
...

Method for getting decoder

...
   public static ImageCodecInfo GetDecoder(string mimetype)
   {
      return ImageCodecInfo.GetImageDecoders().FirstOrDefault(e => e.MimeType == mimetype);
   }
...

How to cut picture from image on C#

Method for cutting Rectangle (at point (x,y), with height h and width w) from Image.

...
   public static Image Cut(int x, int y, int w, int h, Image image)
   {
      Rectangle rect = new Rectangle(x, y, w, h);

      using Bitmap target = new Bitmap(w, h);

      using (Graphics g = Graphics.FromImage(target))
      {
         g.DrawImage(image, 0, 0, rect, GraphicsUnit.Pixel);
      }

      image = new Bitmap(target, new Size(target.Width, target.Height));

      return image;
   }
...

How to save image with a specific number of bytes

Method for changing image in order to make it consist of needed number of bytes.
It reduces image quality until its size is less than parameter value (memoryInKb) and then saves it to provided path.

...
   public static void Save(string fullpath, int memoryInKb, Image image)
   {
      long qual = 101;

      ImageCodecInfo imagecodecinfo = GetEncoder("image/jpeg");  //GetEncoder is set earlier

      System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;

      using EncoderParameters encoderparams = new EncoderParameters(1);
      double current_size=0;
      do
      {
         qual--;
         EncoderParameter encoderparam = new EncoderParameter(encoder, qual);
         encoderparams.Param[0] = encoderparam;
         
         using MemoryStream mem = new MemoryStream();
         image.Save(mem, imagecodecinfo, encoderparams);
         string text = Convert.ToBase64String(mem.ToArray());
         current_size = Encoding.Default.GetByteCount(text) / 1.333 / 1024;
      }
      while (current_size>memoryInKb);

      image.Save(fullpath, imagecodecinfo, encoderparams);
   }
...

How to change image extension on c#

...
   public static void ChangeExtension(string originpath,string destinationpath, ImageFormat format)
   {
     using Image image = Image.FromFile(originpath);

     image.Save(destinationpath, format);
   }
...

How to resize image on c#

Method that returns resized image with a spesific size.

...
   public static Image Resize(Size size, Image image)
   {
     return new Bitmap(image, size);
   }
...

How to scale image on c#

Method that proportionally resizes image. It uses the previous method Resize.

...
   public static Image Scale(bool relation, int size, Image image)
   {
      double A = image.Width, B = image.Height;
      if (relation)
      {
         image = Resize(new Size(size, (int)(size * B / A)), image);
      }
      else
      {
         image = Resize(new Size((int)(size / B * A), size), image);
      }
      return image;
   }
...

How to draw rectangle over image using c#

...
   public static Image DrawRect(Image image, int x, int y, int w,int h)
   {
      using Pen pen = new Pen(Color.Black, 1);
      Bitmap bitmap = new Bitmap(image);
      Graphics graphics = Graphics.FromImage(bitmap);
      graphics.DrawRectangle(pen, x, y, w, h);
      return bitmap;
   }
...

FAQ about HTTP Client with examples

What is HTTP Client?

In client-server model Server is the one who handle requests and send responses, Client is the one who send requests and handle responses.
client-server
Generally speaking, Client is a program, library or a program method that:

  1. Sends request with some data to the server
  2. Recieves response messege from server

That list is a minimal requirements to be considered a client.

Client can be both a high-level many functional library and Two request-response method code.

Wisely chosen Client is crucial for the performance of the web application that uses external API or deals with a large number of requests.
As a rule each language platform has its native tool to do client’s job.

Why do you need HTTP Client?

Nowadays, there are some standarts of biulding HTTP request messeges in client-server model. That is how various web systems can communicate. As you can see in RFC documentation, there are a lot of information about what is HTTP and how to use it. Usually a common developer doesn’t have time to look through it. But he doesn’t really have to.

Client is developed to match standarts of a protocol it works with and architecture of this protocol usage (for instance, REST). In our case it is HTTP or HTTPS.

Client is a way to simplify a whole work with sending and obtaining data, because:

  • it takes into account all protocol specification
  • it is designed to be high performance at low level and simple to use at hign level
  • developer doesn’t need to know how protocol works

HTTP Request Methods

HTTP Requests are widely used to work with external databases by means of API. In order to make API usage more predictable and easy requests are divided by methods:

  • GET – to pass info in url (e.g https://[site url][parameters]) and obtaine public data
  • POST – to pass private info
  • DELETE – to pass private info in order to request removal of something from database
  • PUT – to pass private info in order to request update of something in database
  • and others

HTTP Client examples

webapplication

.NET C# HTTP Client

System.Net.Http namespace provides a lot of classes for work in web. HttpClient is a modern and fast HTTP .Net Client.

...
   using System.Net.Http;  //adding Http namespace
...
   HttpClient _client=new HttpClient();

   string url="http://www.brainbeast.best";  //some url

   string resp = await _client.GetStringAsync(url);  //get request, resp will contain html code of a webpage
...
Javascript HTTP Client

Web version of JS has XMLHttpRequest object that can send and recieve http messeges, set request method and work in async regime.

...
    function PostRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            
          var resp=this.responseText;  //response messege

        }
    };
    
    xhttp.open("POST", "http://someurl", true);  //setting Method, url, async regime (true/false)
    xhttp.send("private data");  //private data to send
}
...
PHP HTTP Client

By means of cURL PHP running servers can execute http requests. cURL is not the only option.

...
    $crl = curl_init();

    curl_setopt($crl, CURLOPT_URL,"https://some_url");

    curl_setopt($crl, CURLOPT_POST, 1);

    curl_setopt($crl, CURLOPT_POSTFIELDS,"private post data");

    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);

    $resp = curl_exec($crl);

    curl_close ($crl);

    echo $resp;
...

How to download image with HTTP Client on C#?

...
   HttpClient _client=new HttpClient();
   byte[] buffer = null;
   try
   {       
      HttpResponseMessage task = await _client.GetAsync("https://www.brainbeast.best/wp-content/uploads/2020/05/client-server.jpg");
      Stream task2 = await task.Content.ReadAsStreamAsync();
      using (MemoryStream ms = new MemoryStream())
      {
        await task2.CopyToAsync(ms);
        buffer = ms.ToArray();
      }
      File.WriteAllBytes("C:/client-server.jpg", buffer);  //path to save image and bites of this image
   }
   catch
   {

   }
...

How to set timeout in C# HTTP Client?

...
   HttpClient _client=new HttpClient();
   _client.Timeout = TimeSpan.FromSeconds(300);
...

How to add Custom Header to HTTP Request on C#?

...
   HttpClient _client=new HttpClient();
   client.DefaultRequestHeaders.Add("Some header", "some value");
...

How to create HTTP POST request and send JSON data on C#?

First option is to install Microsoft.AspNet.WebApi.Client from Nuget.

...
class Person
{
   public string Name {get;set;}
   public string Surname {get;set;}
}
...
   Person person=new Person {Name ="Andy", Surname="Smith"};  //you can post any class with public fields

   HttpClient _client=new HttpClient();

   var response = await client.PostAsJsonAsync("http://endpoint", person);

   var resptext = await response.Content.ReadAsStringAsync();
...

Second option:

...
   HttpClient _client=new HttpClient();

   var values = new Dictionary
      {
        { "username", "andy" },
        { "password", "12345678" }
      };

   var content = new FormUrlEncodedContent(values);

   var response = await _client.PostAsync($"https://some endpoint", content);

   var responseString = await response.Content.ReadAsStringAsync();
...

FAQ about Regular expressions with examples

regex
Regular expressions are both textual data processing method and language for building masks. Mask is a set of symbols and special characters that represent some pattern, which is used to catch segments of text for further work (replacing, extracting, checking conditions).
Regular expressions can be used with many popular programming languages: C#, javascript, pyton, php and so on.

Note: rules of building masks are similar in almost all cases.

How to use regular expression on C#?

To set up the regular expression tool, three major steps should be performed:

  1. Create pattern string
  2. Create exemplar of Regex class
  3. Process text by means of Regex
...
   string [email protected]"\sHello{3}";  //mask for catching "hello" with three O in the end and one space in left side
...

Note: pattern or mask is rule of processing text. You can try any mask using online tester.

...
   Regex reg = new Regex(pattern);  //Regular expression
   
   string text="Hi, John. Hellooo, Mary. Hello, Gary.";  // textual data to analize

   MatchCollection matches = reg.Matches(text);  //returns collection of Matches. In our case it matches " Hellooo"
...

It is possible to call a match by index from matches. Match class has some usefull properties:

  • Value – string that matches pattern
  • Index – position of the first character of captured string in the original string
  • Length – number of character in captured string
...
   string firstmatch=matches[0].Value; //firstmatch equals " Hellooo"
...

How to create list of substrings from text with Regex?

...
   MatchCollection matches = reg.Matches(text);  //match collection from text

   List resultlist = matches.Select(m => m.Value).ToList();  //using Linq

   string[] resultarray= new string[matches.Count];  //not using Linq
   for(int i=0; i<matches.Count; i++)
   {
      resultarray[i] = matches[i].Value;
   }
...

How to ignore letter case in regular expressions?

...
   Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); //ignores letter case

   Regex regex2 = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.RightToLeft); //ignores letter case and process from right to left
...

Note: it is possible to set more RegexOptions (RegexOptions.IgnoreCase | RegexOptions.RightToLeft | RegexOptions.Compiled).

How to do replacing with Regex?

...
   //replaces "Helooo" with "Howdy"
   string newtext = Regex.Replace(text, pattern, "Howdy");
...

How to set timeout to Regex?

...
   Regex regEx = new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(10));  //stops processing after 10 sec
...

How to make Regex work faster?

Dealing with huge amount of textual data, you will stumble upon a problem of execution speed loss. Setting RegexOptions.Compiled will make Regex perform faster.

...
   Regex regEx = new Regex(pattern, RegexOptions.Compiled);  //takes a bit more time for compilation, but works faster
...

Pattern for extracting emails from text

The following mask is able to catch ordinary emails (e.g. [email protected]), complex emails ([email protected]) and protected from spam emails (e.g. email[at]email.com, [email protected] dot com):

...
   string emailpattern =  @"([a-zA-Z0-9_\-\.]+)(@|(\s*\[\s*at\s*\]\s*)|(\s*" + "\"" + @"\s*(at)\s*" + "\"" + @"\s*))([a-zA-Z0-9_\-\.]+)((\.)|(\s+dot\s+)|(\s*\[\s*dot\s*\]\s*)|(\s*" + "\"" + @"\s*(dot)\s*" + "\"" + @"\s*))([a-zA-Z]{2,5})";
...

Patterns for extracting links from page

...
   string tagPat = @"?<\s*a[^>]*>(.*?)?<\s*/\s*a\s*>";  //pattern for A tags 

   string hrefPat = "href *= *(\"(?<url>.+?)\")"; //pattern with group url for href attribute
...

Groups in regular expressions

You can organize result of Regex matches into one or more groups:

... 
   string hrefPat = "href *= *(\"(?<url>.+?)\")"; //pattern with group url for href attribute
   
   string text = "<a href=\"http://somedomain\"> Domain </a>";

   Regex regex = new Regex(hrefPat, RegexOptions.IgnoreCase);

   string result=regex.Match(text).Groups["url"].Value;  //result equals http://somedomain
...

FAQ about Selenium WebDriver on c# with examples

Selenium is a set of tools that are used to automate web browser work. It is possible to use these tools with such popular languages as C#, PHP and Java.

How to install Selenium tools to the project in Visual Studio?

First of all, it is necessary to install Selenium.Webdriver packages to the project. By means of NuGet package manager programmer can install them right from the project window:

nuget

  1. Go to Tools/NuGet Package Manager/Manage NuGet Packages for Solution…/ in Visual Studio
  2. In “NuGet – Solution” tab go to Browse
  3. In search line write the package name – Selenium.Webdriver
  4. Choose the package and press install button

Secondly, it is necessary to download drivers that match browsers you choose to test and OS of the computer:

  1. Update all browsers you want to test
  2. Download appropriate driver
  3. Place downloaded driver (.exe) to the application directory

Finally, using directives to Selenium namespaces must be added:

...
   using OpenQA.Selenium;
   using OpenQA.Selenium.Chrome;
   using OpenQA.Selenium.Firefox;
...

Note: Webdriver won`t work with Firefox browser if Firefox: Developer Edition is not installed.

How to create an instance of WebDriver on c#?

There are some classes for each webdriver:

  • ChromeDriver
  • FirefoxDriver
  • and so on

Also, all of them inherit IWebDriver interface. An instance of webdriver class can be initialized by means of default constructor (that has some overloads):

...
   FirefoxDriver firefox = new FirefoxDriver();
   ChromeDriver chrome = new ChromeDriver();
   List<IWebDriver> drivers = new List<IWebDriver>() { firefox, chrome };  //put webdrivers to the list
...

How to force webdriver to wait until the web content is fully loaded?

Working with webdriver, programmer can stumble upon such a problem that webdriver instance won`t wait until web page content is fully loaded. That can lead to exceptions when command to find and perform some actions with dom element is executed. To solve this issue Implicit wait time should be set.

...
   IWebDriver driver = new ChromeDriver();
   driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); //driver will try to execute dom commands for 10 seconds in case of failure
...

How to hide command prompt (console) while using webdriver on c#?

...
   ChromeDriverService chromeservice = ChromeDriverService.CreateDefaultService();
   chromeservice.HideCommandPromptWindow = true; //hide console window
   ChromeDriver driver = new ChromeDriver(chromeservice);

   FirefoxDriverService firefoxservice = FirefoxDriverService.CreateDefaultService();
   firefoxservice.HideCommandPromptWindow = true; //hide console window
   FirefoxDriver driver = new FirefoxDriver(firefoxservice);
...

How to execute your javascript code in webdriver window?

There are two similar options to inject and execute new javascript code in webdriver:

  • by means of webdriver class method ExecuteScript or ExecuteScriptAsync
  • by means of IJavaScriptExecutor interface that is inherited by webdriver classes
...
    FirefoxDriver firefoxdriver = new FirefoxDriver();
    firefoxdriver.ExecuteScript("alert("Hello!");");  //your js code
    firefoxdriver.Quit();

    IWebDriver driver= new FirefoxDriver();
    IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
    executor.ExecuteScript("alert("Hi!");");   //your js code
    driver.Quit();
...

How to move cursor to some point in webdriver window?

In case of web pages what contain actions associated with mouse moves, ability to manipulate mouse is needed. For example, in order to parse web pages, you will need to get whole usefull html content from web sites. As a rule, for a number of reasons (often for protecting from spam bots) web masters try to hide some part or a whole sites` content from beeing loaded by bots (in our case by webdriver bot). The most popular way of achieving such kind of a protection is to check if the mouse is moved while surfing the site. Sometimes the folowing code can be really helpful:

...
   ChromeDriver driver = new ChromeDriver();
   Actions action = new Actions(driver);

   action.MoveByOffset(5,5).Perform();  //moves cursor to point (5,5)

   action.MoveByOffset(10, 15).Perform();  //moves cursor to point (10,15)
...

How to navigate to some webpage in webdriver window?

...
   driver.Navigate().GoToUrl("https://www.brainbeast.best/");
...

How set page load time?

...
   driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10);  //time to wait untill page is loaded
   try
   {
      driver.Navigate().GoToUrl(url);  //if page is not loaded in 10 sec exception is thrown
   }
   catch
   {
      //catch timeout exception
   }
...

How to set Chrome command line switches?

In case of making complex and various tests chrome CLI switches can be really useful and sometimes required.

...
   ChromeOptions options = new ChromeOptions();
   options.AddArguments(new List<string>() { "switch 1", "switch 2", "and so on" });  //adding list of chrome CLI arguments

   ChromeDriver driver = new ChromeDriver(options);
...

Full list of CLI agruments.

How to set windowless regime in webdriver?

If tests are done without requirement of showing up any useful information it is logical to switch off window mode. To run webdriver without window, add neseccary CLI arguments:

...
   ChromeOptions options = new ChromeOptions();
   options.AddArguments(new List<string>() { "headless"});
...

Drag-and-Drop on C# in WPF

working-womanDeveloping desktop WPF or WinForm projects, you can stumble upon an idea of creating drag & drop functionality. Drag-and-Drop effect will simplify file manipulation between browser, computer file system and desktop applications.

To understand the following sample you should already know:

  1. Basic priciples of Object-oriented programming
  2. How to create WPF or WinForm projects

To make it work you should get on with installed Visual Studio.

Drag & Drop in WPF .Net Core/Framework

  1. Create WPF project
  2. Add ListView to the main window
  3. Add Drop and MouseMove handlers to ListView

wpf-project

In order to simplify the logic of the program, let`s add a class and name it FileObject, that contains Name (image.jpeg, essay.txt etc) and Fullname (C:/somefolder/image.jpeg, E:/myessays/essay.txt etc):

...
    class FileObject
    {
        public string Name { get; set; }

        public string FullName { get; set; }

        public FileObject(string name, string fullname)
        {
            Name = name;
            FullName = fullname;
        }

        public override string ToString()
        {
            return Name;
        }
    } 
...

By means of the following code user is able:

  • to drop some file to the list.
  • to drop some file to some folder from list

Dragging the file to ListView, it is possible to handle drop event and get the full file`s path:

...
     public readonly string DirPath = AppDomain.CurrentDomain.BaseDirectory;      /*path to the folder where the executable file is*/

        private void lv_list_Drop(object sender, DragEventArgs e)
        {
            string[] file_pathes = (string[])e.Data.GetData(DataFormats.FileDrop);  /*file_pathes contains pathes of dragged selected files*/

            //add every file to the list copping them to the application directory
            foreach (var path in file_pathes)
            {
                string new_path = DirPath + Path.GetFileName(path); //New file path

                File.Copy(path, new_path);                         //copping dragged file by new_path

                lv_list.Items.Add(new FileObject(Path.GetFileName(path), new_path));  //adding FileObject (that stores file info) to the list
            }
        }
  
...

Note: ListView can put any object to its items property. To show textual representation of the items ListView calls method ToString() that is marked as virtual in object class. That is why ToString() is overridden in FileObject, to show short file name in the list.

To drag some file from the list is it necessary to select it and put cursor in some folder (or browser window etc) realising the left button of the mouse:

...
        private void lv_list_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.MouseDevice.LeftButton==System.Windows.Input.MouseButtonState.Pressed) //Checking that leftbutton is pressed
            {
                var file = lv_list.SelectedItem as FileObject; //Taking the selected object as FileObject

                if(file!=null) //Check that item is really selected. Alternatively file variable equals null

                DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, new string[] { file.FullName }), DragDropEffects.Move);/*new string[] {...} - array contains files` pathes user wants to drag from list*/

                lv_list.Items.Remove(file);                   //removing dropped obect from the list
            }
        }
...

Drag & Drop in WinForm .Net Core/Framework

Instructions are almost similar to the previous ones:

  • Create project
  • Choose Control element (ListView, DataGridView, ListBox etc)
  • Add DragDrop and MouseMove handlers
...
    private void YourElementControl_DragDrop(object sender, DragEventArgs e)
    {
       ...
       foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
            {
                File.Copy(path, DirPath + Path.GetFileName(path));
            }
       ...
    }

    private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
    {
     ...
         if (e.Button == MouseButtons.Left)
         {
                 DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
         }
     ...
    }
...

Note: It is possible to implement drag-and-drop for both files and folders. Also it is possible to use various Control elements for implementation.