/r/csharp

Photograph via snooOG

All about the object-oriented programming language C#.

Information about Reddit's API changes, the unprofessional conduct of the CEO, and their response to the community's concerns regarding 3rd party apps, moderator tools, anti-spam/anti-bot tools, and accessibility options that will be impacted can be found in the associated Wikipedia article: https://en.wikipedia.org/wiki/2023_Reddit_API_controversy

Alternative C# communities available outside Reddit on Lemmy and Discord:


All about the object-oriented programming language C#.


Getting Started
C# Fundamentals: Development for Absolute Beginners

Useful MSDN Resources
A Tour of the C# Language
Get started with .NET in 5 minutes
C# Guide
C# Language Reference
C# Programing Guide
C# Coding Conventions
.NET Framework Reference Source Code

Other Resources
C# Yellow Book
Dot Net Perls
The C# Player's Guide

IDEs
Visual Studio
MonoDevelop (Windows/Mac/Linux)
Rider (Windows/Mac/Linux)

Tools
ILSpy
dotPeek
LINQPad

Alternative Communities
C# Discord Group
C# Lemmy Community
dotnet Lemmy Community

Related Subreddits
/r/dotnet
/r/azure
/r/learncsharp
/r/learnprogramming
/r/programming
/r/dailyprogrammer
/r/programmingbuddies
/r/cshighschoolers

Additional .NET Languages
/r/fsharp
/r/visualbasic

Platform-specific Subreddits
/r/windowsdev
/r/AZURE
/r/Xamarin
/r/Unity3D
/r/WPDev

Rules:

  • Rule 1: No job postings (For Hire and Hiring)
  • Rule 2: No malicious, intentionally harmful, or piracy-related software
  • Rule 3: Posts should be directly relevant to C#
  • Rule 4: Request-for-help posts should be made with effort
  • Rule 5: No hostility towards users for any reason
  • Rule 6: No spam of tools/companies/advertisements
  • Rule 7: Submitted links to be made with effort and quality
  • Rule 8: No unattributed use or automated use of AI Generation Tools

Read detailed descriptions of the rules here.

/r/csharp

279,058 Subscribers

51

The most popular C# articles in 2024

Hello, đź‘‹

I run a popular .NET email newsletters called C# Digest. And I thought it might be fun to look into what were the most popular articles this year.

This is a crowd pleaser by Ken Fedorov. Everyone would like to pick up some new tricks into their sleeves.

David shared various C# 12 refactoring scenarios for a variety of target types using collection expressions and collection initializers.

Entity Framework has been around for 16 (!) years now. And while many of us are using it actively, not everyone is fortunate enough to be able to update with every new release. Dennis shared some of the neat features of the new release.

Performance optimizations are a super popular topic in the newsletter. From Matt Warren’s classics we have Aaron’s article making the top 5 this year.

Steven has published heaps of articles in 2024 but LINQ spans every .NET domain and learning the new features improves the quality of life of every C# developer.

Keep in mind that these might not be the best but the most popular posts. Some of the niche deep dives that I loved over this year didn’t get as many eyeballs as they’d deserve but oh well.

Oh and if you liked some of these consider checking C# Digest out. It’s a simple hand-curated weekly newsletter for C# devs that want to maintain their edge in the .NET space.

Edit: list formatting

6 Comments
2024/12/20
16:40 UTC

0

Clipboard Confusion.

Using winforms.

I am having difficulty setting some rich text into my clipboard so that I can paste it into any other program. I will include the code below, but this is baffling.

I can get it to work to paste into programs like word or web applications like g-mail, but I can never get it to be able to paste into both at the same time.

Yet I know that this is possible because other programs do it.

In the code below, if I comment out the HTML formatting then it works fine to paste into Word, but then it will no longer paste correctly into web applications like gmail. If I leave it uncommented, it works fine for web applications, but will no longer paste into word.

public void SetClipboardData(string rtf, string html)

{

html = Rtf.ToHtml(rtf);

RichTextBox tempRTB = new RichTextBox();

tempRTB.Rtf = rtf;

string tstring = tempRTB.Text;

// Prepare the clipboard data in a standardized format

string htmlClipboardData = BuildHtmlClipboardData(html);

// Create a DataObject to store multiple formats

DataObject dataObject = new DataObject();

// Add HTML format (for Gmail and web editors)

// If I comment this out then the clipboard will word for Word.

// If I do not then it will not paste into word, but will paste

// into gmail.

if (!string.IsNullOrEmpty(htmlClipboardData))

dataObject.SetData(DataFormats.Html, htmlClipboardData);

// Add RTF format (for Word and similar apps)

if (!string.IsNullOrEmpty(rtf))

dataObject.SetData(DataFormats.Rtf, rtf);

// Add Plain Text (as a fallback for basic editors)

string plainText = tstring; // Assuming you have a method to extract plain text

if (!string.IsNullOrEmpty(plainText))

dataObject.SetData(DataFormats.Text, plainText);

// Set the clipboard data

Clipboard.SetDataObject(dataObject, true);

}

0 Comments
2024/12/20
16:34 UTC

1

Updating Word TOC using OpenXML

Hello guys, does everyone know how to update Microsoft Word TOC (table of content) within “.docx” files using only “open XML” library?

I have seen a few implementations that use “Microsoft Interop” library but I don’t have the possibility to download Word program within the environment.

What I need to do is to update an already existing table of content, and I have all the styles used within the file.

Do you have any idea?

0 Comments
2024/12/20
15:42 UTC

0

New .NET MAUI book: Build a full-featured app swiftly with MVVM, CRUD, AI, authentication, real-time updates, and more

As Benjamin Franklin wisely said, 'An investment in knowledge pays the best interest.' This feels more relevant than ever in today’s fast-paced world of technology. For all you .NET MAUI developers out there, I’ve written a book to help you invest your time wisely. Check it out here: .NET MAUI Cookbook: Build a full-featured app swiftly with MVVM, CRUD, AI, authentication, real-time updates, and more

The book includes over 50 step-by-step recipes to help you build practical skills faster. You’ll dive into real-world topics such as:

  • Creating robust, adaptive layouts with advanced XAML
  • Implementing MVVM, DI, cached repository, and unit of work patterns
  • Adding authentication with self-hosted services and Google OAuth
  • Managing sessions and role-based data access
  • Handling real-time updates, chunked file uploads, and offline data modes
  • Integrating AI, from local devices to cloud models
  • Leveraging platform-specific APIs
  • Troubleshooting performance and memory issues

To improve the learning experience, I’ve created a set of GitHub examples that are freely available, even if you decide not to purchase the book: .NET-MAUI-Cookbook

I’d love to hear your thoughts and feedback - thank you for your support!

.NET MAUI Cookbook

1 Comment
2024/12/20
14:51 UTC

4

Controlling state changes from the root object

Hey all. I have the following structure of objects, which basically consists of a `PhaseHolder`, which contains a collection of `Phase`. Each `Phase` can hold a `Comment`, and each `Comment` can hold a list of `Reply`.

public class PhaseHolder
{
    private readonly List<Phase> _phases = new();

    public IReadOnlyCollection<Phase> Phases => _phases.AsReadOnly();

    public bool IsCommentable { get; set; }

    public void AddPhaseComment(string comment)
    {
        var phase = _phases.FirstOrDefault();

        if (phase != null && IsCommentable)
        {
            phase.AddComment(comment);
        }
    }

    public void AddPhase()
    {
        _phases.Add(new Phase());
    }
}

public class Phase
{
    private readonly List<Comment> _comments = new();

    public IReadOnlyCollection<Comment> Comments => _comments.AsReadOnly();

    public void AddComment(string comment)
    {
        _comments.Add(new Comment(comment));
    }
}

public class Comment
{
    private readonly List<Reply> _replies = new();

    public IReadOnlyCollection<Reply> Replies => _replies.AsReadOnly(); 

    public string Description { get; set; }

    public Comment(string comment)
    {
        Description = comment;
    }

    public void AddReply(string reply)
    {
        _replies.Add(new Reply(reply));
    }
}

public class Reply
{
    internal string Description { get; set; }

    public Reply(string description)
    {
        Description = description;
    }
}

The `PhaseHolder` object contains a `bool` property that should control whether comments can be added to any of the phases.

However, it seems this can easily be circumvented, e.g.:

var phaseHolder = new PhaseHolder();
phaseHolder.AddPhase();
phaseHolder.AddPhaseComment("Adding comment in desired way");
var phase = phaseHolder.Phases.FirstOrDefault();
phase?.AddComment("Avoiding IsCommentable check");

These objects are in the same assembly, so no easy ability to make use of `internal` access modifiers. Are there any other obvious approaches I'm not seeing to forcing all comments to go through the `PhaseHolder` method?

9 Comments
2024/12/20
14:52 UTC

0

We have 60 000 stock data products that we update price every 2 seconds to our 10 000 clients, what is the best way to push these updates from .NET API to ReactJS clients?

We have 60 000 stock data products that we update price every 2 seconds to our 10 000 clients. On our frontend data table with 60 000 products that potentially needs to send out updates every 2 seconds to all of our clients.

Is the best way to push these updates from .NET API to ReactJS clients?

11 Comments
2024/12/20
14:35 UTC

0

Resource for Junior .Net interview questions ?? (I have 9 months of experience)

https://preview.redd.it/tt0yt3rkvz7e1.png?width=670&format=png&auto=webp&s=0062dfd4bc5ae9f70fae199cb0c84ad4d9ddfd2d

I have been working at my first ever dev job for 9 months now, sadly 90% of my job involves Angular (angular 16 to be exact) and only 10% is backend stuff, some debugging and minor bug fixes that the backend dev didnt notice but i did

I wanna get away from this company because they pay people that have over 6 months to 1 year of experience minimal wage, i have also had periods where i had nothing to do, no work no tasks and i just sat there doing nothing

My .Net skills arent that good, im inteviewing at a company on monday and on the image you see is the requirements that the company needs for the role im gonna be interviewed, i have done some small projects with .Net Core Web API with sql server but im not as good for someone with 9 months of experience since i barely touch the backend, and i wanna work more on the backend!

What sources would you suggest for learning some .net interview questions (yes i have 9 months of experience and on the requirements it says 3 years, but they still called me for an interview)

Also any tips in general for the interview? I Havent touched any Azure or Docker, i also havent used Moq nor do i know what that is, i also havent done any unit tests

Im planning to do some research to at least know how to explain what this stuff is, and maybe do a bit of coding to remind myself of Dapper and sql server and write some unit tests too!

7 Comments
2024/12/20
12:14 UTC

0

Halppp

"The problem occurs when UserA logs into the application and performs any navigation. At the same time, UserB logs into the application and performs navigation. If UserA refreshes their browser during this process, they realize that their session has been replaced by UserB's session (who logged in recently). I am storing user data in a global variable in the session during login. However, I am clearing the session using session.clear() during login, but this is not solving my problem."

9 Comments
2024/12/20
11:59 UTC

2

I need guidance

So in my class I was told to do a project in C# about managing a company. I'm not entirely sure why I even have programming as a subject, don't take it the wrong way. It's difficult and I don't like it so it's hard for me. Anyways, I'm going to put here exactly what the teacher asked. I'm not asking to for ya'll to do it for me because that's kinda disrespectful, Im only asking for help/how would you do it/what some important parts are. Any help would be appreciated. (By the way, English isn't my native language and the project that I'm going to paste below might not be well translated as I asked ChatGPT to translate it for me)

"The objective of this project is to develop a robust management system to optimize the order and production processes of a company. The system should efficiently manage customers, suppliers, products, raw materials, and orders. Production will be carried out exclusively to fulfill received orders, without maintaining a stock of finished products. The system must check the availability of raw materials, considering the current stock and established minimum levels, and provide information about the need for new raw material orders to ensure the proper fulfillment of all orders. Consider the following:

The system must allow the insertion, updating, removal, and search/listing of entities, namely:

Customers: Record essential information such as name, address, email, and phone number.

Suppliers: Register data such as company name, contact, and address.

Products: Maintain detailed records about products, including name, code, description, and the respective Bill of Materials (BOM). The BOM should specify the quantity and type of raw materials required for the product's production.

Raw Materials: Register the materials needed for production, including name, available quantity, associated supplier, and the definition of a minimum stock level for each material.

Orders: Record customer orders, including information about the customer, ordered products, requested quantities, and status. Orders can have statuses such as Pending, In Production, or Completed. Only orders with Pending and In Production statuses should be considered for calculating the stock to order.

Entity removal must be restricted to prevent the deletion of entities associated with others. For example, it should not be possible to delete a supplier that has associated raw materials or a customer with pending orders. To implement this restriction, use a boolean state, such as deleted, to mark entities as "deleted." Entities with the deleted state set to true should not be visible or selectable. For instance, suppliers marked as deleted should not appear in the list of available suppliers for raw materials.

The system must verify the availability of raw materials required for production, based on the BOM of each product, ensuring that the minimum stock level is maintained.

When raw material stock falls below the minimum level, the system should generate an alert for replenishment from suppliers.

Data must be stored in JSON files to ensure the persistence and integrity of information. At the start of the program, the data should be read from the file, and at the end, the file should be updated with the changes made.

The system must allow the selection of at least two distinct reports from the menu. Examples of reports include:

Available and required raw material stock to meet pending orders, according to the BOM of each product.

Alerts for stock below the minimum level. Each group should propose the production of reports, considering the administrator's interests and the importance of the information for management. One objective is to evaluate the understanding of the problem and the ability to analyze stored data.

The system must implement the generation of at least two graphs to represent data and allow process analysis. Examples of graphs include:

The distribution of raw material stock.

The evolution of orders over time."

4 Comments
2024/12/20
11:02 UTC

9

Programming opportunities for people over 30

I am 34 years old this year, I graduated from college of information technology but in the field of network and system, I worked for 4 years then switched to family business, now I want to return to the field I studied, specifically web programming, I am quite interested in C# and ASP core, everyone let me ask if there are still career opportunities for me in web programming in 2025, when AI is increasingly popular and GPT chat is almost too developed for me and new graduates to find a job.

23 Comments
2024/12/20
08:17 UTC

2

Reading documentation

Hello,

I often see people asking for good books or resources to learn programming, and many responses simply recommend reading the documentation. However, I've been programming for about seven months now, and while I have a solid grasp of the basics and some familiarity with libraries (especially ones with easy-to-understand documentation), this progress is largely thanks to using tools like ChatGPT to explain things to me.

Whenever I try to learn directly from documentation, I tend to get lost in rabbit holes or struggle to understand the material. On one hand, I’d like some tips on how to effectively learn from documentation and make it my primary resource. On the other hand, do you think starting with the C# documentation is truly the best way to begin learning the language?

7 Comments
2024/12/20
08:10 UTC

0

EF Core - ordering problem

Hi. I have 3 datas on table like this:

https://preview.redd.it/n630tnxozx7e1.png?width=730&format=png&auto=webp&s=0ac96d8f2da6a84e3a38f907194fbf769891b16a

This is initial state of creating query:

var existingPost = _unitOfWork.PostRepository.GetAll()
    .Where(post => post.TranslationsPostSlugs.Any(slugTranslation => slugTranslation.Translation_Slug == slug))
    .Include(post => post.ImagePaths)
    .Include(post => post.VideoPaths)
    .Include(post => post.TranslationsPost.Where(x => x.LanguageId == LanguageId || LanguageId == null))
    .Include(post => post.TranslationsPostSlugs.Where(x => x.LanguageId == LanguageId || LanguageId == null))
    .FirstOrDefault();

When im trying to get 'TranslationsPostSlugs' datas inside foreach block i get them in wrong order (2 1 3, but expected order is as in table - 1 2 3):

var r1 = existingPost.TranslationsPostSlugs.ToList(); // r1 : Wrong order - 2 1 3
var r2 = existingPost.TranslationsPostSlugs.OrderBy(x => x.LanguageId).ToList(); // r2 : Valid order - 1 2 3

existingPost.TranslationsPostSlugs.ForEach(postSlugTranslation =>
{
    Console.WriteLine($"================================ DATA : {postSlugTranslation.LanguageId}");

    result.TranslationsPostSlugs.Add(new GetPostSlugsTranslationResponseDTO()
    {
        LanguageId = postSlugTranslation.LanguageId,
        Slug = postSlugTranslation.Translation_Slug
    });

    /* result:
        ================================ DATA : 2
        ================================ DATA : 1
        ================================ DATA : 3
    */
});

// My current fix to this ordering problem in 'TranslationsPostSlugs':
result.TranslationsPostSlugs = result.TranslationsPostSlugs.OrderBy(x => x.LanguageId).ToList();
  1. Why ordering happens? Why ordering happens only to 'TranslationsPostSlugs', but not to 'TranslationsPost'?

  2. Can you guys recommend any good solution to this ordering problem than mine?

p.s. i dont have any ordering configuration anywhere, everything is in his default behaviour.

Thanks.

5 Comments
2024/12/20
05:48 UTC

0

Speak to me in a relevant, high-level language : C#, classic asp/vb ?

Just for fun, as always, let's carry on a conversation in a c or basic style ((language)dialect))

0 Comments
2024/12/20
04:13 UTC

13

How did you guys learn C#?

I'm trying to learn it so I can make games, of course, I know I'll have to start small, but the first steps are learning it, without college.

54 Comments
2024/12/20
03:29 UTC

14

Question about "Math.Round"

"Math.Round" rounds numbers to the nearest integer/decimal, e.g. 1.4 becomes 1, and 1.6 becomes 2.

By default, midpoint is rounded to the nearest even integer/decimal, e.g. 1.5 and 2.5 both become 2.

After adding "MidpointRounding.AwayFromZero", everything works as expected, e.g.

  • 1.4 is closer to 1 so it becomes 1.
  • 1.5 becomes 2 because "AwayFromZero" is used for midpoint.
  • 1.6 is closer to 2 so it becomes 2.

What I don't understand is why "MidpointRounding.ToZero" doesn't seem to work as expected, e.g.

  • 1.4 is closer to 1 so it becomes 1 (so far so good).
  • 1.5 becomes 1 because "ToZero" is used for midpoint (still good).
  • 1.6 is closer to 2 so it should become 2, but it doesn't. It becomes 1 and I'm not sure why. Shouldn't "ToZero" affect only midpoint?
32 Comments
2024/12/19
22:13 UTC

0

Multiple-point floating point precision in c#?

I know c# doesnt natively support arbitrary or multiple-point floating point precision calculations, but what libraries would you reccomend? Could you also please give a little code example? Thanks to everyone in advance

17 Comments
2024/12/19
21:27 UTC

1

How Can I Bridge the Gap Between My Current Role and My Skills?

I've been labeled as a mid-level developer at my job, but I feel like I’m not quite there yet, especially when it comes to theoretical knowledge. While my practical programming skills are decent, I struggle to explain concepts effectively. Can someone guide me on how or where to find resources and definitions to improve my understanding and communication skills, so I can confidently align myself with the expectations of my role?

4 Comments
2024/12/19
21:16 UTC

4

Any recommendation on learning OOP

Any recommendations for learning OOP, from scratch, perhaps?? This whole oop got me messed up and now I will be writing some dotnet applications (APIs)... I understand classes, object and inheritance... however when the concepts of design patterns and architecture comes in then it is a whole mess... Any recommendations will be highly appreciated.. especially from a practical point of view...

7 Comments
2024/12/19
17:18 UTC

0

how to disable Automatic Model State Validation in ASP.NET Core?

Faced with the problem that my program does not want to validate Null, Empty string. After some time I found that the validation doesn't even reach my Validation class from Fluent Validation. And checking whether more than 3 characters are entered works. After digging a little on the Internet, I found that the problem may be in: Automatic Model State Validation in ASP.NET Core. Tried many ways but for some reason I can turn it off for API only with

services.Configure<ApiBehaviorOptions>(options =>{

options.SuppressModelStateInvalidFilter = true;});

On the API side, it started reaching the class with validation. But it doesn't work for UI. Does anyone know how to turn this off?

11 Comments
2024/12/19
17:07 UTC

31

Is WebForms still popular or is it still active?

I work in a one man IT company, my main role is support and infrastructure, as I took c# programming at university I started to develop small modules in winforms and later in asp.net webforms, I love webforms and I keep developing small web modules in this framewokr, I have just started to investigate about core, mvc but I don't really understand it and it is very difficult to understand, it is much easier to understand the logic and read webforms code than core, what about webforms being popular? Will it stop being supported or do you think it has a future? Bascally im only made not big things, basi login web with sql store procedure, and CRUD info to sql server, i dont use javascript or any other technology. Pure ASP NET WEBFORMS + SQL SERVER querys and store procedures.

Thanks

68 Comments
2024/12/19
15:58 UTC

7

Need guidance with web development in C#

Hello, so i am trying to learn c# to find a job and im kinda stuck for the last couple of weeks.
I started off november 2023 and i learned entry C#, OOP, a bit of LINQ, then I moved to making some projects (made 2 WPF projects that are connected to MS SQL database for some basic CRUD functions using dapper), lately I have been trying to dive into entity framework core. And now I am trying to learn more about web development (ASP.NET CORE) and I am at a spot where I am not quite sure what should I focus on. I have been trying to learn about ASP.NET but I just can't seem to get to start anything meaningful going and my question is, where should I start and what should I prioritize learning.

3 Comments
2024/12/19
13:48 UTC

48

How to actually read this syntax

I started .net with VB.net in 2002 (Framework 0.9!) and have been doing C# since 2005. And yet some of the more modern syntax does not come intuitively to me. I'm closing in on 50, so I'm getting a bit slower.

For example I have a list that I need to convert to an array.

return columns.ToArray();

Visual Studio suggests to use "collection expression" and it does the right thing but I don't know how to "read it":

return [.. columns];

What does this actually mean? And is it actually faster than the .ToArray() method or just some code sugar?

63 Comments
2024/12/19
09:14 UTC

1

NodaTime dates comparison

Hello, I'm looking for a way to compare Instant objects with some precision (in my case i don't want to take nanoseconds into account). Is there a way to do it without creating new objects from parts?

2 Comments
2024/12/19
07:54 UTC

0

My C# script isn't working (Unity)

1 Comment
2024/12/19
06:38 UTC

3

Approach to ASP.NET Secrets Management

Hello!

Main question: Have I overthought my approach to secrets management? And/Or, am I missing an easier solution?

Project details: ASP.NET MVC with .NET 9.0. Controller, Service, Repository/Client design pattern. Application hosted via IIS on a server.

Project constraints: Not able to use third-party hosted services (Azure Key Vault, AWS Secrets Manager), must handle API keys updating at runtime, data must be encrypted at rest and secrets must not be included in repository.

I've researched through official Microsoft documentation, youtube videos and various articles about using appsettings.json, visual studio user secrets and environment variables. Each of these solutions you can seamlessly use the configuration manager which is a plus but I've found each solution has a separate issue.

  • Appsettings.json - Stored in plaintext, kept inside repository, must copy-paste file(s) across dev, staging and production
    • Note: could store each secret encrypted and decrypt the string inside the solution and put appsettings in .gitignore
  • VS User Secrets - strictly designed for development and not for use in production
  • Environment Variables - can't be updated at runtime

The main solution I've found is to use Azure or AWS to securely manage all secrets in dev, staging and prod. Unfortunately, either of those aren't options with this project.

My solution:

Does not use the configuration manager, is custom and uses dependency injection.

  1. I created a folder (not tracked in git) residing at the top level of the application containing .json files that hold the project secrets.
  2. I created a SecretsManagerService class and an Encryption class.
    1. The Encryption class
      1. Encrypts a given byte array and returns the encrypted byte array
      2. Decrypts a given byte array and returns a string
    2. The SecretsManagerService class
      1. Encrypts a specified .json file at rest (encrypts contents then overwrites file)
      2. Reads, decrypts then deserializes a specified .json file into memory
      3. Updates a specified .json file (encrypts updated contents then overwrites file)
  3. SecretsManagerService is injected into other services when secrets are needed

Is this solution just a worse .appsettings.json implementation? (Folder residing at top level, still need to manage across dev, staging and production)

Would you have a different approach, other than Azure/AWS?

Really wanting to learn best practice and hear others thoughts!

7 Comments
2024/12/19
03:31 UTC

0

Autocomplete help in winforms

Edit: I noticed that in the property window I am unable to change the value for the AutoCompleteSource. On youtube videos online this was possible, and they had many options to choose from.

Hello everybody,

I am creating a recipe management app in winforms, and want to implement the built-in autocomplete feature. I am making an API call from Spoonacular (the API company), which checks a string ingredient, and returns potential ingredients. For instance: if the letter is "a", it could suggest apple, almond, etc...

The API calls are successful, however the autocomplete bar from the built-in autocomplete feature, doesn't stay on. It stays for an eye blink, and then diminishes. I have this autocomplete set up for a textbox, and I suspect the issue with the results diminishing is due to the fact that I have it set up under the TextChanged event. Relevant code is below:

private void MealPlanSelectionForm_Load(object sender, EventArgs e)

{

SetUpAutoComplete(breakfastBox);

}

private async Task<List<string>> AutoCompleteRecipe(string ingredient)

{

string apiKey = "myKey(this is a value in my code, but for safety I've left it out)";

string url = $"https://api.spoonacular.com/food/ingredients/autocomplete?apiKey={apiKey}&query={ingredient}&metaInformation=false&number=5";

try

{

using (HttpClient client = new HttpClient())

{

HttpResponseMessage response = await client.GetAsync(url);

if (response.IsSuccessStatusCode)

{

string jsonResponse = await response.Content.ReadAsStringAsync();

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Recipe>>(jsonResponse);

List<string> recipeNames = new List<string>();

foreach (var recipe in result)

{

recipeNames.Add(recipe.Name);

}

return recipeNames;

}

}

}

catch (Exception ex)

{

Debug.WriteLine(ex.Message);

}

return new List<string>();

}

private void breakfastBox_TextChanged(object sender, EventArgs e)

{

AutoCompleteHelper(breakfastBox);

}

private async void AutoCompleteHelper(TextBox box)

{

AutoCompleteStringCollection recipesCollection = new AutoCompleteStringCollection();

var recipes = await AutoCompleteRecipe(box.Text);

recipesCollection.AddRange(recipes.ToArray());

box.AutoCompleteCustomSource = recipesCollection;

box.AutoCompleteMode = AutoCompleteMode.Suggest;

box.AutoCompleteSource = AutoCompleteSource.CustomSource;

}

private void SetUpAutoComplete(TextBox box)

{

box.AutoCompleteMode = AutoCompleteMode.Suggest;

box.AutoCompleteSource = AutoCompleteSource.CustomSource;

}

Thank you for your help, hope my issue makes sense.

1 Comment
2024/12/19
03:09 UTC

Back To Top