C#

C#

C# is a high level, statically typed, object oriented programming language developed by Microsoft. C# code usually targets Microsoft's .NET family of tools and runtimes, which include the .NET Framework and .NET Core.
佴 芬嘉

佴 芬嘉

1685424963

使用 C# 生成图像

在本 C# 教程中,我们将了解如何使用 C# 生成图像。

介绍

要使用 C# 生成图像,您可以使用 System.Drawing 命名空间,它提供用于处理图像的类和方法。

从 NuGet 包管理器下载 NuGet 包 System.Drawing.Common。如果您想了解如何在 Visual Studio 中安装 NuGet 包,请阅读本文 –在 Visual Studio 中安装 NuGet 包

以下是如何生成简单图像的示例:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

在此示例中,我们创建了一个具有所需宽度和高度的新位图对象。然后,我们从图像中获取一个 Graphics 对象,它允许我们在其上绘图。我们使用 DrawRectangle 方法在图像上绘制一个红色矩形。

最后,我们使用 Bitmap 类的 Save 方法将图像保存到文件,指定文件路径和格式(在本例中,我们将其保存为 JPEG 图像)。

保存图像的预览显示在下面的快照中。

请记住在您的项目中添加对 System.Drawing 程序集的引用以使此代码起作用。

文章来源: https: //www.c-sharpcorner.com

#csharp 

使用 C# 生成图像

Gerar imagem usando C#

Neste tutorial C#, aprenderemos como gerar imagens usando C#.

Introdução

Para gerar uma imagem usando C#, você pode utilizar o namespace System.Drawing, que fornece classes e métodos para trabalhar com imagens.

Baixe o pacote NuGet System.Drawing.Common do gerenciador de pacotes NuGet. Se você gostaria de aprender como instalar pacotes NuGet no Visual Studio, siga este artigo – Instalando pacotes NuGet no Visual Studio

Aqui está um exemplo de como você pode gerar uma imagem simples:

using System;using System.Drawing;class Program{    static void Main()    {        // Create a blank image with a specified width and height        int width = 500;        int height = 300;        Bitmap image = new Bitmap(width, height);        // Create a graphics object from the image        Graphics graphics = Graphics.FromImage(image);        // Draw a red rectangle on the image        Pen pen = new Pen(Color.Red);        Rectangle rectangle = new Rectangle(50, 50, 200, 100);        graphics.DrawRectangle(pen, rectangle);        // Save the image to a file        string filePath = "image.jpg";        image.Save(filePath);        // Dispose of the graphics object and image        graphics.Dispose();        image.Dispose();        Console.WriteLine("Image generated and saved successfully.");    }}

Neste exemplo, criamos um novo objeto Bitmap com a largura e altura desejadas. Em seguida, obtemos um objeto Graphics da imagem, que nos permite desenhar sobre ela. Usamos o método DrawRectangle para desenhar um retângulo vermelho na imagem.

Por fim, salvamos a imagem em um arquivo usando o método Save da classe Bitmap, especificando o caminho e o formato do arquivo (neste caso, salvamos como uma imagem JPEG).

Uma visualização da imagem salva é mostrada no instantâneo abaixo.

Lembre-se de adicionar uma referência ao assembly System.Drawing em seu projeto para que esse código funcione.

Fonte do artigo: https://www.c-sharpcorner.com

#csharp 

Gerar imagem usando C#

Сгенерировать изображение с помощью С#

В этом руководстве по C# мы узнаем, как сгенерировать изображение с помощью C#.

Введение

Чтобы сгенерировать изображение с помощью C#, вы можете использовать пространство имен System.Drawing, которое предоставляет классы и методы для работы с изображениями.

Загрузите пакет NuGet System.Drawing.Common из диспетчера пакетов NuGet. Если вы хотите узнать, как установить пакеты NuGet в Visual Studio, следуйте этой статье — Установка пакетов NuGet в Visual Studio.

Вот пример того, как вы можете создать простое изображение:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

В этом примере мы создаем новый объект Bitmap с желаемой шириной и высотой. Затем мы получаем объект Graphics из изображения, который позволяет нам рисовать на нем. Мы используем метод DrawRectangle для рисования красного прямоугольника на изображении.

Наконец, мы сохраняем изображение в файл с помощью метода Save класса Bitmap, указав путь к файлу и формат (в данном случае мы сохраняем его как изображение JPEG).

Предварительный просмотр сохраненного изображения показан на снимке ниже.

Не забудьте добавить ссылку на сборку System.Drawing в свой проект, чтобы этот код работал.

Источник статьи: https://www.c-sharpcorner.com

#csharp 

Сгенерировать изображение с помощью С#
Duy  Tien

Duy Tien

1685360839

Tạo hình ảnh bằng C#

Trong hướng dẫn C# này, chúng ta sẽ tìm hiểu về Cách tạo hình ảnh bằng C#.

Giới thiệu

Để tạo một hình ảnh bằng C#, bạn có thể sử dụng không gian tên System.Drawing, nơi cung cấp các lớp và phương thức để làm việc với hình ảnh.

Tải xuống gói NuGet System.Drawing.Common từ trình quản lý gói NuGet. Nếu bạn muốn tìm hiểu cách cài đặt gói NuGet trong Visual Studio, hãy theo dõi bài viết này - Cài đặt gói NuGet trong Visual Studio

Đây là một ví dụ về cách bạn có thể tạo một hình ảnh đơn giản:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

Trong ví dụ này, chúng tôi tạo một đối tượng Bitmap mới với chiều rộng và chiều cao mong muốn. Sau đó, chúng tôi có được một đối tượng Đồ họa từ hình ảnh, cho phép chúng tôi vẽ trên đó. Chúng ta sử dụng phương thức DrawRectangle để vẽ một hình chữ nhật màu đỏ trên ảnh.

Cuối cùng, chúng tôi lưu hình ảnh vào một tệp bằng phương thức Lưu của lớp Bitmap, chỉ định đường dẫn và định dạng tệp (trong trường hợp này, chúng tôi lưu nó dưới dạng ảnh JPEG).

Bản xem trước của hình ảnh đã lưu được hiển thị trong ảnh chụp nhanh bên dưới.

Hãy nhớ thêm một tham chiếu đến cụm System.Drawing trong dự án của bạn để mã này hoạt động.

Nguồn bài viết: https://www.c-sharpcorner.com

#csharp 

Tạo hình ảnh bằng C#

Generate Image using C#

In this C# tutorial, we will learn about How to Generate Image using C#.

Introduction

To generate an image using C#, you can utilize the System.Drawing namespace, which provides classes and methods for working with images.

Download the NuGet package System.Drawing.Common from NuGet package manager. If you would like to learn how to install NuGet packages in Visual Studio follow this article – Installing NuGet Packages In Visual Studio

Here's an example of how you can generate a simple image:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

In this example, we create a new Bitmap object with the desired width and height. Then, we obtain a Graphics object from the image, which allows us to draw on it. We use the DrawRectangle method to draw a red rectangle on the image.

Finally, we save the image to a file using the Save method of the Bitmap class, specifying the file path and format (in this case, we save it as a JPEG image).

A preview of the saved image is shown in the below snapshot.

Remember to add a reference to the System.Drawing assembly in your project for this code to work.

Article source: https://www.c-sharpcorner.com

#csharp 

Generate Image using C#
Jacob Banks

Jacob Banks

1685343568

Strings in C#: Explained with Examples

In this tutorial, we will learn about C# string, look at some of the newish things about C# strings ... including raw string literals and raw string interpolation that are new in C# 11with the help of examples.

Much of what we work with in our code are strings. Raw string literals make it easy to build complex, multi-line strings, including JSON, in a simple and flexible way. And with no escaping necessary.

Watch the associated video here:

Find the sample code here.

In this article, we'll start with some of the current techniques we use to handle strings, problems we've faced using those techniques, and new C# 11 features that help with our string handling.

Quoted String Literal

The primary way we've worked with strings in C# is using a quoted string literal. These have been available since the beginning of C#.

string header = "<div class=\"card-header\">Vehicle Detail</div>"

But if we have quotes in our string, the string gets a bit messy. We escape those quotes with a backslash. That way the C# compiler can tell the difference between the outside quotes and any quotes within the string.

Standard quoted string literals are often best for single line strings with no characters that need to be escaped.

Verbatim String Literal

For strings that span across multiple lines, we use a verbatim string literal. We define a verbatim string literal with an at sign in front of the first quotation mark. Verbatim means "as is", and is meant to define a multi-line string that displays "as is".

string header = @"
   <div class=""card"">
     <div class=""card-header"">
       Vehicle Detail
   </div>
";

But once again, quotation marks are a challenge! Verbatim string literals require that we use double quotation marks to indicate a quotation mark within a string. This doesn't look horrible in this case ... but when creating a string with lots of quotation marks, like defining JSON, it can be quite messy.

Plus, indentation of verbatim string literals can be a problem.

  foreach (var vehicle in vehicles)
  {
    if (goodCredit)
    {
      if (newVehicle)
      {
        message = @"
          Congratulations on your new vehicle!
          We hope you enjoy driving it as much as we enjoyed building it.
          ";
      }
     }
   }

Above we have a typical bit of code with multiple indentations. And we indent the message nicely within the if block. But then if we display the message, the indentations are included as shown in Figure 1. That may not be the desired result.

Message text indented as defined in the code.

Figure 1. Verbatim string literal retains its indentation

To fix it, we'd have to unindent the text to line up with the left margin.

  foreach (var vehicle in vehicles)
  {
    if (goodCredit)
    {
      if (newVehicle)
      {
        message = @"
Congratulations on your new vehicle!
We hope you enjoy driving it as much as we enjoyed building it.
";
      }
    }
   }

The result is then better as shown in Figure 2. But the code looks a bit messy. And if some unsuspecting developer comes along to "clean up" the indentation, our result is not as we intended.

Message text outdented as defined in the code.

Figure 2. Verbatim string literal must be outdented in the code to appear with no indentation

Raw String Literal (new in C#11)

A new feature in C# 11, released in 2022, is a raw string literal. A raw string literal is a new format for string literals. They allow for whitespace, new lines, embedded quotes, other special characters, or whatever!

A raw string literal begins with at least 3 quotes. And ends with a matching set of quotes. Everything on the lines between the opening and closing quotes is the desired string.

 string header = """
      <div class="card">
        <div class="card-header">
          Vehicle Detail
        </div>
      </div>
    """;

Notice that there is no need for doubling of the quotes or any escape characters. The string displays exactly as it is. This is a much better choice for multi-line strings over the original verbatim string literal.

Another important feature of raw string literals is that the resulting string aligns to the closing quotes. In the example below, we align the message with the beginning of the closing quote.

  foreach (var vehicle in vehicles)
  {
    if (goodCredit)
    {
      if (newVehicle)
      {
        message = """
          Congratulations on your new vehicle!
          We hope you enjoy driving it as much as we enjoyed building it.
          """;
      }
     }
   }

When we display this string, it's aligned appropriately to the left margin as shown in Figure 3.

Hy7tMtzRcGw1AAAAAElFTkSuQmCC

Figure 3. Raw string literal is indented based on the closing quote

Recall that I said that raw string literals start with at least three quotes. The C# team wanted the feature to have a long life, so they made it configurable. If for some reason you need triple quotes within the string, you could use quad quotes to enclose the raw string literal. Just be sure that the string ends with the same number of quotes.

A single line raw string literal requires that the opening and closing quotes are on the same line. Here is a single line raw string literal. Notice the three quotation marks at the beginning and ending. Then the embedded quotes don't require any special characters.

string text = """He said, "None shall Pass"."""

A multiple line raw string literal requires that the opening quotes are on the line above the raw string and the closing quotes are on their own line below the raw string. Here is a JSON string defined using a raw string literal. Notice that we can use normal quotation marks around the field names and string values. So our JSON looks like JSON.

  string vehicleJSON = """
    {
      "id": 1,
      "name": "AT-AT",
      "price": 19416.13
    }
    """;

Since the indenting of the raw string literal is defined by the start of the closing quotes, the text must not be outdented from that closing set of quotes.

The example below has the ending curly brace to the left of the closing quotes. So this code generates a syntax error as shown in Figure 4.

  string vehicleJSON = """
    {
      "id": 1,
      "name": "AT-AT",
      "price": 19416.13
  }
    """;

"Line does not start with the same whitespace as the closing line of the raw string literal"

Figure 4. Error message when raw string literal is outdented beyond the closing quotes

Use raw string literals instead of verbatim strings when working with multiple lines or strings with quotes or other special characters that require escape sequences.

With the power, flexibility, and clarity of the raw string literals, you may never use a verbatim string literal again!

String Interpolation

We often want to include the value of a variable or expression within a string. That's the purpose of interpolation. String interpolation allows us to insert an expression into a string literal.

string pageTitle = "Vehicle Detail";
string header = $"Header: {pageTitle}";

We identify an interpolated string with a dollar sign in front of the first quote. We add one or more expressions into the string using curly braces. The curly braces act as a placeholder.

At runtime, the expression is evaluated and the appropriate value appears in the string in place of the curly braces and expression. This way we can embed the value of a variable or expression in a string literal.

Here are some examples. We can include a calculation or call a method. Any valid C# expression can be inserted within the curly braces.

string answer = $"Answer: { 20 * 2 + 2 }";

string pageTitle = "Vehicle Detail";
string header = $"Header: {PrepareTitle(pageTitle)}";

Constant String Interpolation (New in C# 10)

As of C# 10, we can define an interpolated string as a constant ... but only if the interpolated expression is a constant, like in this example.

const string pageTitle = "Vehicle Detail";
const string header = $"Header: {pageTitle}";

Since the interpolated expression is a constant in this example, the interpolated string can be defined as a constant. This may not be a very common requirement, but it's nice to know the feature is available if you should need it.

Newlines in Interpolation Expressions (New in C# 11)

New in C# 11, we can use multiline interpolated expressions. This can make code within the curly braces a bit easier to read.

In this example, we're using the ternary conditional operator. If the page title variable is empty, we set "no title", otherwise we set the page title. Notice that we must enclose the ternary conditional operator in parentheses within the curly braces.

    string pageTitle = "";

    string header = $"Header: {
      (pageTitle == ""
        ? "No title"
        : pageTitle)
    }";

Putting too much code inside of an interpolation expression makes that code hard to debug and test. So be careful how much code you write within the interpolated expression. In some cases, it may be better to put the code in a function and call that function from the interpolated expression

Verbatim String Interpolation

We can combine string interpolation with verbatim strings using @$ or $@. That way we can have multiple lines of text and optionally, multiple lines for our interpolation expression.

    string pageTitle = "Vehicle Detail";
    string header = @$"
      <div class=""card"">
        <div class=""card-header"">
          {(pageTitle == ""
           ? "No title"
           : pageTitle)}
        </div>
      </div>
    ";

But since it is a verbatim string, we again need double quotes for any embedded quotes.

Raw String Interpolation (New in C# 11)

A better option for string interpolation is raw string interpolation, available in C# 11. Here we add the dollar sign in front of our three sets of quotation marks. Then we can define multiple lines of text and multiple lines for our interpolation expression.

 string pageTitle = "Vehicle Detail";
  string header = $"""
      <div class="card">
        <div class="card-header">
          {(pageTitle == ""
           ? "No title"
           : pageTitle)}
        </div>
      </div>
    """;

Let's look at another example, creating a JSON string. This is the string we want to create. But we want to use interpolation for the price instead of hardcoding it.

   {
      "id": 1,
      "name": "AT-AT",
      "price": 19416.13
    }

Notice that JSON syntax requires curly braces around the object. But if we want to use an interpolated string, the interpolation needs curly braces. So are we going to need to escape those curly braces? Nope!

The C# team wanted a string interpolation solution that was configurable. So for raw string interpolation, we can optionally use two dollar signs. The two dollar signs means that we need two sets of curly braces for the interpolation. That way the single set of curly braces can be interpreted as part of the string literal.

    decimal price = 19416.13M;
    string vehicleJSON = $$"""
      {
        "id": 1,
        "name": "AT-AT",
        "price": {{price}}
      }
      """;

Or we could use three dollar signs with three sets of curly braces, and so on. The number of dollar signs indicates the number of pairs of curly braces required for interpolation.

Very cool!

Wrapping Up

This tutorial walked through options for defining string literals and for string interpolation.

The new raw string literal and raw string interpolation simplify string management, offering a flexible solution for working with strings.

Check out the video here:

Or try out the sample code here.

Source: https://www.freecodecamp.org

#csharp

Strings in C#: Explained with Examples

Сгенерировать изображение с помощью С#

Введение

Чтобы сгенерировать изображение с помощью C#, вы можете использовать пространство имен System.Drawing, которое предоставляет классы и методы для работы с изображениями.

Загрузите пакет NuGet System.Drawing.Common из диспетчера пакетов NuGet. Если вы хотите узнать, как установить пакеты NuGet в Visual Studio, следуйте этой статье — Установка пакетов NuGet в Visual Studio.

Вот пример того, как вы можете создать простое изображение:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

В этом примере мы создаем новый объект Bitmap с желаемой шириной и высотой. Затем мы получаем объект Graphics из изображения, который позволяет нам рисовать на нем. Мы используем метод DrawRectangle для рисования красного прямоугольника на изображении.

Наконец, мы сохраняем изображение в файл с помощью метода Save класса Bitmap, указав путь к файлу и формат (в данном случае мы сохраняем его как изображение JPEG).

Предварительный просмотр сохраненного изображения показан на снимке ниже.

Не забудьте добавить ссылку на сборку System.Drawing в свой проект, чтобы этот код работал.

Оригинальный источник статьи: https://www.c-sharpcorner.com/

#csharp #image 

Сгенерировать изображение с помощью С#

使用 C# 生成图像

介绍

要使用 C# 生成图像,您可以使用 System.Drawing 命名空间,它提供用于处理图像的类和方法。

从 NuGet 包管理器下载 NuGet 包 System.Drawing.Common。如果您想了解如何在 Visual Studio 中安装 NuGet 包,请阅读本文 –在 Visual Studio 中安装 NuGet 包

以下是如何生成简单图像的示例:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

在此示例中,我们创建了一个具有所需宽度和高度的新位图对象。然后,我们从图像中获取一个 Graphics 对象,它允许我们在其上绘图。我们使用 DrawRectangle 方法在图像上绘制一个红色矩形。

最后,我们使用 Bitmap 类的 Save 方法将图像保存到文件,指定文件路径和格式(在本例中,我们将其保存为 JPEG 图像)。

保存图像的预览显示在下面的快照中。

请记住在您的项目中添加对 System.Drawing 程序集的引用,以使此代码生效。

文章原文出处:https: //www.c-sharpcorner.com/

#csharp #image 

使用 C# 生成图像

Generate Image using C#

Introduction

To generate an image using C#, you can utilize the System.Drawing namespace, which provides classes and methods for working with images.

Download the NuGet package System.Drawing.Common from NuGet package manager. If you would like to learn how to install NuGet packages in Visual Studio follow this article – Installing NuGet Packages In Visual Studio

Here's an example of how you can generate a simple image:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a blank image with a specified width and height
        int width = 500;
        int height = 300;
        Bitmap image = new Bitmap(width, height);

        // Create a graphics object from the image
        Graphics graphics = Graphics.FromImage(image);

        // Draw a red rectangle on the image
        Pen pen = new Pen(Color.Red);
        Rectangle rectangle = new Rectangle(50, 50, 200, 100);
        graphics.DrawRectangle(pen, rectangle);

        // Save the image to a file
        string filePath = "image.jpg";
        image.Save(filePath);

        // Dispose of the graphics object and image
        graphics.Dispose();
        image.Dispose();

        Console.WriteLine("Image generated and saved successfully.");
    }
}

In this example, we create a new Bitmap object with the desired width and height. Then, we obtain a Graphics object from the image, which allows us to draw on it. We use the DrawRectangle method to draw a red rectangle on the image.

Finally, we save the image to a file using the Save method of the Bitmap class, specifying the file path and format (in this case, we save it as a JPEG image).

A preview of the saved image is shown in the below snapshot.

Remember to add a reference to the System.Drawing assembly in your project for this code to work.

Original article source at: https://www.c-sharpcorner.com/

#csharp #image 

Generate Image using C#
Desmond  Gerber

Desmond Gerber

1685191271

Devhome: Windows Dev Home Application

Welcome to the Dev Home repo

This repository contains the source code for:

Related repositories include:

Installing and running Dev Home

Note: Dev Home requires Windows 11 21H2 (build 22000) or later.

Microsoft Store [Recommended]

Install Dev Home from the Microsoft Store. This allows you to always be on the latest version when we release new builds with automatic upgrades.

This is our preferred method.

Other install methods

Via GitHub

For users who are unable to install Dev Home from the Microsoft Store, released builds can be manually downloaded from this repository's Releases page.

Via Windows Package Manager CLI (aka winget)

winget users can download and install the latest Dev Home release by installing the Microsoft.DevHome package:

winget install --id Microsoft.DevHome -e

Dev Home roadmap

The plan for Dev Home will be posted shortly and will be updated as the project proceeds.


Dev Home overview

Please take a few minutes to review the overview below before diving into the code:

Dashboard

The Dev Home dashboard displays Windows widgets. These widgets are built using the Windows widget platform, which relies on Adaptive Cards.

Machine configuration

The machine configuration tool utilizes the Dev Home GitHub Extension, but isn't required to clone and install apps. The app installation tool is powered by winget.

Popular apps

The machine configuration tool provides a list of popular apps when selecting applications to install. This is currently a hard-coded list of applications that have been popular with developers on Windows. Popularity was determined by high levels of installation and usage. As this is a moment in time, we are not accepting submissions for this list. We're looking to improve the experience with Suggested Apps so the list can be optimized for developers.


Documentation

Documentation for Dev Home can be found at https://aka.ms/devhomedocs.


Contributing

We are excited to work alongside you, our amazing community, to build and enhance Dev Home!

BEFORE you start work on a feature/fix, please read & follow our Contributor's Guide to help avoid any wasted or duplicate effort.

Communicating with the team

The easiest way to communicate with the team is via GitHub issues.

Please file new issues, feature requests, and suggestions but DO search for similar open/closed preexisting issues before creating a new issue.

If you would like to ask a question that you feel doesn't warrant an issue (yet), please reach out to us via Twitter:

Developer guidance

Building the code

  1. Clone the repository
  2. Configure your system, please use the configuration file. This can be applied by either:
    • Dev Home's machine configuration tool
    • WinGet configuration. If you have the experimental feature enabled, run winget configure .configurations/configuration.dsc.yaml from the project root so relative paths resolve correctly

Running & debugging

In Visual Studio, you should be able to build and debug Dev Home by hitting F5. Make sure to select either the "x64" or the "x86" platform and set DevHome as the selected startup project.


Code of conduct

We welcome contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.


Download Details:

Author: microsoft
Source Code: https://github.com/microsoft/devhome 
License: MIT license

#csharp #windows #dev #application #microsoft 

Devhome: Windows Dev Home Application

How to Create a Neural Network | Train it to Identify Doodles

Exploring how neural networks learn by programming one from scratch in C#, and then attempting to teach it to recognize various doodles and images.

Chapters
0:00 Introduction
2:39 The decision boundary
3:49 Weights
5:42 Biases
6:45 Hidden layers
7:45 Programming the network
9:57 Activation functions
12:42 Cost
15:07 Gradient descent example
18:22 The cost landscape
19:55 Programming gradient descent
21:10 It's learning! (slowly)
23:21 Calculus example
27:34 The chain rule
29:50 Some partial derivatives
33:14 Backpropagation
39:25 Digit recognition
43:56 Drawing our own digits
47:37 Fashion
48:25 Doodles
52:00 The final challenge

Source code: https://github.com/SebLague/Neural-Network-Experiments 
Demo: https://sebastian.itch.io/neural-network-experiment 

The data is from:
Digits http://yann.lecun.com/exdb/mnist/ 
Fashion https://github.com/zalandoresearch/fashion-mnist 
Doodles https://github.com/googlecreativelab/quickdraw-dataset 
Cifar10 https://www.cs.toronto.edu/~kriz/cifar.html 

Subscribe: https://www.youtube.com/@SebastianLague/featured 

#machinelearning #csharp 

How to Create a Neural Network  | Train it to Identify Doodles

Чтение значений из файла App.settings в веб-API

Как читать значения из appsettings.json через интерфейс IOptions в веб-API?

Определите свои свойства в формате ключ-значение в файле Json . Я определил MicroservicesOptions в файле Json.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
  "MicroservicesOptions": {
    "Application1": "App1",
    "Application2": "App2",
    "Application3": "App3"
  }
}

Создайте класс с такими же свойствами и убедитесь, что имена должны быть точно такими же.

public class MicroservicesOptions
{
    public string? Application1 { get; set; }
    public string? Application2 { get; set; }
    public string? Application3 { get; set; }
}

Внедрить конфигурации в Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.Configure<MicroservicesOptions>(Configuration.GetSection("MicroServices"));
}

Теперь добавьте класс, содержащий свойства, в конструктор желаемого класса, где вам нужно.

public class ValuesController : ControllerBase
{
    private readonly MicroservicesOptions _microservicesOptions;
    public ValuesController(IOptions<MicroservicesOptions> options)
    {
        _microservicesOptions = options.Value;
    }
}

Оригинальный источник статьи: https://www.c-sharpcorner.com/

#csharp #webapi 

Чтение значений из файла App.settings в веб-API
木村  直子

木村 直子

1683984780

从 Web API 中的 App.settings 文件读取值

如何通过 Web API 中的 IOptions 接口从 appsettings.json 读取值?

在 Json 文件中以键值格式定义您的属性我在 Json 文件中定义了 MicroservicesOptions。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
  "MicroservicesOptions": {
    "Application1": "App1",
    "Application2": "App2",
    "Application3": "App3"
  }
}

创建一个具有相同属性的类,并确保名称应该完全相同。

public class MicroservicesOptions
{
    public string? Application1 { get; set; }
    public string? Application2 { get; set; }
    public string? Application3 { get; set; }
}

在 Startup.cs 中注入配置。

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.Configure<MicroservicesOptions>(Configuration.GetSection("MicroServices"));
}

现在,在所需类的构造函数中注入一个包含属性的类。

public class ValuesController : ControllerBase
{
    private readonly MicroservicesOptions _microservicesOptions;
    public ValuesController(IOptions<MicroservicesOptions> options)
    {
        _microservicesOptions = options.Value;
    }
}

文章原文出处: https: //www.c-sharpcorner.com/

#csharp #webapi 

从 Web API 中的 App.settings 文件读取值
Waylon  Bruen

Waylon Bruen

1683984660

Read Values From App.settings File in Web API

How to read values from appsettings.json via IOptions Interface in Web API?

Define your properties in the key-value format in the Json file. I defined  MicroservicesOptions in the Json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
  "MicroservicesOptions": {
    "Application1": "App1",
    "Application2": "App2",
    "Application3": "App3"
  }
}

Make a class with the same properties, and make sure names should be exactly the same.

public class MicroservicesOptions
{
    public string? Application1 { get; set; }
    public string? Application2 { get; set; }
    public string? Application3 { get; set; }
}

Inject configurations in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.Configure<MicroservicesOptions>(Configuration.GetSection("MicroServices"));
}

Now Inject a class containing properties in the constructor of your desired class where you need.

public class ValuesController : ControllerBase
{
    private readonly MicroservicesOptions _microservicesOptions;
    public ValuesController(IOptions<MicroservicesOptions> options)
    {
        _microservicesOptions = options.Value;
    }
}

Original article source at: https://www.c-sharpcorner.com/

#csharp #webapi 

Read Values From App.settings File in Web API
Royce  Reinger

Royce Reinger

1683978360

An unofficial C#/.NET SDK for accessing the OpenAI GPT-3 API

C#/.NET SDK for accessing the OpenAI GPT-3 API, ChatGPT, and DALL-E 2

A simple C# .NET wrapper library to use with OpenAI's GPT-3 API. More context on my blog. This is an unofficial wrapper library around the OpenAI API. I am not affiliated with OpenAI and this library is not endorsed or supported by them.

Quick Example

var api = new OpenAI_API.OpenAIAPI("YOUR_API_KEY");
var result = await api.Completions.GetCompletion("One Two Three One Two");
Console.WriteLine(result);
// should print something starting with "Three"

Status

Added support for GPT4, streaming conversations with ChatGPT, and supporting IHttpClientFactory.

Should work with the Azure OpenAI Service. See the Azure section for further details.

Thank you @babrekel, @JasonWei512, @GotMike, @megalon, @stonelv, @ncface, @KeithHenry, @gmilano, @metjuperry, @pandapknaepel, and @Alexei000 for your contributions!

Requirements

This library is based on .NET Standard 2.0, so it should work across .NET Framework >=4.7.2 and .NET Core >= 3.0. It should work across console apps, winforms, wpf, asp.net, etc (although I have not yet tested with asp.net). It should work across Windows, Linux, and Mac, although I have only tested on Windows so far.

Getting started

Install from NuGet

Install package OpenAI from Nuget. Here's how via commandline:

Install-Package OpenAI

Authentication

There are 3 ways to provide your API keys, in order of precedence:

  1. Pass keys directly to APIAuthentication(string key) constructor
  2. Set environment var for OPENAI_API_KEY (or OPENAI_KEY for backwards compatibility)
  3. Include a config file in the local directory or in your user directory named .openai and containing the line:
OPENAI_API_KEY=sk-aaaabbbbbccccddddd

You use the APIAuthentication when you initialize the API as shown:

// for example
OpenAIAPI api = new OpenAIAPI("YOUR_API_KEY"); // shorthand
// or
OpenAIAPI api = new OpenAIAPI(new APIAuthentication("YOUR_API_KEY")); // create object manually
// or
OpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromEnv()); // use env vars
// or
OpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromPath()); // use config file (can optionally specify where to look)
// or
OpenAIAPI api = new OpenAIAPI(); // uses default, env, or config file

You may optionally include an openAIOrganization (OPENAI_ORGANIZATION in env or config file) specifying which organization is used for an API request. Usage from these API requests will count against the specified organization's subscription quota. Organization IDs can be found on your Organization settings page.

// for example
OpenAIAPI api = new OpenAIAPI(new APIAuthentication("YOUR_API_KEY","org-yourOrgHere"));

ChatGPT

The Chat API is accessed via OpenAIAPI.Chat. There are two ways to use the Chat Endpoint, either via simplified conversations or with the full Request/Response methods.

Chat Conversations

The Conversation Class allows you to easily interact with ChatGPT by adding messages to a chat and asking ChatGPT to reply.

var chat = api.Chat.CreateConversation();

/// give instruction as System
chat.AppendSystemMessage("You are a teacher who helps children understand if things are animals or not.  If the user tells you an animal, you say \"yes\".  If the user tells you something that is not an animal, you say \"no\".  You only ever respond with \"yes\" or \"no\".  You do not say anything else.");

// give a few examples as user and assistant
chat.AppendUserInput("Is this an animal? Cat");
chat.AppendExampleChatbotOutput("Yes");
chat.AppendUserInput("Is this an animal? House");
chat.AppendExampleChatbotOutput("No");

// now let's ask it a question'
chat.AppendUserInput("Is this an animal? Dog");
// and get the response
string response = await chat.GetResponseFromChatbotAsync();
Console.WriteLine(response); // "Yes"

// and continue the conversation by asking another
chat.AppendUserInput("Is this an animal? Chair");
// and get another response
response = await chat.GetResponseFromChatbotAsync();
Console.WriteLine(response); // "No"

// the entire chat history is available in chat.Messages
foreach (ChatMessage msg in chat.Messages)
{
    Console.WriteLine($"{msg.Role}: {msg.Content}");
}

Streaming

Streaming allows you to get results are they are generated, which can help your application feel more responsive.

Using the new C# 8.0 async iterators:

var chat = api.Chat.CreateConversation();
chat.AppendUserInput("How to make a hamburger?");

await foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())
{
    Console.Write(res);
}

Or if using classic .NET Framework or C# <8.0:

var chat = api.Chat.CreateConversation();
chat.AppendUserInput("How to make a hamburger?");

await chat.StreamResponseFromChatbotAsync(res =>
{
    Console.Write(res);
});

Chat Endpoint Requests

You can access full control of the Chat API by using the OpenAIAPI.Chat.CreateChatCompletionAsync() and related methods.

async Task<ChatResult> CreateChatCompletionAsync(ChatRequest request);

// for example
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
    {
        Model = Model.ChatGPTTurbo,
        Temperature = 0.1,
        MaxTokens = 50,
        Messages = new ChatMessage[] {
            new ChatMessage(ChatMessageRole.User, "Hello!")
        }
    })
// or
var result = api.Chat.CreateChatCompletionAsync("Hello!");

var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
// or
Console.WriteLine(results);

It returns a ChatResult which is mostly metadata, so use its .ToString() method to get the text if all you want is assistant's reply text.

There's also an async streaming API which works similarly to the Completions endpoint streaming results.

Completions

The Completion API is accessed via OpenAIAPI.Completions:

async Task<CompletionResult> CreateCompletionAsync(CompletionRequest request);

// for example
var result = await api.Completions.CreateCompletionAsync(new CompletionRequest("One Two Three One Two", model: Model.CurieText, temperature: 0.1));
// or
var result = await api.Completions.CreateCompletionAsync("One Two Three One Two", temperature: 0.1);
// or other convenience overloads

You can create your CompletionRequest ahead of time or use one of the helper overloads for convenience. It returns a CompletionResult which is mostly metadata, so use its .ToString() method to get the text if all you want is the completion.

Streaming

Streaming allows you to get results are they are generated, which can help your application feel more responsive, especially on slow models like Davinci.

Using the new C# 8.0 async iterators:

IAsyncEnumerable<CompletionResult> StreamCompletionEnumerableAsync(CompletionRequest request);

// for example
await foreach (var token in api.Completions.StreamCompletionEnumerableAsync(new CompletionRequest("My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1)))
{
    Console.Write(token);
}

Or if using classic .NET framework or C# <8.0:

async Task StreamCompletionAsync(CompletionRequest request, Action<CompletionResult> resultHandler);

// for example
await api.Completions.StreamCompletionAsync(
    new CompletionRequest("My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1),
    res => ResumeTextbox.Text += res.ToString());

Embeddings

The Embedding API is accessed via OpenAIAPI.Embeddings:

async Task<EmbeddingResult> CreateEmbeddingAsync(EmbeddingRequest request);

// for example
var result = await api.Embeddings.CreateEmbeddingAsync(new EmbeddingRequest("A test text for embedding", model: Model.AdaTextEmbedding));
// or
var result = await api.Embeddings.CreateEmbeddingAsync("A test text for embedding");

The embedding result contains a lot of metadata, the actual vector of floats is in result.Data[].Embedding.

For simplicity, you can directly ask for the vector of floats and disgard the extra metadata with api.Embeddings.GetEmbeddingsAsync("test text here")

Moderation

The Moderation API is accessed via OpenAIAPI.Moderation:

async Task<ModerationResult> CreateEmbeddingAsync(ModerationRequest request);

// for example
var result = await api.Moderation.CallModerationAsync(new ModerationRequest("A test text for moderating", Model.TextModerationLatest));
// or
var result = await api.Moderation.CallModerationAsync("A test text for moderating");

Console.WriteLine(result.results[0].MainContentFlag);

The results are in .results[0] and have nice helper methods like FlaggedCategories and MainContentFlag.

Files (for fine-tuning)

The Files API endpoint is accessed via OpenAIAPI.Files:

// uploading
async Task<File> UploadFileAsync(string filePath, string purpose = "fine-tune");

// for example
var response = await api.Files.UploadFileAsync("fine-tuning-data.jsonl");
Console.Write(response.Id); //the id of the uploaded file

// listing
async Task<List<File>> GetFilesAsync();

// for example
var response = await api.Files.GetFilesAsync();
foreach (var file in response)
{
    Console.WriteLine(file.Name);
}

There are also methods to get file contents, delete a file, etc.

The fine-tuning endpoint itself has not yet been implemented, but will be added soon.

Images

The DALL-E Image Generation API is accessed via OpenAIAPI.ImageGenerations:

async Task<ImageResult> CreateImageAsync(ImageGenerationRequest request);

// for example
var result = await api.ImageGenerations.CreateImageAsync(new ImageGenerationRequest("A drawing of a computer writing a test", 1, ImageSize._512));
// or
var result = await api.ImageGenerations.CreateImageAsync("A drawing of a computer writing a test");

Console.WriteLine(result.Data[0].Url);

The image result contains a URL for an online image or a base64-encoded image, depending on the ImageGenerationRequest.ResponseFormat (url is the default).

Image edits and variations are not yet implemented.

Azure

For using the Azure OpenAI Service, you need to specify the name of your Azure OpenAI resource as well as your model deployment id.

I do not have access to the Microsoft Azure OpenAI service, so I am unable to test this functionality. If you have access and can test, please submit an issue describing your results. A PR with integration tests would also be greatly appreciated. Specifically, it is unclear to me that specifying models works the same way with Azure.

Refer the Azure OpenAI documentation and detailed screenshots in #64 for further information.

Configuration should look something like this for the Azure service:

OpenAIAPI api = OpenAIAPI.ForAzure("YourResourceName", "deploymentId", "api-key");
api.ApiVersion = "2023-03-15-preview"; // needed to access chat endpoint on Azure

You may then use the api object like normal. You may also specify the APIAuthentication is any of the other ways listed in the Authentication section above. Currently this library only supports the api-key flow, not the AD-Flow.

As of April 2, 2023, you need to manually select api version 2023-03-15-preview as shown above to access the chat endpoint on Azure. Once this is out of preview I will update the default.

IHttpClientFactory

While this library does not fully support dependancy injection at this time, you may specify an IHttpClientFactory to be used for HTTP requests, which allows for tweaking http request properties, connection pooling, and mocking. Details in #103.

OpenAIAPI api = new OpenAIAPI();
api.HttpClientFactory = myIHttpClientFactoryObject;

Documentation

Every single class, method, and property has extensive XML documentation, so it should show up automatically in IntelliSense. That combined with the official OpenAI documentation should be enough to get started. Feel free to open an issue here if you have any questions. Better documentation may come later.


Download Details:

Author: OkGoDoIt
Source Code: https://github.com/OkGoDoIt/OpenAI-API-dotnet 
License: View license

#csharp #gpt #machinelearning #sdk #dotnet #ml #openai 

An unofficial C#/.NET SDK for accessing the OpenAI GPT-3 API