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

How to Build a Chat Agent for Ollama Using C#

Details
Written by: Stanko Milosev
Category: C#
Published: 17 January 2026
Last Updated: 18 January 2026
Hits: 26
This example is based on an implementation taken from this website.

To begin, I create a new WinForms project in C# targeting .NET 10, and then install the OllamaSharp NuGet package.

In this example, txtOllamaUri, txtModel, and txtMessage are WinForms controls (for example, TextBox instances). Replace them with the corresponding controls or values from your own UI:

    Chat _chat;
    OllamaApiClient? _ollamaApiClient;
	
    uri = new Uri(txtOllamaUri.Text);
    _ollamaApiClient = new OllamaApiClient(uri);
    _ollamaApiClient.SelectedModel = txtModel.Text;

    _chat = new Chat(_ollamaApiClient);
	
    await foreach (var answerToken in _chat.SendAsync(txtMessage.Text))
        Console.Write(answerToken);
Example download from here.

My first OpenWebUI tool

Details
Written by: Stanko Milosev
Category: C#
Published: 09 January 2026
Last Updated: 10 January 2026
Hits: 56
First, about my setup, the host system runs Windows 11, and all tools are installed in a Windows 11 virtual machine using VMware.

On the host system, to fully utilize the available resources, I installed Ollama with the qwen2.5-coder model, as well as OpenWebUI via Docker.

Inside the VMware environment, I created an ASP.NET Core Web API project in Visual Studio, which automatically generated the WeatherForecastController.

Since Docker is running on the host system and the WeatherForecastController is running inside VMware, I changed the settings of my ASP.NET Core Web API to allow access from outside the virtual machine.

My \Properties\launchSettings.json file looks like this:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5259",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://0.0.0.0:7216;https://0.0.0.0:7217",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

This means that the controller was accessible via the following endpoint:

https://192.168.2.50:7217/WeatherForecast
In OpenWebUI tools, I wrote:
import requests
import urllib3

class Tools:
    def today_from_csharp_http(self) -> str:
        """
        Get the current weather.
        """
        url = "https://192.168.2.50:7217/WeatherForecast"
        try:
            r = requests.get(url, timeout=5, verify=False)
            r.raise_for_status()

            data = r.json()
            if not isinstance(data, list) or len(data) == 0:
                return f"Unexpected JSON: {type(data).__name__}: {data}"

            first = data[0]
            date = first.get("date")
            summary = first.get("summary")
            temp = first.get("temperatureC")

            return f"OK: {date} | {summary} | {temp}°C"
        except Exception as e:
            return f"HTTP request failed: {e}"

The tool must be enabled for this model by checking the corresponding tool checkbox.

Post Joomla! article

Details
Written by: Stanko Milosev
Category: C#
Published: 06 July 2025
Last Updated: 06 July 2025
Hits: 1237

Here is my Example how to post Joomla! article from .NET.

Four steps are needed:

  1. Open Joomla! admin page
  2. Login to Joomla!
  3. Open add article page
  4. Save and close

First we will create HttpClient and same instance I will use for every step:

HttpClientHandler httpClientHandler = new HttpClientHandler
{
    CookieContainer = new CookieContainer(),
    UseCookies = true,
    AllowAutoRedirect = true
};
HttpClient client = new HttpClient(httpClientHandler);

For every step we will need token

static string ExtractTokenName(string html)
{
    var regex = new Regex(@"""csrf\.token"":""(?<token>[a-f0-9]{32})""");
    var match = regex.Match(html);

    if (match.Success)
    {
        return match.Groups["token"].Value;
    }

    throw new Exception("CSRF-Token not found.");
}
  1. Open Joomla! admin page:
    async Task<string> OpenJoomlaAdminPage(HttpClient httpClient, string url) 
    {
        HttpResponseMessage getResponse = await httpClient.GetAsync(url);
        string html = await getResponse.Content.ReadAsStringAsync();
        return html;
    }
    
  2. Login to Joomla!:
    async Task<bool> LoginToJoomla(HttpClient httpClient, string url, string username, string password, string joomlaAdminPagehtml)
    {
        var tokenName = ExtractTokenName(joomlaAdminPagehtml);
        var tokenValue = "1";
        var formContent = new FormUrlEncodedContent([
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("passwd", password),
            new KeyValuePair<string, string>("option", "com_login"),
            new KeyValuePair<string, string>("task", "login"),
            new KeyValuePair<string, string>(tokenName, tokenValue)
        ]);
        HttpResponseMessage postResponse = await httpClient.PostAsync(url, formContent);
        string postResult = await postResponse.Content.ReadAsStringAsync();
        return postResult.Contains("mod_quickicon") || postResult.Contains("cpanel");
    }
    
  3. Open add article page:
    async Task<string> OpenAddArticle(HttpClient httpClient, string addArticleUrl)
    {
        HttpResponseMessage createResponse = await httpClient.GetAsync(addArticleUrl);
        string createHtml = await createResponse.Content.ReadAsStringAsync();
        return ExtractTokenName(createHtml);
    }
    
  4. Save and close:
     
    async Task<bool> PostArticleToJoomla(HttpClient httpClient, string url, string articleToken, string title, string catid, string articletext)
    {
        var formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("jform[title]", title),
            new KeyValuePair<string, string>("jform[catid]", catid),
            new KeyValuePair<string, string>("jform[language]", "*"), 
            new KeyValuePair<string, string>("jform[state]", "1"),
            new KeyValuePair<string, string>("jform[articletext]", articletext),
            new KeyValuePair<string, string>("task", "article.save"),
            new KeyValuePair<string, string>(articleToken, "1")
        });
    
        HttpResponseMessage postResponse = await httpClient.PostAsync(url, formData);
        string postResultHtml = await postResponse.Content.ReadAsStringAsync();
    
        return postResultHtml.Contains("Article saved.");
    }
    
Example download from here.

Proper way to cancel task

Details
Written by: Stanko Milosev
Category: C#
Published: 23 May 2025
Last Updated: 01 July 2025
Hits: 1224
cancellationToken
   CancellationToken
   A cancellation token that can be used to cancel the work if it has not yet started. Run(Func, CancellationToken) does not pass cancellationToken to action.
From here.

If you have an async method that you want to cancel, you need to provide a CancellationTokenSource to that method. Example:

public void ExecuteWithCancellationTokenSource(string path, CancellationTokenSource cancellationTokenSource)
{
	foreach (var fileName in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
	{
		fileNameProgress.Report(fileName);
		Thread.Sleep(1000);
		if (cancellationTokenSource.IsCancellationRequested) break;
	}
}
Otherwise, you can't cancel it if you have a method like this:
public void ExecuteWithoutCancellationTokenSource(string path)
{
	foreach (var fileName in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
	{
		fileNameProgress.Report(fileName);
		Thread.Sleep(1000);
	}
}
and you start execution something like this:
Task task = Task.Run(() => { readFromHdd.ExecuteWithoutCancellationTokenSource(_path); }, _cancellationTokenSource.Token);

try
{
	await Task.WhenAll(task);
}
catch (Exception ex)
{
	tbFileNames.AppendText(ex.Message + Environment.NewLine);
}
finally
{
	tbFileNames.AppendText("Done" + Environment.NewLine);
}
it will never stop. Or even worse, if you start like this:
Task task = Task.Run(() => { readFromHdd.ExecuteWithoutCancellationTokenSource(_path); }, _cancellationTokenSource.Token);

Task groupOfAllTasks = Task.WhenAll(task).ContinueWith(t =>
{
	if (t.IsFaulted)
	{
		throw new Exception("rException!");
	}
}, _cancellationTokenSource.Token);

List<Task> allTasks =
[
	groupOfAllTasks
];

try
{
	await Task.WhenAll(allTasks);
}
catch (Exception ex)
{
	tbFileNames.AppendText(ex.Message + Environment.NewLine);
}
finally
{
	tbFileNames.AppendText("Done" + Environment.NewLine);
}
It will raise a TaskCanceledException, but the operation will continue executing in the background.

Example download from here.

  1. How to Load a Large File from MS SQL
  2. One consumer, multiple tasks
  3. Get types and size from database
  4. Task.Run cannot be canceled immediately

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 168

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