r/csharp • • 7h ago

DocuTrust.NET: validate uploads by magic bytes (security update, looking for testers)

0 Upvotes

DocuTrust.NET is a small .NET 8 library that checks an upload's magic bytes against the type you expect. A PNG renamed to report.pdf fails.

I just did a security pass on it. It now checks the client file name too, rejects ZIP/OLE files over 100 MB before parsing, and keeps file names and paths out of error messages. I also updated a dependency that was pulling in a vulnerable OpenMcdf.

For now it only identifies file types. It doesn't scan for macros or scripts

 dotnet add package DocuTrust.NET

https://github.com/saa-999/DocuTrust.NET

If you try it, I'd like to know what breaks.


r/csharp • • 2h ago

Help C# On Linux

6 Upvotes

Hi guys i need some help. so i just started my third year in cs and completely switched to linux and yesterday i started my class on Programming with paradigms and my professor is using visual studio to create Winforms .net projects or something like this i am quite new to C# world and .net especially and i don't know what to do where to write the code cause he does all those sorts of visual gui handling adding buttoms and stuff and i just downloaded rider but it does not have those gui stuff and also is quite weird to move around file structure even if we forget that code based window creation so if there is any alternative or something that will help please let me know if not it does not concern me to use rider and get used to it but if there is something that i can follow my professor better please let me know

Thanks in advance

Wannabe Systems Administrator


r/csharp • • 6h ago

JetPack WPF Theme (kind of like MahApps Metro)

0 Upvotes

I'm working on a packaged version of the good old 2010 Silverlight theme "JetPack".

I had Claude have a good look at how MahApps Metro is structured and had it construct a JetPack theme bundle along with documentation for it.

A lot of useful usercontrols that lacked in the Silverlight theme has been added, along with Mica effect, DataGrid (similar to Telerik RadGrid), SearchCombobox (similar to RadComboBox) and more.

Anyways - feedback is appreciated :)

Repo : https://github.com/Montago/JetPackTheme

Documentation : https://montago.github.io/JetPackTheme/

Nuget : https://www.nuget.org/packages/JetPack.Wpf/


r/csharp • • 23h ago

I built Magpie, a self-hosted media discovery and automation app in C#

Post image
0 Upvotes

r/csharp • • 5h ago

Help How do you artificially trigger all the execution paths in a code ?

0 Upvotes

By installing Microsoft.AspNetCore.Identity and System.ComponentModel.DataAnnotations, I believe you are able to compile the following —nearly— self-contained code:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
namespace PlayGround
{

    public class SignupViewModel
    {



        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Name")]
        public string? Name { get; set; }

        [Required]
        [RegularExpression("^
\\+
?(\\d{1,3})?[-.\\s]?(
\\(
?\\d{3}
\\)
?[-.\\s]?)?(\\d[-.\\s]?){6,9}\\d$|(^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+
\\.
[A-Za-z]{2,}$)", ErrorMessage = "Please enter a valid email address or phone number")]
        [Display(Name = "Email or phone number")]
        public string? EmailOrPhoneNumber { get; set; }


        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string? Password { get; set; }


        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string? ConfirmPassword { get; set; }



    }
    public record RegistrationResult(bool IsSucceeded, List<string> Errors);

    public class ApplicationUser : IdentityUser
    {

    }
    public interface IAccount
    {
        public Task<RegistrationResult> RegisterUser(SignupViewModel SignupInput);
    }
    public class UserAccount : IAccount
    {
        private readonly IUserStore<ApplicationUser> _userStore;
        private readonly UserManager<ApplicationUser> _userManager;
        public UserAccount(IUserStore<ApplicationUser> userStore,
            UserManager<ApplicationUser> userManager)

        {
            _userManager = userManager;
            _userStore = userStore;
        }


        // HOW TO TEST THE `RegisterUser` METHOD ALONE WITHOUT RUNNING THE WHOLE  APPLICATION ?
        // I WANT TO TRIGGER ALL THE PATHES OF THE `RegisterUser` METHOD TO VERIFY THAT EACH PATH IS TRIGGERED WHEN IT IS NEEDED.
        public async Task<RegistrationResult> RegisterUser(SignupViewModel SignupInput)
        {
            // PATH 1
            var validationContext = new ValidationContext(SignupInput);
            var results = new List<ValidationResult>();
            bool valid = Validator.TryValidateObject(SignupInput, validationContext, results, validateAllProperties: true);
            if (!valid)
            {
                // PATH 2
                return new RegistrationResult(false, ["The sent data is not valid"]);
            }


            ApplicationUser user = new ApplicationUser();
            await _userStore.SetUserNameAsync(user, SignupInput.Name, CancellationToken.None);

            if (!(_userManager.SupportsUserEmail))
            {
                //PATH 3
                throw new NotSupportedException("user manager does not support user email");
            }

            var _emailStore = (IUserEmailStore<ApplicationUser>)_userStore;
            await _emailStore.SetEmailAsync(user, SignupInput.EmailOrPhoneNumber, CancellationToken.None);
            var result = await _userManager.CreateAsync(user, SignupInput.Password);
            List<IdentityError> identityErrors = result.Errors.ToList();

            if (identityErrors.Count != 0)
            {
                //PATH 4
                List<string> errorsStrings = new List<string>();

                foreach (IdentityError identityError in identityErrors)
                {
                    errorsStrings.Add(identityError.Description);
                }

                return new RegistrationResult(false, errorsStrings);



            }

            await _userManager.AddToRoleAsync(user, "Normal-User");
            return new RegistrationResult(true, []);

        }

    }

}

This code is a part of bigger application for sure, to test that method, I run the whole application:

 dotnet watch run --launch-profile https

I'm forced to do that because the input to the RegisterUser is provided by the browser, but I will not be able to trigger all the paths inside the method if I passed the data to the method using it.

Is there a way to test this method without running the whole application so that I can provide whatever data I want to the method by bypassing the client-side and the server-side validation in order to artificially trigger all the possible paths of execution ?

An applied example would be appreciated.

EDIT :

I come across the term Unit testing a lot, I'm not sure if this is what I need.


r/csharp • • 5h ago

Is it normal to not remember Syntax

Thumbnail
0 Upvotes

r/csharp • • 8h ago

CsCheck 5.0 - .NET 11 and native AOT ready

Thumbnail
5 Upvotes

r/csharp • • 20h ago

Help Confused about how default method arguments work underneath the hood in C# (CS1736)

26 Upvotes

So I recently came across CS1736 while writing some code. For example, the following method code results in a compile-time error:

public static void ErrorMethod(int[] a = new int[0]{}) {}

I’d never come across this error before strangely enough. When I read the MSFT docs about what causes it, I see the following explanation:

A default parameter value is evaluated upon the invocation of the method. What a value may be when the method is eventually invoked cannot be pre-determined at declaration-time unless that value is constant at compile-time.

What’s confusing me is why the compiler needs the arguments to be compile-time constants to be able to initialize them with default values, especially since they are only evaluated when the method is called during runtime. Wouldn’t the compiler in this case already know what I’m initializing the array as? Wouldn’t this make more sense as a runtime error if you initialize with some problematic value?

Also I’d like to confirm, when they say “compile-time constant” in the docs, is that just a different way to refer to regular “Constants”? Or is this referring to something else?

Thanks!