My portal
  • 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

Two examples of WebAPI with multiple Post parameters

Details
Written by: Stanko Milosev
Category: C#
Published: 15 July 2023
Last Updated: 15 July 2023
Hits: 94
First example
WebAPI:
[HttpPost]
public string Post(string value1, string value2)
{
	return $"Sent: {value1}, {value2}";
}
Console:
Console.WriteLine("************* POST *************");

HttpClient httpClientPost = new HttpClient();
Task<HttpResponseMessage> httpResponseMessage = httpClientPost.PostAsync(@"https://localhost:7037/api/Values?value1=test1&value2=test2'", null);
Task<string> httpClientPostResult = httpResponseMessage.Result.Content.ReadAsStringAsync();
Console.WriteLine(httpClientPostResult.Result);
Example download from here

---

Second example.

First install Microsoft.AspNetCore.Mvc.NewtonsoftJson

In \WebApi\WebApi\Program.cs add line:

builder.Services.AddMvc().AddNewtonsoftJson();
Now Program.cs looks like:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMvc().AddNewtonsoftJson();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
Controller:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace WebApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // POST api/<ValuesController>
    [HttpPost]
    public string Post([FromBody] JObject data)
    {
        return "test";
    }
}
Console:
using System.Text;

Console.WriteLine("************* POST *************");

HttpClient httpClientPost = new HttpClient();

Task<HttpResponseMessage> httpResponseMessage = httpClientPost.PostAsync(@"https://localhost:7037/api/Values"
    , new StringContent(@"{""additionalProp1"":[""string""],""additionalProp2"":[""string""],""additionalProp3"":[""string""]}"
        , Encoding.UTF8
        , "application/json"));

Task<string> httpClientPostResult = httpResponseMessage.Result.Content.ReadAsStringAsync();
Console.WriteLine(httpClientPostResult.Result);
Taken from here.

Example download from here.

HttpClient Get and Post

Details
Written by: Stanko Milosev
Category: C#
Published: 18 March 2023
Last Updated: 20 March 2023
Hits: 349
  • 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: 415
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: 641
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.
  1. Example of KML file with images
  2. Dynamically Loading Assemblies
  3. KML example
  4. Difference between Path.Join and Path.Combine

Subcategories

C#

Azure

ASP.NET

JavaScript

Software Development Philosophy

MS SQL

IBM WebSphere MQ

MySQL

Joomla

Delphi

PHP

Windows

Life

Lazarus

Downloads

Android

CSS

Chrome

HTML

Linux

Eclipse

Page 1 of 151

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