Becquerel
Becquerel
CC#
Created by Becquerel on 4/24/2024 in #help
What's the basic approach for CI/CD integration tests in Azure DevOps?
I'm looking into this stuff for the first time and want general guidance on reasonable approaches. Context: - Large solution with some old janky integration tests that never get run. - We're in the middle of moving to DevOps. - The integration tests expect a SQL Server instance. I have toyed around with Testcontainers. It seems potentially great if somewhat tough to setup properly. This is what I am leaning towards at the moment. The other approach that comes to mind is provisioning a database from Azure at the start of a test run and then dropping it when we're done. This is less appealing to me because tests have to keep the playing field clean. How do you approach this? I'm not looking for a detailed guide (though feel free to give one if you're in the mood), just the high-level view on what approaches are viable and which are dead-ends.
11 replies
CC#
Created by Becquerel on 2/8/2024 in #help
ASP.NET Core authorization for just me -- a personal project
I have a background service meant solely for personal use running on a spare laptop in my closet. I want to add some endpoints so I can query its status without getting up to check on it. It's on the same wifi network as my desktop PC. What's the simplest way to open up the API so I can hit its endpoints, but also lock it down so nobody except me can get in? I found this article -- is an IP whitelist generally secure? https://learn.microsoft.com/en-us/aspnet/core/security/ip-safelist?view=aspnetcore-8.0
50 replies
CC#
Created by Becquerel on 8/10/2023 in #help
❔ How would you embed a Git commit hash in an assembly?
I want to stamp a commit hash into a binary so I can display it in the UI. I'm fine with pulling stuff from the assembly info via reflection if necessary. I've found a few libraries that promise this, but they all seem janky and ~4-5 years old. What do people use for this nowadays?
44 replies
CC#
Created by Becquerel on 7/27/2023 in #help
❔ ASP.NET Core: differentiate multiple actions per controller based on SOAP XML Body
I have an old legacy ASP.NET project with routes like this: 'http://foobar.com/myservice.asmx'. There are three actions associated with this route that are all GET, differentiated by the HTTP body. E.g., it will contain stuff like <soap:MyFirstAction>, <soap:MySecondAction>, etc. I want to write a drop-in replacement in ASP.NET Core that uses identical routing. I think I can make a controller to house all these actions that just has the static route of [Route("myservice.asmx")] or whatever. But can I have multiple GET actions in this one controller that are only differentiated by the type the XML of the body deserialises to?
2 replies
CC#
Created by Becquerel on 4/8/2023 in #help
❔ Enforcing dotnet format in CI/CD
Does anyone have experience enforcing dotnet format rules in CI/CD? We;re using Azure Devops/TFS specifically. My understanding is that you shouldn't actually format anything in the pipeline, just run --verify-no-changes and use git pre-commit hooks to ensure the code is formatted before it's pushed up. But when I tried to implement this I had unending trouble with the git hooks, since we're on WIndows. Are there any alternatives?
2 replies
CC#
Created by Becquerel on 3/18/2023 in #help
✅ Interesting uses of yield return
I recently needed to generate an arbitrary number of unique random numbers, and after a little thinking I found I could get a really elegant solution by using yield return to generate an infinite stream of ints. This made me realise I basically never use this language feature and there's probably a lot of cool applications for it I'm missing. Any tricks/interesting patterns you've written with it?
24 replies
CC#
Created by Becquerel on 1/14/2023 in #help
❔ What forms of auth are most common for ASP.NET Core?
Both authentication and authorization. I know it's a big topic so I want to start off learning the styles I'm most likely to see in production. Does it depend on the type of project you're doing (MVC, Blazor, APIs)?
6 replies
CC#
Created by Becquerel on 9/11/2022 in #help
Dependency injection, but critical resources are only available after building the service provider
I'm trying to introduce dependency injection to a monogame project. For those unaware, Monogame gives you a Game class with some crucial components (GraphicsDevice and ContentManager) for getting stuff drawn to the screen. These components are only initialized after you construct your Game instance and call .Run() on it, making it 'live'. So far I've been creating my service provider manually inside the Game class and using it as a faux-entry point. However, I really want to move the DI outside and resolve Game like anything else. This is mainly because it'll let me use proper async/await, which I currently can't do. I have a mix of UI services that rely on the Game components (GraphicsDevice etc.) and 'pure' backend services. I can't have separate service providers for backend and frontend services, because the frontend relies on the backend. Is there a way to 'add' services to an IServiceProvider after it's been built? Can give more detail as necessary.
19 replies
CC#
Created by Becquerel on 9/7/2022 in #help
Calculating length of a Span of bytes when encoding text [Answered]
I need a method that takes text, encodes it and converts it to base 64 without allocations (if possible). This is what I have so far:
private Span<char> ToBase64(Span<char> text)
{
// _encoding is UTF-8

// get how many bytes the text will take up when encoded
var byteCount = _encoding.GetByteCount(text);

// alloc array with that count so we can get a Span<byte>
Span<byte> span = stackalloc byte[byteCount];

// write the encoded text into the byte span
_ = _encoding.GetBytes(text, span);

// use the encoded byte span to actually go to base64
// _encoder is a nuget package that asks for an ArraySegment<char>
return _encoder.ToBaseNonAlloc(span.ToArray());
}
private Span<char> ToBase64(Span<char> text)
{
// _encoding is UTF-8

// get how many bytes the text will take up when encoded
var byteCount = _encoding.GetByteCount(text);

// alloc array with that count so we can get a Span<byte>
Span<byte> span = stackalloc byte[byteCount];

// write the encoded text into the byte span
_ = _encoding.GetBytes(text, span);

// use the encoded byte span to actually go to base64
// _encoder is a nuget package that asks for an ArraySegment<char>
return _encoder.ToBaseNonAlloc(span.ToArray());
}
I'm using this to encode/decode JSON. I have a unit test for roundtripping (encode/decode the same object and check it's equivalent) this that is failing.
private class MyObject
{
public string Name { get; set; }
public int Age { get; set; }
public bool Alive { get; set; }
}

[Fact]
public void Encode_ShouldRoundTrip()
{
var obj = new MyObject
{
Name = "John Doe",
Age = 32,
Alive = true
};

var json = JsonConvert.SerializeObject(obj);

// _encoder here is my own class where the above method lives
var encoded = _encoder.Encode(json);
var unencoded = _encoder.Decode(encoded);

var newObj = JsonConvert.DeserializeObject<MyObject>(unencoded);

newObj.Should().BeEquivalentTo(obj);
}
private class MyObject
{
public string Name { get; set; }
public int Age { get; set; }
public bool Alive { get; set; }
}

[Fact]
public void Encode_ShouldRoundTrip()
{
var obj = new MyObject
{
Name = "John Doe",
Age = 32,
Alive = true
};

var json = JsonConvert.SerializeObject(obj);

// _encoder here is my own class where the above method lives
var encoded = _encoder.Encode(json);
var unencoded = _encoder.Decode(encoded);

var newObj = JsonConvert.DeserializeObject<MyObject>(unencoded);

newObj.Should().BeEquivalentTo(obj);
}
It decodes the actual JSON correctly, but then continues onwards, filling up the string with garbage data that causes deserialization to explode. {"Name":"John Doe","Age":32,"Alive":truep4��bY,P�&��4]�!�V��!�]D��aQ<@0XbUh2VaplSHNXUThGbhhUTwQQP==
16 replies
CC#
Created by Becquerel on 9/2/2022 in #help
Grouping an IEnumerable based on multiple fields of the target type
I have an object Foo like this:
public class Foo
{
public bool CanA;
public bool CanB;
public bool CanC;
public bool CanD;
}
public class Foo
{
public bool CanA;
public bool CanB;
public bool CanC;
public bool CanD;
}
Given a List<Foo>, I'd like to group them into some kind of collection based on whether these fields are true or not. An item would appear in multiple lists if multiple of these are true. I am currently thinking along these lines:
var dictionary = new Dictionary<string, List<Foo>>();

dictionary.Add("Can A", mySource.Where(x => x.CanA).ToList());
// repeat for B, C, D
var dictionary = new Dictionary<string, List<Foo>>();

dictionary.Add("Can A", mySource.Where(x => x.CanA).ToList());
// repeat for B, C, D
It feels like I should be able to do this more neatly with GroupBy or something, but I've only used that with single values before. Anyone done this?
2 replies
CC#
Created by Becquerel on 9/1/2022 in #help
Dependency injection - transient services inside a singleton?
I'm in Monogame (not my choice) and using DI to resolve various services I need, including those that represent user-facing screens. These screens live inside a big game-loop class that lives for the lifetime of the app. I want those screens to be refreshed every time they're activated. Currently I have them set up with a standard constructor that takes in their dependencies and an Initialize() method that refreshes their state. I'd rather be able to get the screens constructed from fresh each time they're needed. What's a good pattern for doing this? It seems analogous to making viewmodels in WPF-style frameworks. What I did there was pass around Func<MyViewModel>s, which pointed at the provider's GetRequiredService<MyViewModel() call to ensure all the dependencies were injected correctly. However, that doesn't seem like a particularly nice solution either. Is there a good way to do this? If I setup my views as transient services, injecting them into a singleton will just capture them, right?
7 replies
CC#
Created by Becquerel on 8/31/2022 in #help
Rider suggestion - creating a property for a DateTime field will introduce struct copying
I encountered this warning from Rider recently when refactoring some old code. I had a class with several DateTime fields and wanted to turn them into autoproperties. Rider warned me that this would introduce struct copying. I didn't get any compilation errors after this, so am I right in assuming it's just a potential performance issue? Why does a property accessor introduce struct copying when field access doesn't? Should I care?
2 replies
CC#
Created by Becquerel on 8/20/2022 in #help
Installing the 3.1 SDK on Linux via package manager [Answered]
Maybe a stupid question, but I'm trying to install 3.1 because I think Monogame requires it. When I run apt-cache search dotnet, I only get results for 6.0. Have the packages for 3.1 been discontinued? I kind of don't want to install manually - just feels a bit untidy. I'm on PopOS if that is relevant.
9 replies
CC#
Created by Becquerel on 8/17/2022 in #help
Idiomatic LINQ way to access both object and an object's property? [Answered]
var list = new List<string>();

foreach (Item item in items)
{
foreach (string thing in item.Things)
{
list.Add($"{thing} + {item.OtherProperty}");
}
}

return list;
var list = new List<string>();

foreach (Item item in items)
{
foreach (string thing in item.Things)
{
list.Add($"{thing} + {item.OtherProperty}");
}
}

return list;
I'd like to do this with LINQ. Normally I would use .Select(), but if the inner operation needs both an object (item) and an inner property (thing), I don't know of a clean way to do it. I can .Select() into a tuple containing both items, but this is really ugly. Any idea?
10 replies