.status-msg-wrap { display: none; }
Wednesday, October 31, 2018
no image

Messages from referenced DLL

I have a .net core 2.1 app that includes a full framework 4.6.1 class library (at the moment i can't change this to .net standard)

I want messages in the class library to be visible to a LogProvider in the .net core.

Is it possible to capture any or all of the following in the .net core app?

System.Console.Write(message);

System.Diagnostics.Trace.TraceInformation(message);

System.Diagnostics.Debug.WriteLine(message);

_source = new TraceSource("NAME", SourceLevels.All);

_source.TraceEvent(TraceEventType.Verbose, 0, message);

Visual Studio Debugger does see the messages in the Debug output.

Messages from referenced DLL Click here
no image

Allow .NET Core service controller to return custom XML payload without throwing 406 Not Acceptable?

Hi all,

Using .NET Core 2.1 and trying to build a simple web service controller that processes the raw HTTP request and returns a custom response. To be more specific, I have a few SOAP methods from legacy systems that perform simple calls I want to just take the incoming SOAP XML, parse it using .NET Core's XML parser and return a response. I'm not interested in writing pages of code or using a SOAP library for .NET Core to accomplish this. This task at hand just doesn't require the overhead.

In my controller:

 [HttpPost] [Route("api/SoapRequest")] public async Task<string> SoapTest() { string response = ""; Response.Headers.Clear(); Response.ContentType = @"application/soap+xml; charset=utf-8"; //string result; using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { string soapBody = reader.ReadToEnd(); response = BuildSOAPResponse(soapBody); } return response; } 

And the server accepts the incoming XML, builds my SOAP payload but on return I get this nasty "406 Not Acceptable"

HTTP/1.1 406 Not Acceptable < Content-Type: application/soap+xml; charset=utf-8 < Server: Kestrel < X-SourceFiles: =?UTF-8?B?YzpccHJvamVjdHNcZG90bmV0XE1HMlJlYWxtQVBJQWRhcHRlclxNRzJSZWFsbUFQSUFkYXB0ZXJcYXBpXGJvZHlUeXBlc1xSZWFkU3RyaW5nRGF0YU1hbnVhbA==?= < X-Powered-By: ASP.NET < Date: Wed, 31 Oct 2018 22:47:11 GMT < Content-Length: 0 

In Startup.cs I'm explicitly telling ASP.NET to ignore HttpNotAcceptable (if I understand the flag correctly) I've also explored adding the StringOutputFormatter() which doesn't work. Also the generic XML Formatter fails as it doesn't like the "application/soap+xml..." Content-Type.

 public void ConfigureServices(IServiceCollection services) { // services.AddMvc(); //(o => o.InputFormatters.Insert(0, new RawRequestBodyFormatter())); services.AddMvc(options => { options.ReturnHttpNotAcceptable = false; // If you need to add support for XML // options.OutputFormatters.Add(new StringOutputFormatter()); }); } 

Does anyone know of a simple fix to this? Should I write my own custom OutputFormatter? I can't find any examples of how to do that. Thanks!

Allow .NET Core service controller to return custom XML payload without throwing 406 Not Acceptable? Click here
no image

What's the best project structure to maintain multiple modules and services ?

Hello,

i plan to develop modular project (similiar to CMS) and i am not sure what's the best option how to maintain project.

I would like to have everything under one solution. So what's an example ?

User/Service/Module:

- handling user registration, login and so on

- contains model, migrations...

WebModule MVC:

- contains forms, controller logic, calls to UserModule

MyService

- calls 3th party REST API

- contains model, migrations...

- can be used from other MVC module

I would like to cut dependencies between projects. There will be around 10-15 feature modules. Desired result is when i put UserModule to other project, different MVC i will just run migrations and it will be possible to use it. And here are some questions.

Develop custom modules and service modules as WebAPI projects or use projects references ?

Should i put all database models under one distinct project which will contain all migrations ?

What about projects deploying ?

Any other tips how to maintain ?

Net.Core

Thanks much, i appreciate every comment.

What's the best project structure to maintain multiple modules and services ? Click here
no image

Razor Pages inline routing

IM trying to learn .Net Core and Razor Pages and I'm following this video step-by-step. The link starts at a specific time in the video where the presenter adds @page "{Id}" which allows him to consume the routing variable directly via RouteData.Values["Id"]. When i try this my web app stops working, giving result of Page not found. Soon as i remove it it works again. I've tried this in both Core 2.0 and 2.1.

Is anybody else able to do this and if possible, can you tell me what it is called so i could perhaps do some googling on it? I'm struggling to find relevant information on it.

Razor Pages inline routing Click here
Tuesday, October 30, 2018
no image

Adding a dotnet standard with core nugets to a an older core project

I have am creating a .NET standard package that has version 2.1.1 of the Microsoft.AspNetCore.Http nuget package in it.

I need to add this nuget to all of our core projects and I add it to a test core project of the same version and it works great, but when I try to add it to a project with version 2.0.6 of Microsoft.AspNetCore.All and I get a version conflict

Assembly 'Nuget.Project' with identity 'Nuget.Project, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'Microsoft.AspNetCore.Http.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=xxxxx' which has a higher version than referenced assembly 'Microsoft.AspNetCore.Http.Abstractions' with identity 'Microsoft.AspNetCore.Http.Abstractions, Version=2.0.3.0, Culture=neutral, PublicKeyToken=xxxxxx'

I changed the tokens to x's and replaced the name of the project for privacy reasons.

My Nuget is accessing HttpContext so I need the Core in it. I don't know how to make the nuget package okay to put on older versions

Adding a dotnet standard with core nugets to a an older core project Click here
no image

Referencing a web api

In a Visual Studio webform app is referencing a web api the same as importing the library via nuget, it just doesn't import the entire library into the project?

Referencing a web api Click here
no image

How do you automatically update user claims in a SAAS application after cancellation?

I was wondering if there's any best practice on updating a user's claims based upon a monthly payment schedule and when the user decides to cancel.

Example:

A user signs up and gets on a recurring payment plan. Each month when the payment is auto-processed (thanks to stripe), it looks like you need to create an api endpoint for stripe to ping when payment has been successful.

When this is successful, you ensure the user's claim is set to "active" (or whatever) and a update the end date in the db.

When a user cancels or payment unsuccessful, a stripe response is sent to your api endpoint to notify the system of cancellation and you update the claims, and db.

However, my question is, how do you keep that account active for only 6 more days if the user cancels on the 25th of the month? And how do you auto shut it down? A check at login?

How do you automatically update user claims in a SAAS application after cancellation? Click here
no image

Invitation to join a, friendly C# community

Hello!

Are you someone, who is looking for a place to stay, where people help you out with your daily programming questions. Maybe you’re someone who would like to share their experience instead. We’re here for you!

C# inn- a friendly community would like to invite you to join! We’re a young and growing community with over 500 members, with dozens of new members joining daily. Our members help each other out and we try to keep as friendly atmosphere as possible. Your opinion matters to us, our staff listens to your needs and suggestions, so we’re constantly changing and trying to be a bit better than we were yesterday, by adding/removing channels, coming up with ideas, planning the future. We’re mostly focused on C#, but there are other channels for other languages, as requested by our community :)

Also, every weekend we have programming lessons, where people can learn C#, object oriented programming, clean code. We also have some people streaming live coding and sometimes some members offer mentorship on a project or topic.

Invitation link: https://discord.gg/Bfme3PD

Looking forward meeting you!

Invitation to join a, friendly C# community Click here
no image

Accessing accessing a child control within a custom usercontrol

Sorry in advance if this is a stupid one. I can't seem to figure out this detail and I'm guessing it's pretty basic.

I have a custom usercontrol that consists of a few controls, including a datagrid. Most of the time the data that gets populated in the grid, are just strings, but occasionally I need to apply formatting or suppress columns, so I need to be able to access the datagrid.

I've made a public property on the usercontrol that returns the gridcontrol. I was expecting it to work something like this:

<comp:MyControl>

<comp:MyControl.MyGrid>

<comp:MyControl.MyGrid.Columns>

....do something here

/comp:MyControl.MyGrid.Columns

/comp:MyGontrol.MyGrid

/comp:MyControl

But, it doesn't seem to work that way, or I'm missing a step. MyGrid is innaccessable. If anyone can set me on the correct path, it would be greatly appreciated. Thank you.

Accessing accessing a child control within a custom usercontrol Click here
no image

CI/CD options for .Net 4.x web apps to dedicated server from BitBucket?

Our source code is in Bitbucket and currently I'm deploying the apps using WebDeploy publishing to IIS from Visual Studio. I need a more automated process as the number of sites is increasing, and something that would include some JS and CSS build steps.

Ideally I'd like the process to be: 1) Push to master branch 2) Tool automatically grabs the source code, runs an npm install, runs npm build and gulp to process the JS/CSS 3) Results published to IIS

Optionally I'd also like the tool to run a set of unit and integration tests before the final publish. I'm open to CI/CD services or installing software on the server but our budget is small.

If you need specifics it's currently a single solution with 3 web app projects, each of which need to be deployed to a test, staging, or live server depending on the branch being pushed, using webpack to compile/transpile Vue and gulp to build CSS from SASS.

CI/CD options for .Net 4.x web apps to dedicated server from BitBucket? Click here
no image

Publish to a windows server?

So I have created an app just for the fun of learning mvc..

Now I would like to put it online, but how? I have an account at a hoster from before which serves my php applications, but there is also the possibility to create webspace for a asp.net account and SQL Server.

How do I publish using visual studio? Or is it done using FTP?

EDIT: Oh and I have read about it, seems you should use something similar to Remote desktop? But I don't have access to any RD at my current hoster.

Publish to a windows server? Click here
Monday, October 29, 2018
no image

Libraries for working with data?

What are your favorite libraries/resources in .NET for working with data? I don't do any fancy machine learning, but my job is starting to entail more and more data engineering - retrieval/cleaning/parsing/etc - as well as some basic regression fits and graphing.

For right now, I can't make use of Python's extensive packages for such (pandas, etc.) because of management's fear of open source.

Any suggestions? Thanks.

Libraries for working with data? Click here
Sunday, October 28, 2018
no image

Which approach should I take when building a real-time app with SignalR?

I'm thinking about creating a real-time app. The main application will be WPF-based, and will need to support a few real-time features. Users will be able to move controls around on a canvas. The delta's don't need to be transferred, but the final mouse-up positions will be. The application will also have a text-based chat system among other things.

Let's say that, for every control on the canvas, I have an object in my database. Let's also say that the X's, Y's, Width, and Height are updated in the database on mouse up of the control.

Do you think it would be wise to have client's update the database with their changes... and then simply pass the SignalR enabled web server the Id, Entity Type, and CRUD operation type. Then SignalR will broadcast that message to everyone else and the other client's will pull the data from the DB themselves?

How scalable is this type of approach in general?

Or should I pass the relevant data in my message so the client's don't need to fetch it?

Any pointers to worthwhile resources will be appreciated!

Thanks for looking

Which approach should I take when building a real-time app with SignalR? Click here
Saturday, October 27, 2018
no image

.NET Framework doesn't work

Hi!

I get the following error, whenever I try to start a .Net application: ".NET Framework Initialization Error: To run this application, you first must install one of the followig versions of the .NET Framework: (...)". For the first time, I got the "Please set registry key - HKLM\Software\Microsoft\.NETFramework\InstallRoot to point to the .NET Framework install location" error, that I could solve easilly, then came this.

I tried all of the solutions that the Google showed on the first pages for this errors, but nothing has changed. The "Please set registry key" atleast disappeared, but the other one still exists.

What caused the error?

I made a scan with Avira's bootable antivirus (I had no viruses, just made a general scan), that deleted something by itself that was necessary. Unfortunately, I don't know exactly what it is, because my PC went into sleep mode after the scan and I didn't manage to wake it up, back to the antivirus (I guess it was because the OS run on a USB/on RAM), so I restarted to Windows.

Which programs don't work?

Many apps don't even start, without giving an error message, ie. IObit Uninstaller, Gmail Notifier(however, this one gave the registry error before solving it); other apps gives the "you first must install" error, ie. vibrance GUI; there are apps that don't manage to connect to the internet, ie. Steam; and the Office 365 lost his license key, and I can't log in, because the sign in window is empty.

Among many others, I have thried these: turning off and then back the .NF in the Windows features, .NET Framework Repair Tool, .NET Framework Setup Verification Tool, .NET Framework Cleanup Tool. .NF isn't listed between my apps (neither in Contor panel, nor in Settings). I tried to delete all of the .NF's, I managed I guess, but the installers still see them as installed, so they don't allow me to install again. In C:\Windows\Microsoft.NET the folders still exist, but it isn't a good solution to delete them manually, I guess. I think the problem is with the Windows 10's built-in frameworks. The Verification tool fails for every version above 3.5.

Is there any solution except reinstalling the Windows?

.NET Framework doesn't work Click here
no image

IIS error: "Creation of the virtual directory failed with error: Filename '...//.vs/config/applicationhost.config' Error: Cannot write configuration file" (ASP.NET)

I have 3 PCs, so to streamline development I use Onedrive (BEFORE YOU CRUCIFY ME: I use Github for bigger projects, I know Onedrive is risky). So I assume that's why I'm getting this error.

But this only happens on one of the computers, the other two are fine (my Surface does give me an error, but not this, and it works fine there).

I'd rather not reinstall VS again, and somehow I doubt that will fix it since it's an IIS error.

I've tried to get the IIS manager, but it refuses to install on Windows 10. Also I didn't have to do this on my other PCs so again I doubt this will fix it.

IIS error: "Creation of the virtual directory failed with error: Filename '...//.vs/config/applicationhost.config' Error: Cannot write configuration file" (ASP.NET) Click here
Friday, October 26, 2018
no image

MySQL and Xamarin Connection Issue

Having trouble getting my Xamarin project to open a connection to MySQL. In a basic console app using the full .net framework the code runs fine, but in my xamarin project running on .net standard 2.0 it fails. Any suggestions on how to handle this?

From what I have read .net standard doesn't work with the connector and the best way around it is to use a web api, is that true?

Any help is greatly appreciated I am fairly new to Xamarin.

MySQL and Xamarin Connection Issue Click here
no image

Is anyone aware of a good set of articles discussing VB.Net for C# developers?

Let me give a bit of background. I've not used VB since the early days of my career and back then VB was VB6, not .Net. Once .Net came out, I played around a bit with VB.Net, I'm well aware that it's significantly different than VB6 but I also am quite aware that it's not at all like C#.

I've found plenty of "C# for VB.Net Developer" tutorials, but is there a good set of tutorials/articles that have the reverse perspective? I ask because I have a potential client who needs a developer who can do some C# work, but has a lot of VB.Net code that needs to be written into an existing application. I'm considering taking on this client, but I need to review VB.Net from the perspective of an experienced .Net developer.

Thanks guys.

Is anyone aware of a good set of articles discussing VB.Net for C# developers? Click here
no image

Show: RunInfoBuilder - command line parser using object trees, my first open src project

https://github.com/rushfive/RunInfoBuilder

Hey guys, I spent some time building out a command line parser, mainly for fun and for use in another project im going to work on.

What's different about this compared to other parsers out there is that it doesn't use attributes to "tell" the parser how to handle arguments. Rather, it requires you to completely layout, in code, how a command should be configured and handled using a configuration object.

Would love to hear any feedback, comments, or anything else that you think of.

Thanks for taking the time to check it out!

Show: RunInfoBuilder - command line parser using object trees, my first open src project Click here
Thursday, October 25, 2018
no image

How to download and install the .NET Platform SDK (Roslyn) offline?

Currently my only source of internet is my phone, but my carrier doesn’t allow hotspot tethering so I just download to my phone and transfer to my computer. I’ve been wanting to try getting my feet dirty in Roslyn and code analyzing but it appears as though I’m out of luck. I even tried downloading it off of the Visual Studio marketplace but still no prevail. Any ideas? I really want to see what everyone is talking about.

How to download and install the .NET Platform SDK (Roslyn) offline? Click here
no image

Any recommended libraries to obfuscate embedded javascript?

Does anyone have any recommendations for libraries/nuget packages that can obfuscate javascript that is embedded in razor pages?

I'm specifically talking about js that's been written within a <script> tag in a razor page.

Thanks!

Any recommended libraries to obfuscate embedded javascript? Click here
no image

Some questions about old code, older frameworks, UWP and .NET Core?

Ok, so first of all sorry if this post is all over the place or does not make perfect sense. Honestly my head is all over the place about this. I am by no means an expert, but I make do.

I have some old code that targets .NET framework 4 and I would like to start down the path of developing a "companion" style mobile application for some of my users. The idea is this would be a bare bones app that runs on a handheld device that has the capability of performing a select few of the lighter tasks that can be done with the full desktop software.

My question is about upgrading the framework on these older class libraries to something that can be referenced by a UWP application. I understand that they need to be .NET Core (Standard?) libraries and that .NET 4.5+ should implement that? Does that mean I should just make these libraries target 4.5 since that is the minimum or do I go for the latest? Should I be targeting one of these Core frameworks instead? My guess is that upgrading the class libraries would also require me to upgrade the windows forms applications that reference them. Will windows forms still support the upgraded class libraries? Thank you in advance!

Some questions about old code, older frameworks, UWP and .NET Core? Click here
no image

.Net Core Authentication middleware for JWTs - ValidateIssuerSigningKey not working as expected

I assumed that when a JWT is sent to my.Net Core API, the payload is hashed together with the expected signing key and is then checked if the result matches the signing key included in the JWT, and if it does not match it would be rejected as Unauthorised.

The problem is that I created a unit test where I constructed a JWT (like I normally would do for any other token), decrypted it manually, swapped the payload out for another with different user claims, encrypted it back without touching the signing key (so it should no longer match) and header parts of the token, and then sent it to the API, but the API validated it successfully and the request was not rejected.

Here are my Authentication options:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { // validate server that created token ValidateIssuer = true, ValidIssuer = Configuration["Jwt:Issuer"], // check if recipient of token is authorized ValidateAudience = true, ValidAudience = Configuration["Jwt:Audience"], // check if key used to sign token is known to server ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Signingkey"])), RequireSignedTokens = true, // check if token has expired ValidateLifetime = true, RequireExpirationTime = true, ClockSkew = TimeSpan.Zero, // enable decryption of the token using same secret TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Secret"])) }; }); 

And, before anyone asks the obvious, I am using it:

app.UseAuthentication(); // before UseMvc and most other middleware 

Here is my unit test (very messy and large but it's more of a spike):

[Test] public void When_Calling_PostAsync_With_Tampered_Payload_And_Original_Header_And_Signature_Then_Should_Return_Unauthorized() { // arrange var originalEncryptedToken = SetupAuthTokenAndApiSender(); var originalDecryptedToken = Decrypt(originalEncryptedToken); var sections = originalDecryptedToken.Split("."); var originalRawHeader = sections[0]; var originalRawPayload = sections[1]; var originalRawSignature = sections[2]; // create another token with a different account ID var otherAccountId = Guid.NewGuid(); Claims.AddClaim("account_id", otherAccountId.ToString()); Claims.AddClaim("anotherKey", "anotherValue"); Claims.AddClaim("stack_id", "2d563cfb-e4a7-4d7e-a8ff-8291b97ee56e"); var otherEncryptedToken = SetupAuthTokenAndApiSender(); // join original header and signature with the payload from the other token and then encrypt the results var forgedEncryptedJwtToken = SwapPayloadAndEncrypt(originalEncryptedToken, originalRawHeader, originalRawSignature, otherEncryptedToken); // decrypt new forged token to assert whether the JWT sections are as expected var forgedDecryptedToken = Decrypt(forgedEncryptedJwtToken); sections = forgedDecryptedToken.Split("."); var forgedRawHeader = sections[0]; var forgedRawPayload = sections[1]; var forgedRawSignature = sections[2]; var innerForgedTokenPayload = JwtPayload.Base64UrlDeserialize(forgedRawPayload); // act TestAudit.AccountId = otherAccountId; var response = TestPostAsync(TestAudit); // assert originalRawHeader.Should().BeEquivalentTo(forgedRawHeader); originalRawPayload.Should().NotBe(forgedRawPayload); originalRawSignature.Should().BeEquivalentTo(forgedRawSignature); innerForgedTokenPayload.Claims.Should().HaveCount(8); innerForgedTokenPayload.Claims.Should().Contain(c => c.Type.Equals("account_id") && c.Value.Equals(TestAudit.AccountId.ToString())); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", forgedEncryptedJwtToken); response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.Unauthorized); } 

So, basically, the header and signature sections are identical to the original token but the payload is very different. The signature signing key does not match the payload anymore so why is the server accepting it? All ideas are appreciated, thank you.

.Net Core Authentication middleware for JWTs - ValidateIssuerSigningKey not working as expected Click here
no image

Looking for a good way to manage a lot of web.config files from localhost through production

We have over 100 unique applications (web apps, web services, win services) along with their web and exe.config files that need to be managed in several environments (localhost, dev, test, pre-prod, prod, livedemo) and each one shares some common files such as a standardized connectionStrings file with approx 120 connection strings per environment. Keeping track of, and maintaining them all is nearly a full time job and one of our biggest pain points when deploying. Are there any tools that help manage these better?

I've played with Slow Cheetah and Fast Koala. they don't do quite what I'm looking for. I'm working on trying to create publish profiles and transforms as well as parameters.xml, but with so many apps and so many environments, it's a big task to take on.

I'm not sure what silver bullet I'm looking for... but I'm running dry on ideas and hoped maybe someone could throw out some thoughts on what they do to manage theirs.

Looking for a good way to manage a lot of web.config files from localhost through production Click here
Wednesday, October 24, 2018
no image

Exchange EWS API

I've got a VB dot net sub I'm thinking about reworking. It currently runs on a timer and checks for emails and their attachments and stores them in a database. The current code appears to be using Exchange EWS API Proxy to do this. The ExchangeVersionType is using 2007 and the biggest problem we have with it right now seems to be that if an email contains an image in the senders signature it crashes. We have to manually remove the image and resend the email to the inbox of the account it gets the emails from.

I just went through the code today to get a better understanding of how it works and noticed there are two libraries for handling emails - Exchange EWS and Exchange EWS proxy. I'm just curious what the major difference is between these two API's? Can I use either of them to do what I need to do?

Exchange EWS API Click here
no image

Unit testing private methods, should you make them public violating O (open/close) in SOLID or use a framework like Moq to to test the private methods via the public ones?

I'm trying to figure the best way to unit test GetHumanPlayerShot and CreateComputerShot private methods in the code sample below. They don't need to be public, so making them so would break open / closed principle in SOLID.

Whats the best way to unit test private methods? is there a way to check they are called with a unit test and check the result? I can mock out RandomLocationGenerator.Generate(0,10) as that implements an interface.

For brevity, ive omitted some code / classes in my example code

The only public method that needs to be exposed is RunGame as it returns the gameState.

Should i make methods public to make them testable or is there a better way?

public interface IBattleShipGameStateMachine { GameState RunGame(); } public class BattleShipGameStateMachine : IBattleShipGameStateMachine { public BattleShipGameStateMachine(IGame game, IConsole consoleWrapper, IRandomNumberGenerator randomLocationGenerator) { this.ConsoleWrapper = consoleWrapper; this.Game = game; this.RandomLocationGenerator = randomLocationGenerator; this.ValidShotTester = new Regex(@"\d+,\d+", RegexOptions.Compiled); this.gameState = GameState.NotStarted; } private GameState gameState { get; set; } public GameState RunGame() { this.gameState = GameState.GameRunning; IPlayer playerOne = this.Game.Players.First(p => p.PlayerNumber == 1); IPlayer playerTwo = this.Game.Players.First(p => p.PlayerNumber == 2); while (!this.gameState.Equals(GameState.PlayerOneWon) && !this.gameState.Equals(GameState.PlayerTwoWon)) { // human and computer take turns shooting Location shot = this.GetHumanPlayerShot(); if (this.gameState.Equals(GameState.PlayerExit)) { break; } // logic omitted here to check if ships hit / all ships sunk etc Location shot = CreateComputerShot(); } return this.gameState; } // creates a location x,y. need to unit test this to ensure its a valid location private Location CreateComputerShot() { int x = this.RandomLocationGenerator.Generate(0, 10); int y = this.RandomLocationGenerator.Generate(0, 10); Location shot = new Location(x, y); while (otherPlayer.Board.Coordinates[shot] == CoordinateState.ShotHit || otherPlayer.Board.Coordinates[shot] == CoordinateState.ShotMissed) { x = this.RandomLocationGenerator.Generate(0, 10); y = this.RandomLocationGenerator.Generate(0, 10); shot = new Location(x, y); } return shot; } private Location GetHumanPlayerShot() { while (true) { this.ConsoleWrapper.WriteLine("Enter x,y coordinates e.g. 1,2 or x to quit"); string shotCommand = this.ConsoleWrapper.ReadLine(); if (shotCommand.Equals("x", StringComparison.InvariantCultureIgnoreCase)) { this.gameState = GameState.PlayerExit; return new Location(0, 0); } Match match = this.ValidShotTester.Match(shotCommand); if (match.Success) { string[] playerCoordinates = shotCommand.Split(","); int x = Convert.ToInt32(playerCoordinates[0]); int y = Convert.ToInt32(playerCoordinates[1]); if (x > this.Game.BoardSize || y > this.Game.BoardSize) { this.ConsoleWrapper.WriteLine("Invalid shot try again"); continue; } Location shot = new Location(x, y); return shot; } this.ConsoleWrapper.WriteLine("Invalid shot try again"); } } } public struct Location { public Location(int x, int y) { this.X = x; this.Y = y; } public int X { get; set; } public int Y { get; set; } } public enum GameState { [Description("GameRunning")] GameRunning, [Description("NotStarted")] NotStarted, [Description("Exit Game")] PlayerExit, [Description("Player One Won!")] PlayerOneWon, [Description("Player Two Won!")] PlayerTwoWon } 
Unit testing private methods, should you make them public violating O (open/close) in SOLID or use a framework like Moq to to test the private methods via the public ones? Click here
no image

Difference between AddScoped, AddTransient, AddSingleton ?

I understand the difference in short, but I don't have a lot of experience with ASP NET Core so I got away with using transient all the time so far. What are the potential situations when I would want a scoped or a singleton service?

Difference between AddScoped, AddTransient, AddSingleton ? Click here
The webdev Team