|
Hi Pete,
It doesn't work for me.
@Html.ValidationMessageFor(s => s.Activation_Date, "Activation Date is invalid");
1. I always have "Activation Date is invalid" visible beneath the activation date input field
2. Secondly, I have other validation error messages in a Validator class for Activation_Date field
RuleFor(x => x.Activation_Date).NotEmpty().WithMessage("Activation Date is required");
RuleFor(x => x.Activation_Date).GreaterThanOrEqualTo(DateTime.Today).WithMessage("Activation Date must be greater than or equal to the current date");
|
|
|
|
|
You appear to be mixing FluentValidation with ASP MVC Validation. I would choose one and stick with that. In this case, FluentValidation is going to be more flexible for you.
|
|
|
|
|
I have this code
public static void Main(string[] args)
{
var dir = @"C:\temp\TestDir";
PrintDirectoryTree(dir, 2, new string[] { "folder3" });
}
public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
{
excludedFolders = excludedFolders ?? new string[0];
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator + Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(directory))
{
Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
if (lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
{
PrintDirectoryTree(d, lvl - 1, excludedFolders, lvlSeperator + " ");
}
}
}
How can I display just the first 10 files in all directories found
|
|
|
|
|
Your requirements are not exact.
First you might want to be sure exactly what you mean by "first". That depends on ordering. And if you don't specify/define the ordering then the OS/apis will provide it in whatever order it wants.
Second it is not clear if you want 10 total files or 10 files per directory. But regardless you are going to need something that keeps count.
|
|
|
|
|
There are several ways to do that: the most basic is to add a count to your loop:
int showCount = 10;
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator + Path.GetFileName(f));
if (--showCount <= 0) break;
}
A better way is to use the array as an Enumerable and only process ten items:
foreach (string f in Directory.GetFiles(directory).Take(10))
{
Console.WriteLine(lvlSeperator + Path.GetFileName(f));
}
But ... the order in which Directory.GetFiles "delivers" files is not defined by the method definition: The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required. So you need first decide what are "the first ten" and sort them according to that decision: name order? Create date? Modification date? Size? Ascending or descending?
We can't make that decision for you: we don't know your app!
You should also be aware that Directory.GetFiles has a number of overloads, one of which allows you to return all files in all subdirectories in a single call: Directory.GetFiles Method Overload 3[^] which may improve your app performance with large directory structures.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
In addition to the other answers, if you don't want all of the files, it would be better to use EnumerateFiles rather than GetFiles .
Directory.EnumerateFiles Method (System.IO) | Microsoft Learn[^]
GetFiles will enumerate all of the files and store the paths in an array, most of which you will throw away. EnumerateFiles uses lazy enumeration, so it will only enumerate the files you want, and won't store any state.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The only problem with that is the lack of sorting on the enumerable - "first 10" requires a sort of some description, or it's just random files that get picked.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Indeed; even the underlying Win32 API doesn't guarantee the order:
The order in which this function returns the file names is dependent on the file system type. With the NTFS file system and CDFS file systems, the names are usually returned in alphabetical order. With FAT file systems, the names are usually returned in the order the files were written to the disk, which may or may not be in alphabetical order. However, as stated previously, these behaviors are not guaranteed.
However, it's probably still more efficient to use some sort of bounded sorted list to store the 10 "first" files based on your chosen sort order as they're enumerated, rather than getting the list of all files, sorting them, and then picking the "first" 10.
Eg, using SortedList<TKey, TValue> , which unfortunately doesn't support an upper-bound on the number of elements:
const int NumberOfFiles = 10;
const int Capacity = NumberOfFiles + 1;
SortedList<string, string> firstFiles = new(Capacity, StringComparer.OrdinalIgnoreCase);
foreach (string filePath in Path.EnumerateFiles(directoryPath))
{
string fileName = Path.GetFileName(filePath);
firstFiles.Add(fileName, filePath);
if (firstFiles.Count == Capacity)
{
firstFiles.RemoveAt(firstFiles.Count - 1);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
NET Framework 4.8 - .NET8 Compatibility
Hello everyone!
I have an old project done in C# using .NET Framework 4.8.
Is it possible to use in this project a dll made later in .NET8?
Thanks for your help.
|
|
|
|
|
It's almost impossible to give a blanket answer to this. It depends on what you have used in there. If you're referencing a .NET package that has no .NET 8 equivalent then, no, you can't use it. You're most likely going to have to do more work to include appropriate NuGet packages for items that you took for granted in the full fat framework.
|
|
|
|
|
I'm trying to load a list of drives. If you went to Windows Explorer and clicked on This PC, you would see all of the drives and devices available to you, physically installed, USB, and phones/tablets. This is the list I want
In addition to my C: hard drive, I have a Lenovo tablet, my Samsung S22 Ultra phone, a USB DVD drive, Seagate USB HDD all plugged in.
So, first I use this to get the HD and DVD drives:
var allDrives = DriveInfo.GetDrives();
First Problem
This gives me the drives, but for the DVD drives the DriveType is showing as 'CDRom'.
Second Problem
I want to get tablets and phones that are plugged in. I found this[^], which works well, with one small problem. Based on that I wrote this bit of code that writes out some of the drive meta data:
I get the ClassId from here[^]. Maybe my class Id is wrong??
public static List GetUSBDevices()
{
var file = @"c:\projects\usbinfo.csv";
if (File.Exists(file))
{
File.Delete(file);
}
var devices = new List();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity"))
{
collection = searcher.Get();
}
using (var sw = new StreamWriter(file, true))
{
var line = "";
var keys = new string[]
{
"Name",
"Description",
"Caption",
"ClassGuid",
};
foreach (var key in keys)
{
line += $"{key},";
}
sw.WriteLine(line);
line = "";
foreach (var device in collection)
{
var name = (string)device.GetPropertyValue("Name");
var classGuid = (string)device.GetPropertyValue("ClassGuid");
if (classGuid == "{eec5ad98-8080-425f-922a-dabf3de3f69a}")
{
foreach (var key in keys)
{
try
{
line += $"{(string)device.GetPropertyValue(key)},";
}
catch { }
}
sw.WriteLine(line);
line = "";
}
}
}
collection.Dispose();
return devices;
}
That produced this
Name,Description,Caption,ClassGuid
One Touch,One Touch HDD ,One Touch,{eec5ad98-8080-425f-922a-dabf3de3f69a}
E:\,STORAGE DEVICE ,E:\,{eec5ad98-8080-425f-922a-dabf3de3f69a}
Galaxy S22 Ultra,SM-S908U,Galaxy S22 Ultra,{eec5ad98-8080-425f-922a-dabf3de3f69a}
Lenovo Tab M10,Lenovo TB-X505F,Lenovo Tab M10,{eec5ad98-8080-425f-922a-dabf3de3f69a}
Note the last two, the Galaxy S22 Ultra and Lenovo Tab M10 - these I want. The first two are HDD's, which I already have from GetDriveInfo().
So, to recap
1. With GetDriveInfo, how do I know if a drive that says CDRom is really a DVDRom?
2. Is there some way to get just the tablets & phones?
I'm open to a better way of someone has one.
Thanks!
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
Kevin Marois wrote: With GetDriveInfo, how do I know if a drive that says CDRom is really a DVDRom?
You can't. GetDriveInfo relies on a Win32 API, and the DriveType enum is mapped to the Win32 drive types, which haven't been updated to include DVD/Blu-Ray types.
DRIVE_UNKNOWN
The drive type cannot be determined.
DRIVE_NO_ROOT_DIR
The root path is invalid; for example, there is no volume mounted at the specified path.
DRIVE_REMOVABLE
The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader.
DRIVE_FIXED
The drive has fixed media; for example, a hard disk drive or flash drive.
DRIVE_REMOTE
The drive is a remote (network) drive.
DRIVE_CDROM
The drive is a CD-ROM drive.
DRIVE_RAMDISK
The drive is a RAM disk.
There is an extended list of disk types defined in the IMAPI2 library:
IMAPI_MEDIA_PHYSICAL_TYPE (imapi2.h) - Win32 apps | Microsoft Learn[^]
You may be able to reference and use that library, as described in this SO answer[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Great thanks. I'll take a look
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
Hi All,...
I am reading into a rich text box a small number (0.385 to 0.457) which is read into a Rich Text Box as a string
and my though was to use Text.ConvertTo(float) in the following way
Value_Extract = ((Convert.ToDecimal(rtbIncoming.Text));
Value_Extract is a float...
This does not work compiles and Bang falls over when run, had look on Stack Overflow they seem to do in a similar way. Is this the correct way?? As VS helpfully tells me I need to cast a float as a decimal, decimal.tryparse??
modified 3-Jan-24 8:25am.
|
|
|
|
|
I typically use float.TryParse(string, out float result); This returns true if successful and false if not.
HTH
Jack of all trades, master of none, though often times better than master of one.
|
|
|
|
|
Hi,
Thanks for that float.TryParse(), will I be able to get out as a floating point?..
|
|
|
|
|
Yes:
if (float.TryParse(myTextBox.Text, out float result))
{
Console.WriteLine(result);
}
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Are you sure it compiles? String doesn't have a ConvertTo method, and you can't pass the Decimal type as an argument like that.
Assuming the text is a valid number, then Convert.ToSingle(rtdData.Text) should give you a float back. Or Convert.ToDecimal(rtdData.Text) would give you a decimal , which you would then have to cast to store in a float variable.
But these methods will throw an exception if the text is not a valid number. It would be better to use float.TryParse / decimal.TryParse so that you can notify the user if the value can't be parsed.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Okay, I will give that a go...
It hasn't crashed yet!!
modified 3-Jan-24 9:04am.
|
|
|
|
|
I notice that VS Intellisense wants to tag every LINQ query I code with ".ToList()".
It is in fact an extra step that imposes unnecessary overhead when all you need is an IEnumerable in the chain. It just gets worse as the "frame rate" increases. While List<> is prefered "internally", it doesn't pay to be reflex "converting" when it isn't necessary. (IMO)
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
It doesn't "want" to append it. It's just that the "AI" has seen it so much in all of the code in its training repositories that it thinks that's what is most likely to come next.
|
|
|
|
|
I doesn't "want" to but can't help itself? Caught up in the herd mentality? And that makes it "OK"?
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
An AI in only as good as the training set it's taught with, so yeah, you could say it's following the heard.
I never said that makes it "OK". All I said is what it's doing.
|
|
|
|
|
lol. Yep.
I have certainly seen developers do that. They can't figure out how to do it in the initial clause so they end up processing it in memory.
Definitely not a good thing for working with a database.
Sigh...unfortunately I have also seen this happen implicitly by the library. I can see it by profiling in SQL Server while running a linq expression. That makes everything horribly wrong. It means I have no way to verify except by profiling everything.
I have seen all of the following by profiling.
- It dragged the entire table into the app space and then applied the clauses.
- It did an in clause by doing a while loop over each in parameter. So 200 separate SQL calls.
- It did a join by doing a different SQL call for each table and then joining in memory.
None of the above makes me want to ever use linq again.
|
|
|
|
|
Just use your best judgement as always. Intellisense helps you type faster (some of the time), but it's no substitute for intelligence.
ToList'ing everything all the time is obviously silly.
|
|
|
|
|