/r/learncsharp

Photograph via snooOG

Learn C# is about learning C#! Post your questions regardless of your experience level.

Welcome to /r/LearnCSharp!

Please read the rules and guidelines below and search before posting.

Rule 1: Posts must be about learning C#.

Rule 2: No posts advertising blogs, videos, or tutorials. If you'd like to make such a post here, ask the moderators.

Rule 3: No posts that are recruiting or hiring, but looking for buddies or mentors is fine.

Rule 4: Be polite, constructive, and serious -- make sure your answer isn't a joke or mocking the questioner.

If you make a post here, you must engage with the people who answer you. Tell them it worked, tell them it didn't, ask for clarification. Do not delete your post after you get an answer! Leave it up so others might find it an learn, or continue the conversation.

To get the best help, make sure you ask a complete question. "I'm stuck" isn't actionable. Posting your assignment or naming a goal isn't good enough, either. No screenshots -- format your code using four spaces on every line so that Reddit will format the whole block as code.

The site-wide rules always apply!

/r/learncsharp

19,332 Subscribers

3

Connect Oracle Database with ASP.NET(C#) MVC

Hi, I am newbie in c# and i have been assigned with a task to create website where user can upload excel file, and be able to update the data into Oracle Database. My question is how can I link Oracle Database with ASP.NET(C#) MVC. (sorry for my english). Been looking at tutorial, but i am confused where to start.

0 Comments
2024/12/18
02:18 UTC

1

Beginner project

Small projects I started over the weekend. What are your thoughts? Check it out here: https://github.com/sarf01k/TypingSpeedTester

1 Comment
2024/12/18
00:21 UTC

1

project/solution setup for multiple projects

x:y

I need to add/update products in NopCommerce as well as subscribe to events (ie orders being placed)

I am developing a NopCommerce plugin. Nopcommerce consumes the DLL of my plugin.

I am trying to develop the plugin, as much as possible, in a separate solution. This will hopefully keep the git repo easier to manage, as well as faster compile and start times etc.

The plugin is a Class Library.

I created a console app to call the class library, my plugin, to test certain aspects of the plugin. I have validated that my independent functions work (calling an existing API) and now I need to test actually interacting with the Nop webserver...

So what is the best way to do this? Deploy the NopCommerce build to a local server (or even just let it run in VS maybe), import the DLL of my plugin through the admin console, and attach a remote debugger?

0 Comments
2024/12/16
23:23 UTC

7

Question about the Microsoft "Learn C#" collection.

The learning path/collection I'm talking about is this one: https://learn.microsoft.com/en-us/collections/yz26f8y64n7k07

1.) Is this recommended or are there better free material available?

2.) I've come mid-way through this collection and it seems like it's one day written by someone who cares about teaching and other days it's by someone looking to punch 9-to-5.

I'll give an example, in some sections they go all out and explain everything from what you're doing and why you're doing. Then they go into a "DO THIS, ADD THIS" mode suddenly - this gets worse when they have those boring "Grade students" examples.

So it goes even bipolar and rushes the introduction of concepts, take for example this part. https://learn.microsoft.com/en-us/training/modules/csharp-do-while/5-exercise-challenge-differentiate-while-do-statements

The whole ReadLine() gets introduced suddenly out of no where and then they make the overwhelm the student mistake.

Any recommendations?

9 Comments
2024/12/15
18:11 UTC

3

Semaphore in API

I am writing a minimal API with a simple async POST method that writes to a new line on a file. I have tested the method using Postman so I know the API call works but I am looking to make the shared file resource safe and Microsoft Learn recommends using a binary semaphore with async/await. My question is can I use a semaphore within the Program.cs file of the minimal API? Will this have the desired result that I am looking for where if there are multiple threads using the post request will there only be one lock for file?

I’m not sure if this makes sense but I can try to post the actual code. I’m on my phone so it’ll be a little difficult.

5 Comments
2024/12/11
17:46 UTC

8

Is there a cleaner way to write this code?

A page has an optional open date and an optional close date. My solution feels dirty with all the if statements but I can't think of a better way. Full code here: https://dotnetfiddle.net/7nJBkK

public class Page
{
    public DateTime? Open { get; set; }
    public DateTime? Close { get; set; }
    public PageStatus Status
    {
        get
        {
            DateTime now = DateTime.Now;
            if (Close <= Open)
            {
                throw new Exception("Close must be after Open");
            }
            if (Open.HasValue)
            {
                if (now < Open.Value)
                {
                    return PageStatus.Scheduled;
                }

                if (!Close.HasValue || now < Close.Value)
                {
                    return PageStatus.Open;
                }

                return PageStatus.Closed;
            }
            if (!Close.HasValue || now < Close.Value)
            {
                return PageStatus.Open;
            }
            return PageStatus.Closed;
        }
    }
}
9 Comments
2024/12/11
12:24 UTC

7

Is jumping straight into Blazor a bad idea? Want to remake a MERN project using C#/Blazor.

Hey everyone. Recently began focusing on learning a new language and have had a really interesting time learning C#. I completed the Foundational C# course on Microsoft Learn yesterday and have really come to appreciate the language.

I have been considering remaking a project I made with JS/React. It was a clone of OP.GG, which is a website that collects and displays League of Legends player information. It also had sign up/sign in functionality and let users save multiple summoner names to their account. The project communicated heavily with the Riot Games API, with multiple endpoints, controllers, and methods used to collect and organize the data before displaying it to the user.

I want to remake this project using C#/Blazor primarily because, to be honest, I kinda hated JS. I really prefer strongly typed languages built around OOP and C# basically has almost everything I liked about Java (and to a lesser extent C++) without all the bloated verbose code, plus a few extra features that I really like.

Is it a bad idea to jump straight into Blazor and try to build the project? I have gone over some tutorials on Blazor, and it's a lot to absorb initially, especially regarding dependency injection and how context classes work. Tutorial hell is a menace and I find myself learning much better by just trying to build something. I also need to spend time to learn the basics of developing an API to communicate with the Riot Games API, along with learning how to utilize Entity Framework to store data. Lastly, I want to take this project a bit further and learn some unit testing in C# and also learn how to deploy it using Azure.

Any tips for good resources before diving in? Thanks for reading!

4 Comments
2024/12/11
03:14 UTC

2

How to update the selected node of a WinForms treeview to be always visible while scrolling with the mouse wheel?

If you scroll with the arrow keys, the selected node is always updated and visible. But if you're scrolling with the mouse wheel the selected node goes out of view. How to make the selected node to "travel" with the mouse wheel movement? (preferably the selected node should be the first from the visible treeview section).

The treeview is fully expanded all the time. I tried:

    private void TreeViewOnMouseWheel(object sender, MouseEventArgs e)
    {
        if (treeView.SelectedNode != null)
        {
            treeView.SelectedNode = treeView.TopNode;
            treeView.SelectedNode.EnsureVisible();
        }
    }

without success.

3 Comments
2024/12/05
18:36 UTC

2

Please help me about switch expressions!

I give up, I 've been looking everywhere on answers on it on stackflow and google so I'm giving up and asking for help!

class Program
{
static void Main()
{
Console.WriteLine("Let us Play");
Heroes.Heroe_Heroe();
string myLovelyClass = Heroes.Hero_Hero();  //not working cannot convert int to string! :(

class Heroes
{
public static void Heroe_Heroe()
{
Console.WriteLine("Choose your Heroes");
string class_ofHeroes[] = {"Thief", "ChosenPriest"};
Console.WriteLine($"1 => {class_ofHeroes[0]}");
Console.WriteLine($"2 =>{class_ofHeroes[1]}");
int myClass = Convert.ToInt32(Console.ReadLine());
string my_ClassBaby = myClass switch
{
1 => "Thief",                 
2 => "ChosenPriest"          //Also Endlessly Looping!
}
return my_ClassBaby;
}

I don't really like to abuse if & else looks like a nightmare if use too much!

I want to maximize the switch expression.

7 Comments
2024/12/05
17:08 UTC

1

WPF ShowDialog() returning before close

I have a WPF window that opens to choose a COM port when a port has not been previously selected. Once a port has been selected the window sets the com number and closes. The WPF window has been proven to work by itself and added it to my program.

It is called by a separate class with:

 Task commy = Commmy.Selected();
 Task.Run(async() =>  await Commmy.Selected());
 WinForms.MessageBox.Show("done waiting");

I have a message box at the end of the task Selected() and after the await as a "debug". These will not exist in the final code.

From what I understand Show() is a normal window and ShowDialog() is modal window.

I am using a ShowDialog() to prevent the method from finishing before I close the window(only possible once a COM port has been selected) however the message box at the end of the method opens up the same time as the window opens. The await is working because the "done waiting" message box will not open until I close the "at end of selected" message box. This tells me that the ShowDialog is not working as I intended (to be blocking) and I don't know why.

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace ComSelectionClass
    internal class Commmy
    {
        static MainWindow mainWin;

        public static Task Selected()
        {
            Thread thread = new Thread(() =>
            {
             MainWindow mainWin = new MainWindow();

                mainWin.ShowDialog();
                mainWin.Focus();
                mainWin.Closed += (sender, e) => mainWin.Dispatcher.InvokeShutdown();

                System.Windows.Threading.Dispatcher.Run();
            });
         
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            System.Windows.Forms.MessageBox.Show("at end of selected");
            return Task.CompletedTask;
        }
    }

Any help to block my code until the window is closed would be appreciated.

12 Comments
2024/12/04
05:58 UTC

4

I need help to generate a custom TreeView structure [WinForms]

Hi. Given a string lists of paths (every path always contain at least one folder), I must generate a TreeView structure where the root nodes are the paths, except the last folder which is displayed as a child node if it's not a root folder. Basically display as much as possible from the path where it doesn't have subfolders.

I need this for a specific file manager kind of app I'm developing.

For instance, from these paths:

c:\Music
d:\Documents
e:\Test\Data\Test 1
e:\Test\Data\Test 2
e:\Test\Data\Test 3
e:\ABC\DEF\XYZ\a1
e:\ABC\DEF\XYZ\a1\c2
e:\ABC\DEF\XYZ\a2
e:\ABC\DEF\XYZ\b1

it should generate something like...

 _c:\Music
|
|_d:\Documents
|
|_e:\Test\Data
|	|_Test 1
|	|_Test 2
|	|_Test 3
|
|_e:\ABC\DEF\XYZ
	|_a1
	|  |_c2
	|_a2
	|_b1

EDIT: I found a solution for a simplified case:

 _c:\Music
|
|_d:\Documents
|
|_e:\Test\Data
|	|_Test 1
|	|_Test 2
|	|_Test 3
|
|_e:\ABC\DEF\XYZ
|	|_a1
|	|_a2
|	|_b1
|
|_e:\ABC\DEF\XYZ\a1
    |_c2

https://www.reddit.com/r/learncsharp/comments/1h5cdgk/comment/m0kr79e/?utm_source=reddit&utm_medium=web2x&context=3

7 Comments
2024/12/03
01:59 UTC

12

When is the right time to give up?

Still a newbie and would like to ask when do you guys decide to ask help? or look at google?

I'm trying to build like a clock at the moment and trying to build it without looking in google or looking at other people's work.

Currently. I'm losing and my brain hurts xD

EDIT: Thanks to all of the people who answered here. I never thought that usingngoogle is just fine, I thought I was cheating or something, hahah.

14 Comments
2024/12/01
14:27 UTC

1

How to implement state machine pattern?

Context: User fills in a form on my webpage. User then saves the form, based on the filled in data the form can get the following states:

States:

 public enum State
    {
        [Description("NewForm")] // Initial state
        Draft = 0,
        [Description("Denied")]
        Afgekeurd = 1,
        [Description("Approved")]
        Afgerond = 2, 
        [Description("WaitForApprovalManager")]
        WaitForApprovalManager = 3,
        [Description("WaitForApprovalTech")]
        WaitForApprovalTech = 4,
        [Description("WaitForApprovalFinance")]
        WaitForApprovalFinance = 5,
    }

How I implemented the State Machine Pattern:
FormStateService.cs:

public class FormStateService
    {
        private FormState _currentState; // Current state of the form
        private Form _form; // Form that the user filled in
 
        public FormStateService(Form form)
        {
            _form = form;
            if (_currentState == null)
            {
                SetState(new DraftState()); // Set initial state to draft
            }
        }
 
        public void SetState(FormState state)
        {
            _currentState = state;
            _currentState.SetContext(_form);
        }
 
        public Form HandleStateTransition()
        {
            _currentState.HandleStateTransition(this);
            return _form;
        }
 
        public Status GetCurrentState()
        {
            return (State)_form.State;
        }
    }

FormState.cs:

    public abstract class FormState
    {
        protected Form _form;
 
        public void SetContext(Form form)
        {
            _form = form;
        }
 
        public abstract void HandleStateTransition(FormStateService stateMachine);
    }

WaitForApprovalManagerState.cs

        public override void HandleStateTransition(FormStateService stateMachine)
        {
 
            if (_form.TotalReceipt >= 500) // Wait for managed to approve
            {
                _form.State = (int)Status.WaitForApprovalManagerState;
                stateMachine.SetState(new WaitForApprovalManagerState());
                return;
            }
 
            if (_form.TotalReceipt >= 500 && _form.ManagerApproved && _form.TechForm == true) // If manager has approved let tech approve
            {
                _form.State = (int)Status.WaitForApprovalTechState;
                stateMachine.SetState(new WaitForApprovalTechState());
                return;
            }
 
        }
2 Comments
2024/11/30
16:44 UTC

3

Generic classes, events, and subscriptions

I have a Generic class: MyClass<T> where T is IGameElement.

I also have a class named Player.

I am getting into events and I am having a hell of a time here.

there is a third class that is running my program, it is sort of the programs Main. For this troubleshooting, lets call it Main.

There is an instance of MyClass in Main, and there is a Player class in Main.

I need the Player class proper, to be able to subscribe to the MyClass event, handle the event, then unsubscribe to that same event. I have tried everything and I am bashing my head against the wall. Reflection, Dynamic, etc... The problem I am having is that I need the Player class to not care about MyClass's type. Unless I am getting something wrong here, that is what I cannot seem to do.

Anyone want to walk me through what I need to do to get this behavior?

2 Comments
2024/11/28
05:29 UTC

1

Process.Start() Works debugging but not in production :(

Hey everyone! I am learning to start processes(.exe's) using C# and so far the debugging experience has been great! I am trying to create a Windows Service that is constantly running in the background checking if 3 processes are running! If for some reason these processes stop, I try to launch them again!

I have had some issues tho- for some reason when I start the executable, the GUI of the program won't show up! The process is created! I can see it running in task manager, but for some reason the program does not start the same way as if I have clicked on it!

After doing some research around, I saw that you have to specify the working directory of your process! Something like this:

using(Process p = new Process())
{
p.StartInfo = new ProcessStartInfo(myObject.ProcessPath);
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(myObject.ProcessPath);
p.Start();
}
_logger.LogWarning($"Starting {device.ProcessPath} at {Path.GetDirectoryName(device.ProcessPath)}");

This did the trick for me in debugging mode! It starts off the process nicely- The GUI shows up and everything works as it is supposed to. But when I try to publish my service, the processes go back to not starting the same way anymore! Do you guys think it might be Visual Studio messing up the program? The publishing options look something like:

Configuration --> Release|Any CPU
Target Framework --> Net 8.0
Deployment Mode --> Self Contained
Target Runtime --> win-x64 (I changed this! it used to be x86... is there a con to using x86?)
Produce Single File --> Yes
Enable ReadyToRunCompilation --> Yes

I am sorry for adding bold letters to the top ;w; I really hope someone can help me- I am completely lost and I feel like big wall of plain text will turn people away :(

3 Comments
2024/11/27
19:10 UTC

1

Why is a ListView's SelectedItems readonly (and thus unbindable)?

It's weird because singular SelectedItem isn't readonly.

0 Comments
2024/11/26
22:25 UTC

3

What's your way of Memory Management?

I'm been learning memory management since yesterday and from what I understood it's best if you where to use arrays or tuples something that you can give them value as a group.

Im just curious whether you guys have your own way of managing it? Like in your own style?

Im just a newbie so forgive me if I wrote something wrong here. Thanks!

13 Comments
2024/11/26
10:24 UTC

2

Architecture question building a list of user editable rule items to be loaded into an engine.

Hi,

I'm looking for some architectural advice. I'm working on a small side project solo. I'm not a professional programmer.

I made a simple front end to a linear optimizer engine to build up a model with various constraints, run the optimizer, then print out the data. I'm transitioning the front end from hard coded in console to a WPF app. I want to have several various types of rules that can be selected by the user with custom input, then, when the user input is all collected, the user clicks a button to run the optimizer.

I made a ListBox to display the various user added rules, and a Frame to display the input page for the rule. Each rule type needs a different page displayed in the frame to collect the input for that particular rule type.

I'm thinking each rule should be an object, and there should be a collection, like a list that contains all the rules. Each rule object should implement an interface with a method that loads the rule into the optimizer model, so that when the optimizer is run, I can just iterate the list and call that function for each rule. Each rule should also implement a function to return it's user input page to load it into the frame when selected from the ListBox list.

I think this should work, but I'm wondering if I'm missing an idiomatic way to do this.

2 Comments
2024/11/26
05:30 UTC

6

Do you use Enums?

I'm just curious cause you got arrays or tuples. In what situation do you use enumerations?

Edit: Sorry guys I didn't elaborate on it

17 Comments
2024/11/23
13:00 UTC

2

ASP.NET and Django. What's the difference?

I'd like to say that I'm not looking for an answer about which one is better, but that's a lie. However, this is subjective for everyone.

If there are anyone here who has experience with both ASP.NET and Django, please share your impressions.

P.S. I searched, but if anyone made a comparison, it was years ago!

4 Comments
2024/11/19
21:49 UTC

0

[WinForms app] How to stop the flickering of a small borderless form displayed on top of main form (like a toast message for a few seconds)?

Both main form and the small form have black backgrounds. Main form includes a videoview and the small form includes a borderless textbox with black background. When the small form is displayed over the main form, sometimes there is a white flicker visible for a few milliseconds, like the system is trying to paint them in white and then it quickly changes the colors to black. How to stop this GDI+ annoyance?

I tried setting either one or both forms to DoubleBuffered and still the same result.

6 Comments
2024/11/19
18:39 UTC

6

How to use foreach?

int[] scores = new int[3] { 1, 2 , 5 };    //How to display or make it count the 3 variables?
foreach (int score in scores)
Console.WriteLine(scores);    // I want it to display 1,2,5

23 Comments
2024/11/17
13:11 UTC

7

Book/Guides/Tutorials that teach OOP with C#?

I already kinda know coding and C#. But when it comes to "how to structure a classes", "private/public/protected etc." and etc. , i just lost, i have no idea what to do.

TLDR: I know coding, but not programming.

4 Comments
2024/11/15
08:06 UTC

17

What's the best way to learn c# as a self learner ?

20 Comments
2024/11/13
23:11 UTC

1

Help me understand Clean Architecture (ASP.NET Core)

Hey,

I've been learning ASP.NET Core for the last couple weeks (coming from Express.js / JS), and at first I started doing my projects with the "N-Tier" architecture, which made a lot of sense right away.

Now, I'm trying to learn different architectural styles, starting with "Clean architecture".

I was trying to "convert" my existing project (made with n-tier architecture) to use clean architecture... but it feels really un-intuitive and needlessly complex to write with clean architecture.

I'd like your opinion on the structure of my project for both n-tier and clean architectures, and any tips on learning clean architecture.

N-Tier Structure:

AppName.API/
  Controllers/
AppName.Business/
  DTOs/
  Filters/
  Services/
  Validators/
AppName.Data/
  Contexts/
  Migrations/
  Models/
  Repositories/
    Implementations/
    Interfaces/

N-Tier Dependencies:

  • "API" references "Business"
  • "Business" references "Data"

Clean Structure:

API/
  AppName.API/
    Controllers/
    Filters/
Core/
  AppName.Application/
    Contracts/
      Persistence/ (this has the interfaces for the repository classes)
    Features/
      DTOs/
      Services/
      Validators/
  AppName.Domain/
    Entities/
Infrastructure/
  AppName.Persistence/
    Contexts/
    Repositories/ (this has the implementations for the repository classes)

Clean Dependencies:

  • "Application" references "Domain"
  • "Persistence" references "Application"
  • "API" references "Application" & "Persistence"
2 Comments
2024/11/13
08:25 UTC

1

Pop up problem

Hi , I am new to c# and I have a problem with running the code , everytime I click the green button that looks like this ▶️ a pop up appears with the title "attach to process" and a bunch of things ending in .exe , for example "AsusOSD.exe" , and the code doesn't run , what do I do?

0 Comments
2024/11/07
10:01 UTC

1

Electron to webview2 which UI

Hello

I'm thinking of replacing a small electron app of mine, and Webview2 seems to be the best alternative.

What would be the best UI to run a webview2 app, Winforms, WPF, ..?

Thanks

3 Comments
2024/11/02
18:55 UTC

3

how do you simulate incomplete tcp data in unit tests

I'm trying to learn about buffers, and TCP handlers in Kestrel.

The way i'm doing this is by implementing a very basic message broker based on the STOMP protocol.

So far i've been parsing frames correctly, when unit testing, but when actually receiving TCP traffic, i should be able to handle incomplete data, and i'm not sure how i can simulate this behaviour in unit tests. Does anyone have examples of unit tests for Microsoft.AspNetCore.Connections.ConnectionHandler ?

This is what i have so far:

public class StompConnectionHandler(ILogger<StompConnectionHandler> logger, IStompFrameParser frameParser)
    : ConnectionHandler
{
    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        logger.LogDebug("Connection {ConnectionId} connected", connection.ConnectionId);
        var input = connection.Transport.Input;
        while (true)
        {
            var result = await input.ReadAsync();
            var buffer = result.Buffer;
            if (frameParser.TryParseFrame(ref buffer, out var frame))
            {
                // TODO: process frame
                logger.LogDebug("received frame {@Frame}", frame);
            }

            input.AdvanceTo(buffer.Start, buffer.End);
            if (result.IsCompleted)
            {
                break;
            }
        }

        logger.LogDebug("Connection {ConnectionId} disconnected", connection.ConnectionId);
    }
}
public class StompFrameParser(ILogger<StompFrameParser> logger) : IStompFrameParser
{
    private ref struct Reader(scoped ref ReadOnlySequence<byte> buffer)
    {
        private readonly ReadOnlySpan<byte> _frameTerminator = new([(byte)'\0']);
        private readonly ReadOnlySpan<byte> _lineTerminator = new([(byte)'\n']);
        private readonly ReadOnlySpan<byte> _carriageReturn = new([(byte)'\r']);

        private SequenceReader<byte> _sequenceReader = new(buffer);

        public bool TryReadToNullTermination(out ReadOnlySequence<byte> sequence)
        {
            return _sequenceReader.TryReadTo(out sequence, _frameTerminator);
        }

        public bool TryReadToLf(out ReadOnlySequence<byte> line)
        {
            return _sequenceReader.TryReadTo(out line, _lineTerminator);
        }
    }


    public bool TryParseFrame(ref ReadOnlySequence<byte> buffer, out StompFrame? frame)
    {
        var reader = new Reader(ref buffer);

        if (!reader.TryReadToLf(out var command))
        {
            frame = default;
            return false;
        }

        var commandText = Encoding.UTF8.GetString(command).TrimCrLf();
        Dictionary<string, string> headers = new();

        while (reader.TryReadToLf(out var headerLine) && Encoding.UTF8.GetString(headerLine).TrimCrLf().Length != 0)
        {
            var header = Encoding.UTF8.GetString(headerLine).TrimCrLf();
            var headerParts = header.Split(':');
            if (headerParts.Length != 2)
            {
                logger.LogError("Invalid header: {Header}", header);
                frame = default;
                return false;
            }

            var key = headerParts[0];
            var value = headerParts[1];
            headers.TryAdd(key, value);
        }

        if (!reader.TryReadToNullTermination(out var body))
        {
            frame = default;
            return false;
        }

        var bodyText = Encoding.UTF8.GetString(body).TrimCrLf();

        frame = new StompFrame(commandText, headers, bodyText);
        return true;
    }
}
public class StompFrameParserTests
{
    private static ReadOnlySequence<byte> CreateReadOnlySequenceFromString(string input)
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(input);
        return new ReadOnlySequence<byte>(byteArray);
    }

    [Fact]
    public void ParsingCorrectFrame_ShouldReturnFrame()
    {
        var logger = Substitute.For<ILogger<StompFrameParser>>();
        var parser = new StompFrameParser(logger);

        var sb = new StringBuilder();
        sb.AppendLine("MESSAGE");
        sb.AppendLine("content-type:application/text");
        sb.AppendLine();
        sb.AppendLine("Hello World");
        sb.Append('\0');

        var buffer = CreateReadOnlySequenceFromString(sb.ToString());

        Assert.True(parser.TryParseFrame(ref buffer, out var result));
        Assert.NotNull(result);
        Assert.Single(result.Headers);
        Assert.Equal("application/text", result.Headers["content-type"]);
        Assert.Equal("Hello World", result.Body);
        Assert.Equal(StompCommand.Message, result.Command);
    }
}
1 Comment
2024/10/30
16:13 UTC

2

MVVM tips or experience with big apps

I would like to learn WPF or Avalonia with the famous MVVM pattern and I have finally understood how it works with the INotifyPropertyChanged however all the starting examples are very basic.

So I have also seen that there is the Community MVVM Toolkit which saves a lot of work and I have tried it and it is fascinating. I have also seen that many Avalonia examples use ReactiveUI which looking at it from above is a bit more complicated.

Now the question of the matter is, large and complex applications with many classes, models, options, sub-options and user configurable parameters are really handled with MVVM, I ask this because just to create a simple booking application with Singleton Sean (Youtuber) has created me many files and high complexity.

I usually develop with Blazor and API and it is not that complex. I still don't consider myself a very experienced developer but I would like to learn about MVVM to expand my knowledge.

I would like to hear testimonials or opinions from people who have worked on large desktop applications with this pattern or who can give me recommendations for reading or videos.

PS: Singleton Sean's channel has a lot of valuable content.

5 Comments
2024/10/30
10:23 UTC

0

I want to vent :(

I want to vent and say it is miserable to learn c# in the start.

It feels like learning a new game. I dont know anything. It feels frustrating to know new stuff. I feel down if things have errors and if things dont work.

I was doing while loop ( FirstAnsw < 1 || FirstAnsw > 2 ). It's not working and it it is not recognizing the method I put underneath it. I keep thinking about it for a week now.

Honestly, It's just a struggle. But it is fun but man it just brings you down if nothing works and it just becomes a mess.

Yeah I have no Com sci degree or training. I just want to build some fun games or apps for trolling like your mouse dissapearing or freezing while you use it hahaha

21 Comments
2024/10/30
09:14 UTC

Back To Top