New answers tagged

0

Problem Size This is an exponential problem in passwordLength. Your on-screen output and file output is going to take a maximum of 7^62 = 3,521,614,606,208 words, each "New password: " + 7 + "\n", minimum 22 bytes in UTF-8, that's over 70 TiB. I would choose another format to express it in, since this is unlikely to complete. Maybe with a ...


0

In addition to the post by @aepot, I made the following changes which reduced the completion time significantly. I used a dictionary instead of a list to query patient Id. Querying a large list of objects in for loop is what really slowed down the processing. Here's what the code looks like now: for (int i = 0; i < ptdiags.Count; i += BATCH_SIZE) { var ...


0

Another approach. public static async Task ForEachAsyncSemaphore<T>(this IEnumerable<T> items, Func<T, Task> func, int dop, CancellationToken ct) { async Task operation(T item, ...


1

Few syntax improvements first: private EmployeeModel _selectedEmployee; public EmployeeModel SelectedEmployee { get => _selectedEmployee; set { if (Set(ref _selectedEmployee, value)) { Messenger.Default.Send(new EmployeeToken(value)); // ensure that you don't block the UI Thread for a long time ...


1

Async method out-of-the-box is using multiple threads for continuations. (Everything after await is continuation). Exception of this rule if existing SynchronizationContext. Don't Task.Run asynchronous I/O-bound operation, do it only for synchronous CPU-bound one. Asynchronous programming, SynchrinizationContext & TaskScheduler. Mixing .ContinueWith and ...


3

Overall a very good first attempt at a "real" project. Drop "Manager" class name suffix — Consider renaming GameManager to simply Game. Similarly rename ScoreManager to something like GameScore. I see the "Manager" suffix frequently applied to classes that do not really manage something. Read I shall call it... Something ...


3

I can see a few improvements that can be made. First, you can make ResponseCacheKeyProvider static. and rename it to something like HttpCacheProfileProvider so you can control all Requests/Responses headers, and can be related to the CacheProfiles class as well. Then, you can make some improvements to it like using IReadOnlyList instead of List to have read-...


1

one way of solving this would be using Task.WhenAll the idea is to add all tasks into a list of tasks then we call Task.WhenAll and await the final results. Here is an example of it : private async Task<ProductItem> SetSiteLink(ProductItem item) { item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink); return Task.FromResult(...


1

Method has multiple mix responsibilities, it should have one responsibility and clearer scope. variable naming doesn't follow naming convention (e.g. id , fm, str) you should always pick a clearer names for your variables. when parsing or converting types, you should always validate them or use the appropriate conversions methods such as int.TryParse. always ...


0

Consider making the settings more readable and strong-typed: public enum Modes{ Mode1 = 1, Mode2 = 2, Mode3 = 4, Mode4 = 8, } public class Config { private Modes configVal; public void SetConfig(Modes modes){ this.configVal = modes; } public bool AreAllSet(Modes modesAllSet) { return ((int)this....


0

I am going to expand upon @OlivierJacot-Descombes answer and offer an alternative. You do not have to limit yourself to a single method signature. And you do not have to use a BitArray. My answer is strictly offered as an alternative but I make no claim as to performance. But since the backing data storage to a BitArray is an internal int[], much of the ...


0

You could use a params array to pass the parameters public void SetConfiguration(params bool[] modes) { var setBits = new BitArray(8); for (int i = 0; i < modes.Length; i++) { setBits.Set(i, modes[i]); } byte[] byteSet = new byte[1]; setBits.CopyTo(byteSet, 0); _mode = byteSet[0]; } You might want to add tests to ...


2

I'm not sure I fully understand the question, but the first thing that leapt to mind is: <T> can encompass a IList<SomeType> already. I mean, the first 75% of GetValue() already works with using IList as the generic type: public async Task<T> GetValue<T>( string cacheKey, Func<Task<T>> getItem, ...


3

I am the one who added the Homework tag to the post. I will answer your question under the premise that you are a student and that perhaps your instructor has not yet covered some C# features to you but will as the curriculum progresses. @Hescacher gave the standard advice that continually modifying the same string is slow and inefficient. Instead, a ...


3

I think the EventfulConcurrentQueue was not designed for this use case. From the consumer perspective: Things that are not in use IsEmpty Enqueue ItemEnqueued ItemDequeued Things that are missing DequeueAtMostNItems WaitUntilThereAreEnoughItems After I removed the not used things and added the missing ones the class would look like this: public sealed ...


1

I agree with what pacmaninbw says, just a couple more things: For a task object the minimum I'd have is an Id property (unique, make it a private set and initialize it in the constructor), Name (doesn't have to be unique but might be better from a user perspective), and Description (doesn't need to be unique). If you end up storing this in a database you'll ...


1

Simple answer is yes. when you open a connection in a Using statement, once the scope leaves that statement, it automatically disposes of the connection, there really isn't a reason to explicitly close the connection when implementing a Using statement. Reference: Microsoft Reference to the IDisposable Interface that is implemented by the DbConnection Class -...


1

General Observations After reviewing this code it is clear that the 2 functions come from 2 different classes, one class called OrderData which contains the first function shown (with the actual database query) and a second class currently unknown that contains the second function shown. To really help you optimize the code we would need to see the full ...


3

Quick remarks: Please follow the Microsoft naming guidelines. Parameters should be camelcase, same with local variables. Don't write your own ORM or use ADO.NET. Instead, use Dapper. In the middle of retrieving your data from the DB, you start filling MenuItemsXml. Don't do that. Simply retrieve all the values, close the connection, and then start ...


1

Applied few minor optimisations to the code from the OP's answer. Also fixed naming issues (locals name starts from a lower-cased letter). class Program { static void Main(string[] args) { int t = int.Parse(Console.ReadLine()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int n = ...


0

I was finally able to reduce it enough to return result for 1 million inputs in around 10 secs. class Program { static void Main(string[] args) { int T = Convert.ToInt32(Console.ReadLine()); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < T; i++) { int N = Convert.ToInt32(Console....


2

As a very basic application this is fine, however, if the program becomes more complicated and you want to add a data base and asynchronous programming you will run into conflicts with some of the class names. For instance the Task class is supplied by the C# library for asynchronous programming. If I was going to implement a task list application I would ...


3

Performance wise using string concatination (output += ) inside a loop isn't the best choice because for each output += a new string is created because strings are immutable. Using a StringBuilder would be the way to go. But instead of returning a string, you could return an IEnumerable<string> which would make the code more flexible. Passing an ...


0

I frequently write extension methods for IPrincipal and ClaimsPrincipal objects (depending on .NET framework version). Creating an abstraction for a business concept is a good idea, because it centralizes this knowledge (think: Single Source of Truth). If this happens to change in the future, you have one file, one method to modify. Option 1 is preferred, ...


1

Your query is rather baffling. You twice join with the USER table and yet I cannot see any reason for this. This is what I cannot understand: (s.Price /( SELECT COUNT(DISTINCT payer.ID) FROM payer WHERE ShopID = s.ID ) - p.Payed ) AS Topay: you divide the price by the amount of payers? Why? Honestly, I cannot figure out your data model. Why do Shoping ...


1

There are quite a few naming issues in your code. You may want to think about installing a spell check extension in your IDE to help you catch these. I'm an appalling speller so I've got extra spell checks everywhere (IDE, browser etc.) Naming is so important and the thing that is most important of all is that your naming is consistently applied. In your db ...


0

I already found the problem, in the generate item row loop here // Generate Item Row if (dataList != null && dataList.Any()) { int rowNumber = 1; foreach (var item in dataList) { item.RowNumber = rowNumber; var row = sheet.CreateRow(rowNumber); columnIndex = 0; foreach (var prop in props.Where(p => p....


1

If you want to reduce the iteration to get the value for ColumnC and ColumnD and make the code cleaner, you can try using Aggregate instead. var output = input .GroupBy(d => new {d.ColumnA, d.ColumnB}) .Select( g => g.Aggregate( new MappingClass {ColumnA = g.Key.ColumnA, ColumnB = g.Key....


1

Passing the context that way is acceptable but the problem with the context that you have is that it can grow larger the more you add custom statements. This is an anti pattern, because it can be a GOD Object. And if you create new custom statements in the future you may need to touch the context again, which tainted the SOLID principle. The better approach ...


3

IMHO - I usually use recursive to break down a complex loop code into a simpler and smaller code. So if the function I end up created is still a complex one I'd rather use loop instead. In your case it's simpler and easier to do loop instead of recursion. public static int[] BubbleSort(int[] arrayOfValues) { bool swapOccurred; do { ...


0

If you want to take it a bit further and making it a generic unique name / id generator that can be used for anything, we would need to analyse it a bit more. One important aspect is to reserve the unique name you just generated so it cannot be used by a parallel thread/process as well which is quite likely if both look at what was the last name and increase ...


3

Less efficient? It consumes more stack space, which shouldn’t be a problem for any dataset where a bubble sort would be appropriate. With the latest version of the c# compiler, tuple deconstruction will allow you to swap the values with a single line of code (although it will probably be slower). On a side note, I’m not clear on why you have a separate ...


5

Too fancy, too hard to read. The whole code can be compressed into something like BCrypt.Net.BCrypt.HashPassword(salt+password).ToArray() Take a look at how to use this function here: https://jasonwatmore.com/post/2020/07/16/aspnet-core-3-hash-and-verify-passwords-with-bcrypt Most importantly: there's no point in using mighty hashing like SHA3 and BCrypt ...


1

In this post let me focus on the project structure. Project vs Projects Most of the time when we implement a n-tier application we separate each tier into its own project. We also separate implementation and abstraction. Some like this: {Project}.Presentation {Project}.Service.Abstractions {Project}.Service {Project}.Repository.Abstractions {Project}....


0

It really depends, how far you want to go with this. Maybe the most common suggestion that I can give is that what you are doing is called Memory Caching. It's good to call things with a name that is widely understood. Read this article about In memory caching in Asp.net core. Just to give you an example, what can be a possible issue with your code. Let's ...


4

Feedback points listed in order that I come across them. Method names The method names are not descriptive. What does InputMethod() do? In this case, ReadInteger() would've been a much better name that explains exactly what it does. Whenever you try to name a method, look at how you would use it. That is to say, don't look at the method body. Explain it to ...


4

I have few tips: Infinite recursion. The app would never finish until you call Environment.Exit because you have infinite recursion. The result of the infinite recursion is always StackOveflowException, sooner or later. Take the trigger: if you forced to use Environment.Exit to stop the app, then something went wrong. About correct usage of the recursion: ...


1

Welcome to CR. While I do appreciate your enthusiasm and willingness to learn, your first attempt here is fairly lacking. To give that a more positive spin, let's say there are plenty of opportunities for improvement. The good news is indentation is very nice. And you use { } for even one-line if statements. The rest is not so good news. Your namespace is ...


3

In this post I'll focus on the PlayerMovment. Before I try to guide you through the OOP related transformations, let me show you a couple of refactoring techniques which will help you to dramatically reduce the complexity of this method. Guard expression vs Early exit Before private void PlayerMovment() { if (choice2.Checked) { for (...) ...


Top 50 recent answers are included