Nacho Man Randy Cabbage
User built queries on objects
I'm looking at an old app that allows users to build queries to retrieve objects in a list that match that query. It is only querying off a single property on the objects: a
Dictionary<string, string>
. Each object's dictionary property will always have the same keys.
In the current code, it is a massive mess of nested if/else statements.
The flow goes like this:
1. User selects key from the dictionary's keys
2. User selects operator (greater than, less than, equals, IN, contains, etc.) (there is an if/else statement for each of these)
3. User enters a single value
4. User can then decide to AND or OR it with another query, where the process repeats (if/else every time an AND / OR is seen)
What is a better way to structure all this? Is there a specific pattern I can use?1 replies
Winforms - cursor doesn't stay as "WaitCursor" in long running async method
I have an async button click that awaits some long running file i/o stuff. I noticed that for REALLY long i/o stuff (like reading massive files), the wait cursor and controls don't change before hitting that await like in the first two lines of the function below. For smaller files they change without issue. I don't understand why that would matter but that's what is happening.
If I wrap
Importer.ImportFile(item)
in a Task.Run, then it seems to work. Not sure why or if that is the right solution.4 replies
How does .Contains work inside of a .All()?
I'm looking at a piece of code that is:
return parts.All(format.Contains);
parts
is a ReadOnlyCollection<string> and format
is a string.
How is .Contains
in there without the ()? Isn't it a call itself?9 replies
Proper way to constantly log to file
I am working on an app that will need a lot of logging. It's a completely offline system and the user wants all the logs to a file.
What is the best way to handle this so that:
1. All the logs are written in the order that they are called
2. It won't freeze the app waiting for any of the writing to complete
At first I tried just making every log call a fire and forget task, but I noticed some logs would be out of order.
There can be hundreds of log calls every few seconds so I can't make it synchronous because it freezes the UI (WPF if that matters). Any tips or suggestions would be great.
17 replies
Binding DataGrid to DataTable. DataGrid's ItemSource is null on first load. - WPF
I'm trying to bind a DataGrid to a DataTable located in my viewmodel. The columns are dynamic hence why I'm binding to a DataTable and adding the columns and rows in the viewmodel. The relevant VM code looks like:
Now the viewmodel is created before the view, and the view's datacontext is set to the viewmodel when the view is created.
The xaml for the DataGrid is:
There are certain columns I need to hide based on a list of strings in the VM. So I checked in both the View's Loaded event and the DataGrid's Loaded event, and in both cases the ItemSource is null, so I can't access the columns to hide them. Why would it be null if it is bound to the DataTable in the vm?
5 replies
Binding Dictionary to DataGrid (WPF)
I have multiple lists of objects of the same type that contain a dictionary property and I want to bind a datagrid column header to the key, and the cell values to the dictionary's value. Example of the object:
public class MyObject
{
public Dictionary<string, string> Data { get; } // key would be a column header, value would be cell value
}
Now, in each list, the keys themselves will remain the same for each object's dictionary, but could change between lists, so I can't have static column headers. There is no editing in the grid, although I am gonna allow the hiding of columns and filtering.
Not sure the best way to go about this. If it was static keys I could just create an object to represent the data in the dictionary and make an observable collection of that.3 replies
WPF: Bind to each value of a property generated via reflection in ObservableCollection
I have a large list of objects, we'll call the object SpecialData, with ~60 properties on it. I created a class to represent each property in the UI like so (using MVVM toolkit hence the attributes):
In my viewmodel, I get all the attributes of the
SpecialData
class and map them to a collection of CheckableProperty objects like so:
Now in the UI, I want to show each property and its corresponding value for whatever my selected item is in the list of SpecialData
objects. Right now I am doing this every time I select a different item to show the properties of:
11 replies
Design for letting user select properties to write to a CSV file
I have a list of objects where the object type has about 60 properties. The user wants to be able to export this list to a CSV file with only the properties they choose. I'm trying to think of a better design than just a huge if/else statement (bound to a checkbox for each property that the user can check/uncheck) and building each line.
Open to any ideas 🙂
9 replies
Best container for ~1 million objects
What would be the best container choice for ~1 million objects? The objects would be in order, but I would need the ability to jump to any random object quickly (which makes me think dictionary). But at some point I'd need to add in filtering/search based on the properties in these objects. performance is the main concern.
The idea is the user can view the details (properties) of one object a a time, and use a prev/next/jumpto control to go between them. But eventually they want to export these objects after a filtering is applied.
26 replies
How to check if a file is locked by another process and keep checking for specified amount of time?
I am trying to create a simple way for apps to check if a file is locked by another process before locking it themselves and reading/writing to it.
what is the simplest way to achieve this? Some nice-to-haves:
- See the name of the process that is locking it
- See how long the file has been locked for (is this possible?)
- Specify an amount of time/number of tries to check the lock
I've seen mentions of creating a separate file that can act as a "lock" file, i.e. if it exists it means the original file is locked, and having the process doing the locking delete the lock file when it's finished. This seems overly complicated. In my head it should be as simple as just having a using statement on a filestream with FileShare set to None. If it doesn't throw an exception, then it is not locked. But I guess if I want to see how long a file has been locked for then I might need to write that information somewhere (like the "lock" file).
Any tips would be greatly appreciated
7 replies
Making copies of image files and removing all metadata
I have an app that lets users load in jpg, png, tif, gif, and bmp files. I want to be able to make copies of these while removing the metadata in the copies. I'm not sure of the proper way to do this. They are currently loaded in WPF like so:
BitmapImage newImage = new BitmapImage();
using (FileStream stream = File.OpenRead(filePath))
{
newImage .BeginInit();
newImage .StreamSource = stream;
newImage .CacheOption = BitmapCacheOption.OnLoad;
newImage .EndInit();
}
Would it make sense to do a System.IO.File.Copy on each file, and then loop through and remove all the metadata on the copies? or is there a way to do it when the copy is initially created?
If I do the following, it removes all metadata. However, the file size and vertical/horizontal resolution are different in the copy, and gifs are no longer animated.
using (var originalImage = Image.FromFile(filePath))
{
using (Bitmap copyBitmap = new Bitmap(originalImage))
{
// Draw the original image onto the new bitmap
using (Graphics graphics = Graphics.FromImage(copyBitmap))
{
graphics.DrawImage(originalImage, new Rectangle(0, 0, copyBitmap.Width, copyBitmap.Height));
}
// Save the copy without metadata
copyBitmap.Save(outputFileName);
}
}
1 replies
Error when trying to write an attribute string using XmlWriter
I am trying to write an attribute string like so:
string kmlUrl = "http://www.opengis.net/kml/2.2";
using (XmlWriter writer = XmlWriter.Create(filePath, settings))
{
await writer.WriteStartDocumentAsync();
writer.WriteStartElement("kml");
writer.WriteAttributeString("xmlns", $"{kmlUrl}"); // error here
// rest of stuff
}
The element should look like this:
<kml xmlns="http://www.opengis.net/kml/2.2">
However, I get the following error:
"The prefix '' cannot be redefined from '' to 'http://www.opengis.net/kml/2.2' within the same start element tag."
I'm confused why this is happening, because I do the same exact thing with other elements down the line without issue.2 replies
❔ Cannot find .dll in referenced project
I have a class library targetting .NET Standard 2.0. This library references two nuget packages: NETStandard.Library (2.0.3) and NetTopologySuite.IO.Esri.Shapefile (1.0.0).
The class library builds fine.
I then have a console app project in the same solution that targets .NET Framework 4.8.1. This project references the class library project. The console ap builds without warnings or errors. However, when running the app, as soon as I hit the first line that references the class library, I get the following error:
"Exception thrown: 'System.IO.FileNotFoundException' in NetFrameworkTestApp.exe
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in NetFrameworkTestApp.exe
Could not load file or assembly 'NetTopologySuite.Features, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f580a05016ebada1' or one of its dependencies. The system cannot find the file specified."
Looking in the bin folder of the console app, I see the class library dll but not the two nuget packages' dlls. The dlls do exist in the bin of the class library. What am I missing here?
31 replies
❔ How to get substring up until a certain pattern is seen?
I have a bunch of strings that look similar to:
"TEST1_TEST_1995_12_324324_whatever"
"test2_test_3_4_2001_test"
What I am trying to do is get a substring up to but not including the underscore just before 4 digits in a row plus another underscore. In the above two examples, the first substring should give me "TEST1_TEST" because after that is the pattern underscore, four digits, underscore (1995).
The second example should give me "test2_test_3_4" because the pattern after that is, again, underscore, four digits, underscore (2001).
I've been messing around with regex but can't seem to get close.
13 replies
❔ System.IO.FileLoadException for Microsoft.SqlServer.Types
I am working on an old project (.net 4.8) and updating the dependencies. One of these is
Microsoft.SqlServer.Types.dll
. The original version was 10.50.2500.0
. I removed this and VS suggested a nuget package, so I added that to the project which gives me version 16.0.1000.6
. However, I get the following error when running the application now:
System.IO.FileLoadException: 'Could not load file or assembly 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'
This occurs when I call the Fill(DataTable dataTable
function of DbDataAdapter
. I assume the issue will pop up in other places using data adapters. I checked the .csproj file and .config file and don't see any references to the 10.0.0.0
version, so why is it still trying to load that version? How can I fix this?7 replies
❔ Filing empty list with equal items left and right of selected item from another list
Given a list and selected index of an item in that list, I want to fill another list such that items will try to be inserted, in order, to the left and right of that selected item without going past a given max count for the new list. A little confusing, but here's an example:
I have a list with the following strings
This is what I have so far, and it's fine and works, but I'm not sure if there's a more efficient way or using less for loops and if statements.
{ "red", "blue", "green", "yellow", "black", "brown" }
. I am given the index 3
which corresponds to the element yellow
in the list. I want to populate a new list that, given a max of 5, looks like the following:
{ "blue", "green", "yellow", "black", "brown" }
So essentially I try to keep the original selected item in the middle of a new list and insert items from the original list to the left and right until I hit the max. If there's not enough elements to reach the max then it's fine if it's not in the middle.This is what I have so far, and it's fine and works, but I'm not sure if there's a more efficient way or using less for loops and if statements.
int idx = originalList.IndexOf(selectedItem);
int count = 1;
newList.Add(selectedItem); // first add the selecteditem to the new list
// first try to get two elements before the selected item
int lastBeforeIndx = idx;
for (int i = idx - 1; i >= 0; i--)
{
if (count == 3)
{
break;
}
newList.Insert(0, originalList[i]);
lastBeforeIndx = i;
count++;
}
// then try to get 2 elements to the right of the selected item
for (int i = idx + 1; i <= originalList.Count; i++)
{
if (count == 5)
{
break;
}
newList.Add(originalList[i]);
count++;
}
// all finished. Only want to show five at a time in this example
if (count == 5)
{
return;
}
// if not at 5, try adding to the left again
for (int i = lastBeforeIndx - 1; i >= 0; i--)
{
if (count == 5)
{
break;
}
newList.Insert(0, originalList[i]);
count++;
}
10 replies
❔ Can't build wpf project. "TestClassifier_w04izrw3_wpftmp.csproj" -- FAILED.
I'm trying to build a WPF project and I keep seeing the build error:
Done building project "TestClassifier_w04izrw3_wpftmp.csproj" -- FAILED.
I don't know what this file is but I saw multiple copies of it in the obj
folder. TestClassifier
is the name of the project. Not much in the real csproj folder:
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<ApplicationIcon>Resources\Test_Classifier_Icon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Has anyone seen this before? Some searches seem to point towards something with nuget but I'm not using any nuget packages in this project2 replies