milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. C#

HttpClient Get and Post

Details
Written by: Stanko Milosev
Category: C#
Published: 18 March 2023
Last Updated: 20 March 2023
Hits: 14
  • core
Get:
HttpClient httpClientGet = new HttpClient();
Task<string> httpClientGetResult = httpClientGet.GetStringAsync(@"https://localhost:7037/api/Values");
Console.WriteLine(httpClientGetResult.GetAwaiter().GetResult());
Post:
HttpClient httpClientPost = new HttpClient();

Task<HttpResponseMessage> httpResponseMessage = httpClientPost.PostAsync(@"https://localhost:7037/api/Values"
    , new StringContent(@"""string Test"""
        , Encoding.UTF8
        , "text/json"));

Task<string> httpClientPostResult = httpResponseMessage.Result.Content.ReadAsStringAsync();
Console.WriteLine(httpClientPostResult.Result);
Example download from here. Example contains also dummy Web Api for test purposes.

UPDATE: Just a short notice, correct way to use HttpClient synchronously:

var task = Task.Run(() => myHttpClient.GetAsync(someUrl)); 
task.Wait();
var response = task.Result;
From here. Also, HttpClient is IDisposable

Automatically restore NuGet packages

Details
Written by: Stanko Milosev
Category: C#
Published: 10 February 2023
Last Updated: 10 February 2023
Hits: 77
For the article Writing Custom Control in new WPF XAML Designer I wrote the example app where I needed automatically to restore NuGet package. Write NuGet.Config file in folder where is *.sln file, and write it like:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <packageSources>

    <clear />

    <add key="My Private NuGet Server" value="package" />

  </packageSources>  
</configuration>
From here.

Two ways of getting window handle and title

Details
Written by: Stanko Milosev
Category: C#
Published: 02 November 2022
Last Updated: 02 November 2022
Hits: 301
First easiest but does not get every window:
foreach (Process pList in Process.GetProcesses())
{
	string mainWindowTitle = pList.MainWindowTitle.Trim();
	if (!string.IsNullOrWhiteSpace(mainWindowTitle))
	{
		Console.WriteLine(mainWindowTitle);
	}
}
Second:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using HWND = System.IntPtr;

namespace ListWindowsTitles
{
  /// <summary>Contains functionality to get all the open windows.</summary>
  public static class OpenWindowGetter
  {
    /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
    /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
    public static IDictionary<HWND, string> GetOpenWindows()
    {
      HWND shellWindow = GetShellWindow();
      Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

      EnumWindows(delegate(HWND hWnd, int lParam)
      {
        if (hWnd == shellWindow) return true;
        if (!IsWindowVisible(hWnd)) return true;

        int length = GetWindowTextLength(hWnd);
        if (length == 0) return true;

        StringBuilder builder = new StringBuilder(length);
        GetWindowText(hWnd, builder, length + 1);

        windows[hWnd] = builder.ToString();
        return true;

      }, 0);

      return windows;
    }

    private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowTextLength(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern bool IsWindowVisible(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern IntPtr GetShellWindow();
  }
}
Download from here.

Example of KML file with images

Details
Written by: Stanko Milosev
Category: C#
Published: 03 July 2022
Last Updated: 10 July 2022
Hits: 578
  • xml
KML example I took it from here. At the end my KML file gonna look like:
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>Paths</name>
    <description>test</description>
    <Style id="red">
      <LineStyle>
        <color>7f0000ff</color>
        <width>4</width>
      </LineStyle>
      <PolyStyle>
        <color>7f0000ff</color>
      </PolyStyle>
    </Style>
    <Placemark>
      <name>Picture 1</name>
      <Snippet>This is a picture</Snippet>
      <description><![CDATA[Location: 19.8619823, 45.2547803<br> Elevation: 838,0 m<br> Time Created: 12/02/2021 09:57:23 BRT<br> <img src="IMG_20130710_140741.jpg"><br><img src="IMG_20130710_140741.jpg"><br>>]]></description>
      <Point>
        <coordinates>19.8619823, 45.2547803</coordinates>
      </Point>
    </Placemark>
    <Placemark>
      <name>Absolute Extruded</name>
      <description><![CDATA[Transparent green wall with yellow outlines]]></description>
      <styleUrl>#yellowLineGreenPoly</styleUrl>
      <LineString>
        <extrude>1</extrude>
        <tessellate>1</tessellate>
        <altitudeMode>absolute</altitudeMode>
        <coordinates>19.8619823, 45.2547803, 2357 
19.8683723, 45.2524965, 2357 
</coordinates>
      </LineString>
    </Placemark>
  </Document>
</kml>
The model:
using System.Xml;
using System.Xml.Serialization;

namespace CreateKmlFromFiles
{
  public class KmlModel
  {
    [XmlRoot("kml", Namespace = "http://www.opengis.net/kml/2.2")]
    public class Kml
    {
      public Document Document { get; set; }
    }

    public class Document
    {
      public string name { get; set; }

      public string description { get; set; }

      public Style Style { get; set; }

      [XmlElement("Placemark")]
      public Placemark[] Placemark { get; set; }

    }

    public class Style
    {
      [XmlAttribute("id")]
      public string id { get; set; }

      public LineStyle LineStyle { get; set; }
      public PolyStyle PolyStyle { get; set; }
    }

    public class LineStyle
    {
      public string color { get; set; }
      public string width { get; set; }
    }

    public class PolyStyle
    {
      public string color { get; set; }
    }

    public class Placemark
    {
      public string name { get; set; }
      public string Snippet { get; set; }
      public XmlCDataSection description { get; set; }
      public string styleUrl { get; set; }
      public Point Point { get; set; }
      public LineString LineString { get; set; }
    }

    public class LineString
    {
      public string extrude { get; set; }
      public string tessellate { get; set; }
      public string altitudeMode { get; set; }
      public string coordinates { get; set; }
    }

    public class Point
    {
      public string coordinates { get; set; }
    }
  }
}
Program:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using MetadataExtractor;
using MetadataExtractor.Formats.Exif;
using Newtonsoft.Json.Linq;
using Directory = System.IO.Directory;

namespace CreateKmlFromFiles
{
  class Program
  {

    static void Main(string[] args)
    {

      StringBuilder sb = new StringBuilder();
      foreach (string file in Directory.GetFiles(@"C:\someFilesWithGpsLocations"))
      {
        JObject myJObject = JObject.Parse(File.ReadAllText(file));
        sb.Append($"{myJObject["lng"]}, {myJObject["lat"]}, 2357 {Environment.NewLine}");
      }

      KmlModel.Kml kmlModel = new KmlModel.Kml
      {
        Document = new KmlModel.Document
        {
          name = "Paths"
          , description = "test"
          , Style = new KmlModel.Style
          {
            id = "red"
            , LineStyle = new KmlModel.LineStyle
            {
              color = "7f0000ff"
              , width = "4"
            }
            , PolyStyle = new KmlModel.PolyStyle
            {
              color = "7f0000ff"
            }
          }
          , Placemark = new KmlModel.Placemark[]
          {
            new()
            {
              name = "Picture 1"
              , Snippet = "This is a picture"
              , description = new XmlDocument().CreateCDataSection(
                "Location: 19.8619823, 45.2547803<br> Elevation: 838,0 m"
                + "<br> Time Created: 12/02/2021 09:57:23 BRT"
                + "<br> <img src=\"IMG_20130710_140741.jpg\">" 
                + "<br><img src=\"IMG_20130710_140741.jpg\"><br>>"
              )
              , Point = new KmlModel.Point
              {
                coordinates = "19.8619823, 45.2547803"
              }
            }, 
            new()
            {
              name = "Absolute Extruded"
              , description = new XmlDocument().CreateCDataSection("Transparent green wall with yellow outlines")
              , styleUrl = "#yellowLineGreenPoly"
              , LineString = new KmlModel.LineString
              {
                extrude = "1"
                , tessellate = "1"
                , altitudeMode = "absolute"
                , coordinates = sb.ToString()
              }
            }
          }
        }
      };

      TextWriter txtWriter = new StreamWriter
      (
        Path.ChangeExtension
        (
          System.Reflection.Assembly.GetEntryAssembly()?.Location
          , ".kml"
        ) ?? string.Empty);

      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

      ns.Add("", "http://www.opengis.net/kml/2.2");

      XmlSerializer xmlSerializer = new XmlSerializer(typeof(KmlModel.Kml));
      xmlSerializer.Serialize(txtWriter, kmlModel, ns);

      txtWriter.Close();
    }
  }
}
Difference between this example, and this one, is that Placemark is now declared as list of Placemarks:
[XmlElement("Placemark")]
public Placemark[] Placemark { get; set; }
and description:
public XmlCDataSection description { get; set; }
where I had to create CDATA section, like:
description = new XmlDocument().CreateCDataSection("Transparent green wall with yellow outlines")
  1. Dynamically Loading Assemblies
  2. KML example
  3. Difference between Path.Join and Path.Combine
  4. GetCurrentDirectory

Subcategories

WPF

Beginning

Code snippets

NUnit

LINQ

Windows Forms

Page 1 of 33

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10