Home - potatoscript/csharp GitHub Wiki
Title | Remark |
---|---|
What is C#? | Understand the purpose and basics of C#. Learn why C# is used and where itβs applicable. |
Setting Up the C# Environment | Step-by-step guide on installing Visual Studio and setting up the C# environment for programming. |
Title | Remark |
---|---|
Hello World | Your first C# program! Learn how to write and run the classic "Hello, World!" program. |
Variables and Data Types | Learn about different data types in C# (int, string, bool) and how to use variables to store information. |
Comments in C# | Understand how to write comments in your code for clarity. |
Title | Remark |
---|---|
If-Else Statements | Learn how to make decisions in your code using if-else statements. |
Switch-Case | Learn how to use switch-case to simplify multiple conditions in your program. |
Loops (for, while) | Loops allow you to repeat actions in your program. Understand how to use for and while loops. |
Break and Continue | Learn how to break or skip iterations in loops with break and continue . |
Title | Remark |
---|---|
Defining Functions | Learn how to define your own functions (or methods) to organize and reuse code. |
Function Parameters and Return Types | Understand how to pass data to and from functions. |
Recursion | Explore how functions can call themselves and solve problems step-by-step. |
Title | Remark |
---|---|
Classes and Objects | Learn about the building blocks of OOP: classes and objects. Create your own objects to represent real-world entities. |
Properties and Methods | Discover how to define properties and methods for your classes. |
Constructors | Learn how to initialize your objects with constructors. |
Inheritance | Understand how to inherit behavior from other classes and create a hierarchy. |
Polymorphism | Learn how the same method can behave differently based on the object calling it. |
Encapsulation | Learn how to protect data by restricting access to internal object details. |
Abstraction | Explore how to hide complex implementation details and show only necessary features to the user. |
Title | Remark |
---|---|
Arrays | Learn how to store multiple values in an array and access each value. |
Lists | Lists are dynamic arrays. Learn how to add and remove items in a list. |
Dictionaries | Understand how to store data in key-value pairs using dictionaries. |
Queues and Stacks | Explore FIFO (First In, First Out) and LIFO (Last In, First Out) data structures. |
Title | Remark |
---|---|
Try-Catch-Finally | Learn how to handle errors in your program so it doesnβt crash unexpectedly. |
Custom Exceptions | Understand how to create your own exceptions for special error conditions. |
Title | Remark |
---|---|
Reading and Writing Files | Learn how to read from and write to files in C#. |
File I/O with Streams | Dive deeper into working with file streams for reading and writing large files. |
CSV File Handling | Learn how to read and write CSV files (comma-separated values). |
Working with JSON | Learn how to parse and work with JSON data in C#. |
Title | Remark |
---|---|
Connecting to Databases | Learn how to connect your C# application to a database using ADO.NET. |
CRUD Operations (Create, Read, Update, Delete) | Master how to interact with databases to create, read, update, and delete records. |
Using SQL Queries | Understand how to write SQL queries within C# to retrieve and manipulate data. |
Entity Framework | Explore an easier way to work with databases using Entity Framework. |
Title | Remark |
---|---|
Delegates and Events | Learn how to use delegates to pass methods around and create events in your programs. |
LINQ (Language Integrated Query) | Discover how to use LINQ to easily query and manipulate data in C#. |
Asynchronous Programming | Learn how to perform non-blocking operations using async and await keywords. |
Multithreading | Understand how to run multiple operations at once using threads. |
Title | Remark |
---|---|
Creating Forms | Learn how to design and create Windows Forms for desktop applications. |
Buttons, TextBoxes, and Controls | Understand how to add and handle user input controls like buttons and textboxes. |
Working with DataGridView | Learn how to display and manage tabular data using DataGridView. |
Custom Controls | Learn how to create your own custom user interface controls. |
Title | Remark |
---|---|
Building a Complete Application | Combine everything you've learned to build a complete project. This will include designing the UI, handling data, and implementing logic. |
Debugging and Testing | Learn how to debug your C# programs and write tests to make sure everything works correctly. |
Title | Remark |
---|---|
WPF (Windows Presentation Foundation) | This tutorial covers the essentials of building desktop applications using WPF, focusing on UI components, data binding, commands, and MVVM (Model-View-ViewModel) architecture. Ideal for developers transitioning from WinForms to WPF. |
ASP.NET MVC | Learn to build dynamic web applications using ASP.NET MVC, focusing on model binding, controllers, views, and routing. This tutorial is designed for those who are looking to implement the MVC architecture in a .NET web application. |
ASP.NET Core MVC | ASP.NET Core MVC tutorial for building modern web applications with cross-platform support. This guide covers dependency injection, middleware, and RESTful API development using MVC in ASP.NET Core. |
ASP.NET 5 | A detailed guide to developing applications with ASP.NET 5, which is the foundation for modern web APIs and microservices. This tutorial focuses on building scalable and high-performance web applications. |
ASP.NET Web Forms | A comprehensive guide for developers working with ASP.NET Web Forms. Focuses on page-based development and event-driven programming for building dynamic web applications. Ideal for legacy applications. |
ASP.NET API | This tutorial provides an introduction to creating RESTful APIs using ASP.NET. It covers best practices in routing, controllers, and API versioning to build robust and maintainable web services. |
Title | Remark |
---|---|
ConvertImageToBase64 | Simple C# WPF application that converts a PNG image to a Base64 string. |
PotatoMenuApp | C# WPF application tutorial for creating a recipe manager with a menu bar and dynamic content display. |
ConvertImageToBase64.sln
βββ ConvertImageToBase64.Lib β Class Library (reusable code)
βββ ConvertImageToBase64.App β WPF App
dotnet new sln -n ConvertImageToBase64
dotnet new classlib -n ConvertImageToBase64.Lib
This creates the folder and .csproj
file:
ConvertImageToBase64.Lib/
βββ ConvertImageToBase64.Lib.csproj
Move ImageHelper
class from your MainWindow.xaml.cs
into a file like:
ConvertImageToBase64.Lib/ImageHelper.cs
Make sure it looks like this:
namespace ConvertImageToBase64.Lib
{
public static class ImageHelper
{
public static string? ConvertPngToBase64(string filePath)
{
if (string.IsNullOrEmpty(filePath))
return null;
try
{
byte[]? imageBytes = ReadFile(filePath);
return imageBytes != null ? ConvertToBase64(imageBytes) : null;
}
catch (Exception ex)
{
HandleError(ex);
return null;
}
}
public static byte[]? ReadFile(string filePath)
{
try
{
return File.Exists(filePath) ? File.ReadAllBytes(filePath) : null;
}
catch (Exception ex)
{
HandleError(ex);
return null;
}
}
public static string ConvertToBase64(byte[] imageBytes)
{
return Convert.ToBase64String(imageBytes);
}
private static void HandleError(Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
dotnet new wpf -n ConvertImageToBase64.App
dotnet sln ConvertImageToBase64.sln add ConvertImageToBase64.Lib/ConvertImageToBase64.Lib.csproj
dotnet sln ConvertImageToBase64.sln add ConvertImageToBase64.App/ConvertImageToBase64.App.csproj
dotnet add ConvertImageToBase64.App/ConvertImageToBase64.App.csproj reference ConvertImageToBase64.Lib/ConvertImageToBase64.Lib.csproj
ConvertImageToBase64.sln
βββ ConvertImageToBase64.Lib
β βββ ImageHelper.cs
βββ ConvertImageToBase64.App
β βββ MainWindow.xaml.cs
Now your app uses the helper code from the library, and itβs structured cleanly for reuse or packaging later (NuGet, Docker, etc.).
If you have a ConvertImageToBase64.csproj
file from the initial project, you don't need to delete it right away. Instead, youβll need to adjust the structure of your solution.
Hereβs what to do next:
- If the
ConvertImageToBase64.csproj
is part of your WPF app, it should remain. - If itβs an older or unnecessary project thatβs not part of the solution anymore, you can remove it.
- You donβt need to delete the
ConvertImageToBase64.csproj
file if it's already the WPF application project. - Just rename the project to match the new structure if it doesnβt have the
.App
suffix.
Example:
-
Rename it to
ConvertImageToBase64.App.csproj
if needed:mv ConvertImageToBase64.csproj ConvertImageToBase64.App/ConvertImageToBase64.App.csproj
-
Then, make sure to update your solution to add this project to the solution (if itβs not already).
- You can simply remove it:
rm ConvertImageToBase64.csproj
Once youβve sorted out the projects, hereβs how the structure should look:
ConvertImageToBase64.sln
βββ ConvertImageToBase64.Lib β Class Library (reusable code)
β βββ ConvertImageToBase64.Lib.csproj
βββ ConvertImageToBase64.App β WPF App
β βββ ConvertImageToBase64.App.csproj
Ensure both projects are part of the solution (dotnet sln
commands) and that the App project references the Lib project.
If you havenβt already, you can enable NuGet packaging for the class library project.
- Open the
ConvertImageToBase64.Lib.csproj
file and ensure it has thePackage
properties set:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <!-- Or your desired version -->
<PackageId>ConvertImageToBase64.Lib</PackageId>
<Version>1.0.0</Version> <!-- You can increment the version as you update -->
<Authors>Your Name</Authors>
<Description>A library for converting images to base64 strings.</Description>
<PackageTags>image, base64, conversion</PackageTags>
</PropertyGroup>
</Project>
Once everything is in place, navigate to the root folder of your solution and run:
dotnet pack ConvertImageToBase64.Lib/ConvertImageToBase64.Lib.csproj -c Release
This command will generate a .nupkg
file, which you can upload to NuGet.org or use internally.
To publish it, first create an API key on NuGet.org (if you haven't already), then use the following command:
dotnet nuget push bin\Release\ConvertImageToBase64.Lib.1.0.0.nupkg -k <YOUR_API_KEY> -s https://api.nuget.org/v3/index.json
Replace <YOUR_API_KEY>
with your actual key.
Since your app is a WPF application (Windows GUI), you'll need to run it on Windows-based Docker containers.
Hereβs a sample Dockerfile
to containerize your app:
# Use the official Windows image with .NET SDK
FROM mcr.microsoft.com/dotnet/aspnet:6.0-windows-ltsc2022 AS base
WORKDIR /app
EXPOSE 80
# Install .NET SDK to build the app
FROM mcr.microsoft.com/dotnet/sdk:6.0-windows-ltsc2022 AS build
WORKDIR /src
COPY ["ConvertImageToBase64.App/ConvertImageToBase64.App.csproj", "ConvertImageToBase64.App/"]
COPY ["ConvertImageToBase64.Lib/ConvertImageToBase64.Lib.csproj", "ConvertImageToBase64.Lib/"]
RUN dotnet restore "ConvertImageToBase64.App/ConvertImageToBase64.App.csproj"
COPY . .
WORKDIR "/src/ConvertImageToBase64.App"
RUN dotnet build "ConvertImageToBase64.App.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ConvertImageToBase64.App.csproj" -c Release -o /app/publish
# Copy published files to the base image
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ConvertImageToBase64.App.dll"]
-
Build the Docker Image: Navigate to your solution folder and build the image:
docker build -t convertimagetobase64 .
-
Run the Docker Container:
After building the image, you can run it using:
docker run -it --rm convertimagetobase64
Note: WPF apps run on Windows and donβt work directly in Docker containers without a display environment. If you intend to run a GUI (e.g., MainWindow.xaml) in Docker, itβs complex and typically requires additional tools for managing the UI. A better approach might be to separate the library and WPF into different services.
-
NuGet: Share your
ConvertImageToBase64.Lib
package on NuGet and reuse it in any project or offer it to others. -
Docker: Run your app as a service, but note that for GUI-based apps, you'd need special handling to display them outside of the container.
-
Explore other options: You might later want to deploy the WPF app as a Windows Service instead of running it interactively in Docker. If you want to avoid UI, you could convert the app into a console application that handles image conversion in the background.
Before you begin, make sure you have Docker installed on your system:
- Download Docker Desktop from the official website: Docker Desktop for Windows.
- Follow the installation instructions and ensure Docker is running properly on your system.
Your WPF application is a Windows desktop application, which means Docker will run the application in a Windows container. Before creating a Docker container, ensure the application works perfectly on your local machine.
- Ensure that your WPF Application (
ConvertImageToBase64.App
) is successfully compiled and all dependencies are working correctly.
- Ensure your library (
ConvertImageToBase64.Lib
) contains all the necessary methods for image conversion (which it looks like it already does from your provided code). - This class library will be referenced by the WPF application.
Now, let's create a Dockerfile to define how your app will be packaged in a container.
In the root directory of your solution (same level as the ConvertImageToBase64.App
folder), create a new file named Dockerfile
.
Add the following content to your Dockerfile
:
# Use the official Windows image with .NET SDK for build and runtime
FROM mcr.microsoft.com/dotnet/aspnet:6.0-windows-ltsc2022 AS base
WORKDIR /app
EXPOSE 80
# Install .NET SDK to build the app
FROM mcr.microsoft.com/dotnet/sdk:6.0-windows-ltsc2022 AS build
WORKDIR /src
COPY ["ConvertImageToBase64.App/ConvertImageToBase64.App.csproj", "ConvertImageToBase64.App/"]
COPY ["ConvertImageToBase64.Lib/ConvertImageToBase64.Lib.csproj", "ConvertImageToBase64.Lib/"]
RUN dotnet restore "ConvertImageToBase64.App/ConvertImageToBase64.App.csproj"
COPY . .
WORKDIR "/src/ConvertImageToBase64.App"
RUN dotnet build "ConvertImageToBase64.App.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ConvertImageToBase64.App.csproj" -c Release -o /app/publish
# Copy the build output to the base image
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ConvertImageToBase64.App.dll"]
-
FROM mcr.microsoft.com/dotnet/aspnet:6.0-windows-ltsc2022 AS base: This line sets the base image to use a Windows server container with .NET runtime to run the application.
-
FROM mcr.microsoft.com/dotnet/sdk:6.0-windows-ltsc2022 AS build: We use a .NET SDK image to build the project.
-
COPY: Copies the project files into the container.
-
RUN dotnet restore: Restores all necessary dependencies for the application.
-
RUN dotnet build: Builds the application.
-
RUN dotnet publish: Publishes the application, creating an optimized version for deployment.
-
ENTRYPOINT: Specifies how to start the application when the container is run (
dotnet ConvertImageToBase64.App.dll
).
-
Open a Command Prompt or PowerShell window.
-
Navigate to the root of your solution folder where your Dockerfile is located.
cd G:\GitHub\Heartlanguage2024\ConvertImageToBase64
-
Now, build the Docker image:
docker build -t convertimagetobase64 .
The
-t
flag is used to specify the name of the Docker image (convertimagetobase64
).Docker will start the process, downloading the necessary base images (if not already present) and running the commands from the
Dockerfile
to build the application.NOTE: The build process might take a while depending on your system and internet speed.
Once the image is built, you can run it using the following command:
docker run -it --rm convertimagetobase64
- -it: Allows you to run the container interactively (so you can see output or errors).
- --rm: Automatically removes the container when it stops.
- convertimagetobase64: The image you just built.
This should run your application inside the container. Since this is a WPF application (a Windows GUI), it might not display directly on your local system unless you implement a way to forward the GUI to your desktop.
Running a GUI application (like a WPF app) inside a Docker container can be tricky because containers are typically used for headless applications (without a GUI). However, you can try the following approaches:
-
Run with Remote Desktop: You can set up a Windows Server container with RDP support and then access the GUI through Remote Desktop (RDP). However, this setup is quite complex and not ideal for a typical development scenario.
-
Separate Services: A better approach might be to convert your WPF app into a console application that performs the image conversion without needing a GUI. This would allow you to easily run it in Docker.
You can convert your ConvertImageToBase64
application into a console-based application, which is better suited for Docker.
For example, change your MainWindow.xaml
code to a simple Program.cs
entry point for a console app:
using System;
using System.IO;
namespace ConvertImageToBase64
{
public class Program
{
static void Main(string[] args)
{
string filePath = @"C:\Projects\Image.png"; // Specify the path to your PNG file
string? base64String = ImageHelper.ConvertPngToBase64(filePath);
if (!string.IsNullOrEmpty(base64String))
{
Console.WriteLine("Base64 String: ");
Console.WriteLine(base64String);
}
else
{
Console.WriteLine("Error occurred while converting PNG to Base64.");
}
}
}
// Your ImageHelper class remains the same
}
After converting the WPF app to a console application, rebuild the solution, update the Dockerfile accordingly (it should work out of the box), and re-build and run the Docker container.
Once your Docker container is up and running, check the output in the console window to verify that your app is working as expected. If everything is fine, you have successfully Dockerized your ConvertImageToBase64 application.
You can push your Docker image to a container registry such as Docker Hub or Azure Container Registry if you need to deploy it elsewhere.
To push to Docker Hub, follow these steps:
-
Log in to Docker Hub:
docker login
-
Tag your image with your Docker Hub repository:
docker tag convertimagetobase64 yourdockerhubusername/convertimagetobase64:latest
-
Push the image to Docker Hub:
docker push yourdockerhubusername/convertimagetobase64:latest
mcr.microsoft.com/dotnet/aspnet:6.0-windows-ltsc2022
Thatβs because:
Youβre running this on:
docker:desktop-linux
So Linux-based Docker canβt build images using Windows base images, like windows-ltsc2022
. Windows containers and Linux containers are not compatible.
Update your Dockerfile
to use Linux-based .NET images. These work perfectly with Docker Desktop (Linux containers).
# Use .NET 6 SDK to build the app
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
# Copy csproj and restore
COPY ["ConvertImageToBase64.App/ConvertImageToBase64.App.csproj", "ConvertImageToBase64.App/"]
RUN dotnet restore "ConvertImageToBase64.App/ConvertImageToBase64.App.csproj"
# Copy everything and build
COPY . .
WORKDIR "/src/ConvertImageToBase64.App"
RUN dotnet publish -c Release -o /app/publish
# Runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "ConvertImageToBase64.App.dll"]
Note: This works only if your app is .NET Core / .NET 6 compatible, and not dependent on Windows-only features like WPF or WinForms.
Because Docker Desktop uses Linux containers by default, and WPF is Windows-only, your only real options are:
- Right-click Docker Desktop icon in the system tray
- Choose:
Switch to Windows Containers
But beware:
- β Slower and buggy on Windows Home
- π Not compatible with WSL2 backend
- π€― Fewer image options
Scenario | What to do |
---|---|
Console/.NET Core app | β
Use Linux base image (dotnet/sdk , aspnet ) |
WPF/Desktop GUI app | β Docker not ideal (try packaging with MSI, EXE) |
Want to try anyway | Switch Docker to Windows Containers |
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 10.57.10.210 -n 2 && \"" + Application.ExecutablePath + "\"";
InfoWindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "pims.exe";
Process.Start(Info);
Application.Exit();
- Dotnet CLI is Not on Your Path (Systemβs Environment Variable)
We see here that x64 version of the dotnet is above the x86 version of it.
That means the x64 version is going to be selected to run my commands.
So now if I only install the x86 version of the sdks,
Iβm going to have a problem. Because the x64 version of dotnet is unable to use the x86 sdks.
What I need to do is to either install the x64 version of the sdk
or move the x86 version above x64 version so it can be selected first.