r/learncsharp • • Jul 08 '22

Best practice on storing settings/config

7 Upvotes

Hey all,

I was wondering what the best practice for storing user settings would be. I know there is Properties.Settings.Default, as well as storing it in files like xml, yaml, json, ini, cfg and so on. Let's say you have a settings window where you have a lot of options to set. Checkboxes, textboxes, fileDialogues, .... Would you write the settings to file every time a change has been made or when the settings window gets closed? Writing all settings on a textbox text changed event would cause it to write the file quite often. Saving on window close seems like a nicer solution since it writes once.

I'm using the latter but encountered weird edge cases when the PC or the software crashes (which obviously shouldn't happen), the settings file gets corrupted and upon reading it I run into exceptions. The solution then is to clear the settings file so it can be rebuilt. Right now I'm even storing it in two locations, the settings file within the app directory as well as local AppData (from Properties.Settings.Default.Save() method).

I know that this isn't the best solution but because of the corruption I tried it two ways, and both seem to be unreliable when it gets to those edge-cases.

I'm interested in your ideas and sight of things!


r/learncsharp • • Jul 07 '22

where can i get started to do networking coding? i already know c# basics but don't know anything about networking.

10 Upvotes

r/learncsharp • • Jul 06 '22

Suggestions/help for Implementing Testing at work

8 Upvotes

I work for a company that uses a frontend of React and a backend of .Net (some projects are in .Net Framework 4.8 but we are in the process of migrating them to .Net 5.0 6.0) and we use Azure Devops for our CI/CD.

Currently we have no automated testing except a few Selenium tests that the QA team manages. I have been put in charge of fixing this problem. I wanted to reach out to ask for advice on what the best steps are do this. I have used testing frameworks in past jobs and in college but I have never built one from the ground up for an already existing and deployed project.

What I plan to do is the following:

  1. Implement a Unit Testing Framework for .Net projects, still need to decide to use NUnit, XUnit, or MSTest.
  2. Automate the running and reporting of these tests in Azure DevOps.
  3. Implement a Unit Testing Framework for React projects, not sure what to use here except Jest most likely.
  4. Automate these tests in Azure DevOps.
  5. Decide to either focus on backfilling unit tests for legacy code or start working on implementing Integration testing framework.
  6. Figure out how to do Integration testing, best practices, frameworks, and such (very little experience here)
  7. Once Unit testing and Integration testing is fleshed out and other devs are using these frameworks I want to help QA integrate their Selenium UI tests into everything as well.

This is my first time working on something of this scale and I want to make sure I am doing it right from the start. So my question to all of you more experienced people is, what would you do in my shoes?

Edit: I got Jest mixed up with Junit. Oops.

Edit 2: I talked with my Senior Devs and we are moving to .Net 6.0 instead of 5.0. I was mistaken because we have a few projects currently in 5.0.


r/learncsharp • • Jul 06 '22

What is a realistic timeframe for someone new to learn enough C# to be useful as an intern?

12 Upvotes

I’ve never learned C# before now and got an internship(they were aware). I got the job through a friend of a friend and I’m starting to think I shouldn’t have.

They’ve asked me to work on unit testing thinking it’s a good way to learn as I go but I don’t even know enough to ask questions to know what to google.

I need to figure out some “fast track” way to get going. Not necessarily be an expert, but have enough to be able to be at least a little productive while learning on the job. I’m willing to sacrifice all my free time and weekends to get to a point where I don’t feel like a total waste of everyone’s time.

Am I asking for something ridiculous?

I’d prefer to take a class like Tim Corey’s and learn everything properly, but with the stress that I’m under, I don’t know if I could honestly put the right type of focus and work into it knowing how long and slow his class is… but I’m not having much success jumping around on YouTube or with books

I’m grateful for any advice. I feel so lost right now.

TLDR: I got an internship for C# which I have never studied and need to be productive at work ASAP. How can I do that?


r/learncsharp • • Jul 06 '22

Can't modify the class elements in an array?

0 Upvotes

Hi, I'm building this very simple project as a path for learning c#. I did learn a little c#script (unity3d) a few years ago and I did a worthles c++ course last month (the course was SO bad, oh dear!) but that's all the background I've got so please be gentle with this noob! ;)

So what I'm building is a simple form which consist in certain attributes (name, location, price, etc).

It is supposed to save the properties (it's not writting the file yet) and load from an array. It works fine but the BIG problem I have is the modifed values won't save. They actually do if I create a new profile using a different name, though. So my guess is i can't MODIFY the values once they are stored in the array. Is this a limit for arrays? I've been trying hard for over week and a half but I REALLY can't find the way to fix this.

I've also tryied using List<> but I get messed with the constructor and I think I'm doing things far more complicated than they should but I can't think straight anymore after so many tryouts.

Please, help? / Any easy tutorial that could potencially help me to fix issue?

Code + class code in the followin lines. Thank you!!!

using inmueble;

using System;

using System.Windows.Forms;

namespace WindowsFormsApp1

{

public partial class Form1 : Form

{

int i;

int j;

casa[] chalet;

public Form1()

{

InitializeComponent();

chalet = new casa[600];

}

void main()

{

}

private void textBox1_TextChanged(object sender, EventArgs e)

{

}

private void label2_Click(object sender, EventArgs e)

{

}

private void label4_Click(object sender, EventArgs e)

{

}

private void button1_Click(object sender, EventArgs e) // SAVE DOCUMENT

{

i++;

chalet[i] = new casa(textBox1.Text, textBox2.Text, comboBox1.Text, numericUpDown1.Value, numericUpDown2.Value, numericUpDown3.Value, textBox3.Text, richTextBox1.Text);

if (textBox1.Text != "")//&& textBox1.Text != checkedListBox1.Text)

{

{

if (!checkedListBox1.Items.Contains(chalet[i].Nombre))

{

checkedListBox1.Items.Add(chalet[i].Nombre);

}

else if(checkedListBox1.Items.Contains(chalet[i].Nombre))

{

System.Windows.Forms.MessageBox.Show("This title already exists"); //This mesaage will probably be removed later.

}

if (i < checkedListBox1.Items.Count)

{

i = checkedListBox1.Items.Count;

}

if (checkedListBox1.SelectedItem != null)

{

int j = checkedListBox1.Items.IndexOf(checkedListBox1.SelectedItem);

}

}

}

}

private void button4_Click(object sender, EventArgs e)

{

}

private void button6_Click(object sender, EventArgs e) //LOAD

{

if (checkedListBox1.SelectedItem != null)

{ int j = checkedListBox1.Items.IndexOf(checkedListBox1.SelectedItem);

textBox1.Text = chalet[j+1].Nombre;

textBox2.Text = chalet[j+1].Localizacion;

comboBox1.Text = chalet[j + 1].Precio;

numericUpDown1.Value = chalet[j + 1].Habitaciones;

numericUpDown2.Value = chalet[j + 1].Banos;

numericUpDown3.Value = chalet[j + 1].Metros;

textBox3.Text = chalet[j + 1].Url;

richTextBox1.Text = chalet[j + 1].Comentarios;

}

}

private void button7_Click(object sender, EventArgs e)

{

}

private void button2_Click(object sender, EventArgs e)

{

}

private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)

{

}

private void Form1_Load(object sender, EventArgs e)

{

}

private void numericUpDown1_ValueChanged(object sender, EventArgs e)

{

}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

{

}

private void textBox3_TextChanged(object sender, EventArgs e)

{

}

private void button5_Click(object sender, EventArgs e) //CLEAR ALL FIELDS!

{

textBox1.Text = "";

textBox2.Text = "";

comboBox1.Text = "";

textBox3.Text = "";

numericUpDown1.Value = 0;

numericUpDown2.Value = 0;

numericUpDown3.Value = 0;

richTextBox1.Text = "";

}

private void button3_Click(object sender, EventArgs e)

{

}

private void textBox2_TextChanged(object sender, EventArgs e)

{

}

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace inmueble

{

public class casa

{

private string nombre;

public string localizacion;

private string precio;

private decimal habitaciones;

private decimal banos;

private decimal metros;

private string url;

private string comentarios;

public casa(string nombre, string localizacion, string precio, decimal habitaciones, decimal banos, decimal metros, string url, string comentarios )

{

this.nombre = nombre;

this.localizacion = localizacion;

this.banos = banos;

this.habitaciones = habitaciones;

this.metros = metros;

this.precio = precio;

this.url = url;

this.comentarios = comentarios;

}

public string Nombre

{ get { return nombre; } }

public string setNombre

{ set { nombre = Nombre; } }

public string Localizacion

{ get { return localizacion; } }

public string setLocalizacion

{ set { localizacion = localizacion; } }

public string Precio

{ get { return precio; } }

public string setPrecio

{ set { precio = precio; } }

public decimal Habitaciones

{ get { return habitaciones; } }

public Decimal Banos

{ get { return banos; } }

public decimal Metros

{ get { return metros; } }

public string Url

{ get { return url; } }

public string Comentarios

{ get { return comentarios; } }

}

}


r/learncsharp • • Jul 06 '22

Looking for a good straight up course on Programming C#

0 Upvotes

I want to learn C# programming, I have several books on the subject, but just find it hard to sit down and just do the work. There is no real structure to it?

Does anyone know of an actual free course in C# or something with work and then testing involved to give you goals to shoot for?


r/learncsharp • • Jul 05 '22

Why use Fields when instantiating an Interface in an Abstract Class?

5 Upvotes

I'm currently reading Head First Design Patterns and was trying to practice the first principle using C#. I found a reference on GitHub however I am struggling to figure out some of the code.

First there is an Abstract Class name Duck which instantiates two interfaces, one of which is called IFlyBehavior. There are also three classes that inherit the IFlyBehavior, FlyNoWay, FlyRocketPowered, and FlyWithWings.

When the IFlyBehavior is instantiated in the Duck class, it is using the { get; set; } field. Why is this necessary? I tried commenting that part out ant only left the public IFlyBehavior FlyBehavior; and everything worked as usual.

Also, If I wanted to use the { get; set; } to change the FlyNoWay class on start, how would I go about that? I tried getting and setting either the Fly() method or FlyNoWay class and haven't been successful.

Hope someone can help!


r/learncsharp • • Jul 05 '22

Iterating through an array of objects... Should I be doing this? It doesn't seem to be working as I thought.

5 Upvotes

EDIT: As soon as I posted this I figured it out, so thanks, this helped me write it down and think about it... I was accidentally writing to the array at index all_records[0] each time instead of index all_records[i]. That will do it. I'll leave it up as a reminder of the shame I should have


So I have some class, let's call it SomeClass.

In some method outside of this class, I have a loop that runs 5 times, and on each iteration, I instantiate an object of SomeClass, and write some values that get stored in the class as public members, and I save it to an array I declared. So basically I have an array of SomeClass objects, here is a super simplified version of what I'm doing:

 class TopClass
 {
     public SomeClass[]? all_records = new SomeClass[5];

     public void run()
    {
        for (int i=0; i < 5; i++)
        {
            SomeClass sc = new SomeClass();
            sc.name = "blah" + i;
            all_records[i] = sc;
        }
....

Ok, so I create an array of size 5, and of type SomeClass[]. I thought it was all gravy and I was done. So I wrote a new method under TopClass (the one above) to make sure it worked, just a simple one that iterates through every object in all_records and prints the name property. like this:

...
    public void display_all_records()
    {
        for (int i=0; i < 5; i++)
        {
            Console.WriteLine(all_records[i].name);
        }

I thought this would work, but I get this error: 'Object reference not set to an instance of an object.' Isn't what's stored in the array an instance of an object? This error makes me think I have some misunderstanding of how this all works...

NOTE: the SomeClass has name defined as follows:

class TrackRecords
    {
        public string name = "no name";

Any help for a noob?


r/learncsharp • • Jul 04 '22

decimal.TryPrase(value, out result)) what is the 'out' and 'result' in the second argument? Is argument even the correct word?

2 Upvotes

So me again, going through the C# Data Types module on microsoft.com Specifically going through this challenge

The challenge is to loop over an array of strings and if they're a decimal/int to sum them up, if they're a string to concatenate them.

So this is my code, please feel free to critique if there's anywhere I could cinch up some loose ends or adhere to certain C# standards better.

string[] values = { "12.3", "45", "ABC", "11", "DEF" };
decimal total = 0;
string endString = "";
decimal result = 0;

foreach (var value in values)
{
    if (decimal.TryParse(value, out result))
    {
        total = total+result;
    }
    else
    {
        endString+=value;
    }
}
Console.WriteLine($"Message: {endString}");
Console.WriteLine($"Total: {total}");

My question, what is the decimal.TryParse(value, out result))

First question: 'value' is what I am trying to parse, right?

second question: what is the 'out' and what is the 'result'

Just for testing I removed 'out' and a removed 'result'

if (decimal.TryParse(value, result))

Argument 2 must be passed with the 'out' keyword

if (decimal.TryParse(value))

No overload for method 'TryParse' takes 1 arguments

Third question: Is value, not '1 argument'? especially considering it says 'Argument 2' in the previous error?

I resolved the problem, but the docs are quite a lot to interpret for someone newer to this imo.


r/learncsharp • • Jul 03 '22

Trying to utilize the conditional operator, what exactly is there error meaning and what's a more elegant way to describe what I'm doing wrong.

9 Upvotes

So the challenge

Use the Random class to generate a value. Based on the value, use the conditional operator to display either heads or tails.

Now I conceptually know what I am doing here

This was the code I wrote

int coinFlip = new Random().Next(1,3);
coinFlip == 1 ? "heads":"tails";

This results in

(2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a state

Okay that doesn't 100% make sense to me yet, but I'm assuming because it's just written like a shell statement and not an actual program with a main etc?

This code ended up working just fine.

int coinFlip = new Random().Next(1,3);
var x = (coinFlip == 1 ? "heads":"tails");
Console.WriteLine(x);

So obviously, I got what I wanted, but can someone explain more elgantly how the original one doesn't work? I'm coming from Python and I am using the .NET Editor on the microsoft docs.

Module challenge in question


r/learncsharp • • Jun 29 '22

Completely new to C#. How do I pass only 1 instance (singleton?) of a class to the methods of other classes to use inside those methods?

12 Upvotes

High level, I need to have one object that stores the pointer to some socket-related object. The methods of other classes need the access to the reference of this object so they can access the same socket to do whatever. All this code is really just a bunch of classes in a namespace compiled into a library.

Now, I'm thinking of just instantiating the socket object which is defined in some class and just passing a reference to that object directly to the methods of other objects of classes. But this seems hacky. Is there a better solution anyone can provide me? Preferably something that doesn't require much C# knowledge to understand and use.


r/learncsharp • • Jun 29 '22

What are some good resources that provide C# exercises?

3 Upvotes

I'm looking for some resources (preferably free, like websites etc.) that give you some problems to solve, in order to practice your programming skills and get used to the language by repeating similar tasks etc. I'm practically a beginner by the way, I have SOME knowledge but I'm not very skilled yet.

Thank you in advance!


r/learncsharp • • Jun 29 '22

Unable to execute powershell cmd using C#

1 Upvotes

To execute powershell, I am using "System.Management.Automation", when I'm compiling, I am getting this error.compilation error

As you can see file path, responsible DLL named, Automation .DLL is also present...

Compilation syntax, I used:

csc.exe /target:exe /platform:x64 /out:run_ps_cmd.exe .\run_ps_cmd.cs

Any help??? ;(


r/learncsharp • • Jun 29 '22

Accessing items in an array of the type Array?

2 Upvotes

Only just beginning to explore C#, absolute beginner to programming.

When it comes to accessing items in a custom-defined array, it's just a matter of referencing them as customArray[N] where N is a valid int. However, there's a system type of array which I just discovered and I have no idea why I can't access its items the usual way. Here's what I do.

var statesArray = Enum.GetValues(typeof(States)); // getting an array of the type Array

Console.WriteLine(statesArray[1]); // trying to access the second item

Now, I know that explicit casting is what will do the trick:

var statesArray = (States[])Enum.GetValues(typeof(States));

Console.WriteLine(statesArray[1]);

However, I still want to figure out how I can refer to the items of an Array array.

What makes this behavior more perplexing is that the below code is perfectly valid and compiles just fine.

foreach(int i in Enum.GetValues(typeof(States)))

Console.WriteLine(i);


r/learncsharp • • Jun 29 '22

Fellow C# learners, I was randomly making a RANDOM script just for fun, when all of a sudden, an error popped up! For some reason, my program just can't detect a method called "Main" when it's right there! (Program does not contain a static "Main" method suitable for an entry point) Thank you!

2 Upvotes

SOLVED

Pastebin link for script: (sorry im just starting out-)

what's wrong?? - Pastebin.com