|
If you have the methods available: I'd be using a Dictionary:
public Dictionary<KeyRefID, Func<List<decimal>> KeyRefToFunc;
public List<decimal> GetListById(KeyRefDB oKR)
{
if(KeyRefToFunc == null) throw new ... whatever
if(KeyRefToFunc.ContainsKey(oKR.KeyRefID))
{
return KeyRefToFunc[oKR.KeyRefID]();
}
throw new ... whatever
}
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
This reads as more obscure than Peters solution, possibly because I rarely use dictionary . I will always go for the clearest solution as I will not have to puzzle out the working in the future.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi, MyCroft, When I was first discovering (2006) [^] sticking executable code into Dictionaries, it felt very weird. Now, it's even easier since we have Action, Func, and Lambdas, to get us over the Delegate "syntax hump" that confounds many newcomers to C#. Of course, a Delegate lets you have a params list, and Action, and Func, do not.
Consider:
delegate int Calc(params int[] args);
Dictionary<string, Calc> CalcDict = new Dictionary<string, Calc>
{
{"+", (iary) => iary.Sum()},
{"-", (iary) =>
{
for (var i = 1; i < iary.Length; i++)
{
iary[0] -= iary[i];
}
return iary[0];
}
}
};
From my perspective, this "saves you" writing a 'switch statement, and handles variable length input parameters.
But, trust me ... I'm not trying to "sell" you anything, just adding this for the sake of the discussion.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
using System;
using System.IO;
using System.Collections;
namespace Applica
{
static class Program
{
static void Main(string[] args)
{
bool tif = true;
byte[] buffer = BitConverter.GetBytes(tif);
FileInfo ap = new FileInfo("tempii.txt");
string filePath = ap.FullName;
string destinationPath = Path.Combine("C:\\check", Path.GetFileName(filePath));
using (Stream output = File.OpenWrite(destinationPath))
{
int bits = 32;
while (bits > 0)
{
for (int i = 1; i < 33; i++)
{
if (tif == true)
{
tif = false;
goto A;
}
if (tif == false) tif = true;
A:;
output.Write(buffer, 0, bits);
}
}
}
}
}
}
modified 28-Nov-17 20:21pm.
|
|
|
|
|
|
Oh dear
- The smallest unit of "writable data" is a byte.
- Drop that goto (and please don't use it ever again, for anything). Instead: Toggling a boolean variable is as easy as this:
tif = !tif;
- Doesn't help a lot here though because the change will not reflect in buffer . After you create buffer it keeps its value forever.
- You're using the third parameter of the Stream.Write -method wrongly - at least judging from your described intent. It's supposed to be the amount of bytes from buffer , starting at position 0, that should be written into the file stream. But buffer is only 1 byte long and bits says there should be 32 bytes. That's where you are "outside of the array bounds".
- Your while -loop will run forever because bits will be > 0 forever.
You should start using the debugger. Place a breakpoint at the start of your method (first line or opening brace) by placing the cursor there and pressing F9. Then start your program in debug mode by pressing F5. Then step over the execution line-by-line by pressing F10* while you inspect the values of your variables by hovering with the mouse cursor over it. Compare the values you expect with their actual values and when there's a difference try to find out, why.
* : Take a look at further ways of stepping through your code while debugging: In the Debug-Menu and/or the Debugging-Toolbar (and the Debugger-documentation).
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Reminds me of when I got my first 8088.
Now I use MemoryStream and BinaryWriter.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Sorry, may I ask, why you try to do so?
Do you try to solve HDD performance issue or save flash memory read-write cycles?
Thanks!
|
|
|
|
|
This is my first ever attempt at coding against AD, so bear with me...
Here's what I have:
public static void GetAllUsers()
{
PrincipalContext AD = new PrincipalContext(ContextType.Domain, serverName);
UserPrincipal u = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(u);
foreach (UserPrincipal result in search.FindAll().OrderBy(x => x.DisplayName))
{
if (!string.IsNullOrEmpty(result.DisplayName))
{
Console.WriteLine(result.DisplayName);
}
}
Console.ReadLine();
}
When I run this I get back a list of objects. But what I get back is only a partial list. Some users are there, some are not.
Anyone see what I'm doing wrong?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Are you only getting back the first 256 results?
c# - Can I get more than 1000 records from a PrincipalSearcher? - Stack Overflow[^]
PrincipalSearcher search = new PrincipalSearcher(u);
DirectorySearcher ds = search.GetUnderlyingSearcher() as DirectorySearcher;
if (ds != null) ds.PageSize = 0;
Also, you should really be wrapping the disposable objects in using blocks.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm trying to use only Alphanumeric characters an must use 4. No more or less.
The Code I'm using is below. If I remove the For Loop and can type Alphanumeric values in the textbox but I can seem to type only 4 characters. maxLenght says: cannot convert type in to bool. (Must be 4 characters). I appreciate your help.
public void AlphaNumericString()
{
string s = BacBox.Text;
int maxLenght = 4;
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(s))
{
for (int i = 0; i = maxLenght; i++)
{
BacBox.Text = s;
}
}
else
{
MessageBox.Show("Enter 4 alphanumeric characters only");
}
|
|
|
|
|
The * in that RegEx means "any number of, including 0". It doesn't mean "exactly 4".
To get an exact 4 characters, you would have to use a RegEx pattern of "^[a-zA-Z0-9]{4}$".
You don't need that for loop at all.
As for the rest, I have no idea what this code is supposed to be doing. It's not named properly and doesn't return a value soooooo....
I would probably rename the method
public bool IsValidId(string text)
and have it return a true/false value that indicates if the passed in value is a valid Id number, according to your new RegEx pattern.
System.ItDidntWorkException: Something didn't work as expected.
C# - How to debug code[ ^].
Seriously, go read these articles.
Dave Kreskowiak
|
|
|
|
|
Don't repost the same question over and over again. It just duplicates work and doesn't allow for a collaborated answer.
System.ItDidntWorkException: Something didn't work as expected.
C# - How to debug code[ ^].
Seriously, go read these articles.
Dave Kreskowiak
|
|
|
|
|
A "TextBox" usually has a property to limit input length; and "may" have a mask for alphanumeric.
Depends on Windows Forms, WPF, 3rd party.
Easier than doing it yourself.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
I posted this and got no replies, so I thought I'd bump it and see if anyone can contribute
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Kevin Marois wrote: I thought I'd bump it You've been around long enough to know this is frowned on; your link even goes to a different forum.
|
|
|
|
|
Well that's really silly isn't it?
I've never once bumped a thread. I got no replies so I figured it was overlooked.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Did you ever consider that no one has the answer?
|
|
|
|
|
Yes, I considered that
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Was up against the notorious, apostrophe issue, when sending a command line, which included an apostrophe, to a Database.
So after an enormous amount of Google'ing, I see now that it is recommended procedure to use parameterized commands, to do the trapping for you.
So I did just that.
Rewrote my code with the parameterized commands.
Simply put, my code is designed to read all file names off of a drives root, and enter them into a Database.
As you can see in my code, I store all of the file names into an Array, and then retrieve them one by one using a, FOREACH.
All well and good, and it does work, Line 36,
Console.WriteLine(fi.Name); proves it, but, Line 31,
cmd.Parameters.AddWithValue("@FileName", fi.Name); only grabs the very first filename, and then enters that first filename, as many times into the Database, as there are files on the root directory.
Why is Line 36, the Console Window line working perfectly, reflecting every single filename, but Line 31 only grabs the very first filename, and holds on to it?
static void Main(string[] args)
{
DriveInfo di = new DriveInfo(@"C:\");
string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\\mydbtry.accdb";
OleDbConnection con = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
con.ConnectionString = conString;
con.Open();
DirectoryInfo dirInfo = di.RootDirectory;
FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (FileInfo fi in fileNames)
{
cmd.CommandText = "Insert into Table1 (FileName) Values (@FileName)";
cmd.Parameters.AddWithValue("@FileName", fi.Name);
cmd.Connection = con;
cmd.ExecuteNonQuery();
Console.WriteLine(fi.Name);
}
con.Close();
Console.WriteLine("Finished.");
Console.ReadKey();
}
|
|
|
|
|
You're continuously adding more parameters to the OleDbCommand.Parameters -collection when you only ever need a single one. The first one you add is being used for every command execution.
Store the parameter in a variable, add it to the parameters-collection only once and then modify its value instead in the loop.
Also, I would recommend you to use all your OleDb*-objects that are disposable, in a using-block:
using (OleDbConnection con = new OleDbConnection())
using (OleDbCommand cmd = new OleDbCommand())
{
}
That's the cleanest way to ensure you're not leaking resources. Goes for everything else that implements IDiposable as well, not only database-objects.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Try something like:
cmd.Connection = con;
cmd.CommandText = "Insert into Table1 (FileName) Values (@FileName)";
SqlParameter param = new SqlParameter("@FileName", SqlDbType.NVarChar);
cmd.Parameters.Add(param);
foreach (FileInfo fi in fileNames)
{
param.Value = fi.Name;
if (cmd.ExecuteNonQuery() < 1)
{
}
Console.WriteLine(fi.Name);
}
|
|
|
|
|
Sascha, Richard,
You know, in C# there are at least twenty different ways to achieve the same goal.
And that's why you'll never see two programmers shaking hands in agreeance on the same approach.
Having said that, I want to thank both of you. Although coming from different directions, both of your assistance were correct. Thank you.
|
|
|
|
|
I have an application which displays a treeview based on data contained in a dedicated file.
I would like to get at the same time the name, index, ... of the current clicked treeview item in order to give additional details on click event.
I have been looking in different forums but all I've seen there are somewhat complicated approaches not that easy to adapt to my application.
Has anyone developed a project for this purpose?
Thanks in advance for your replies.
RV
|
|
|
|
|