|
You could use a delegate in .NET 2.0 or a Lambda expression if you're using .NET 3.5.
|
|
|
|
|
Hi folks! I've coded myself into another corner... again! I need a guru.
This time, I'm writing code that checks that the parameter list for a call to a method is valid. Why? Because I am dynamically calling various methods with parameters read from an XML file. Why? Don't ask... looooong story.
Breifly, a call to my routine might look like
StandardTest.PerformDALvsDBTest(
"DALRoutines",
"InsertCustomer",
new object[] {
DateTime.Parse(parm0),
parm1,
Int32.Parse(parm2)
}
);
Okay. So my routine goes through a bunch of checks and finally obtains a reference to the method to be called (MethodInfo.methodRef ). The call to the method will be made using
methodRef.Invoke(null, myBindings, null, Params, null);
But first, I must make sure that all the items in the object[] Params are of the right type. To do that I loop through methodRef.GetParameters() and check each one against each Params[index].GetType() .
If there are the correct number of parameters, and they are all of the correct type, etc, then I will perform the Invoke() , otherwise, I throw an error indicating the method name, the parameter, the expected type and the type that was used:
e.g. "The System.Type for parameter #0 in the parameter list for the method [DALRoutines.InsertCustomer] is System.DateTime; System.TimeSpan was expected".
So, here is my problem:
I have a method that expects a parameter to be an Int32 . However, when the value is passed in the object[] Params , it seems to be changed to Int16 (even if I specifically indicate that it is Int32 as above - I assume that it is because it is a small value). When my routine starts comparing parameter types it spits out an error saying it was passed an Int16 when it expects an Int32 . The kicker is that the call to Invoke() would still work if it was made - .NET does not seem to mind and handles the conversion inherently. But I can't find a way to tell that it would work - all I can see is that the two types are different.
I have tried investigating different ways to tell if the types are compatible (including Type.IsSubclassOf() and Type.IsAssignableFrom() ) but I can't seem to find anything that will let me know that an Int16 can be used as the value for an Int32 parameter.
Does anyone know a way to do this?
Clive Pottinger
Victoria, BC
|
|
|
|
|
You could always try to perform a cast on it. It's not the most efficient method, but I figure that's not what you're worried about - what with the reflection and all.
|
|
|
|
|
Would something like this be okay?
public static bool ImplicitCastAllowed(Type type, object value)
{
try
{
Convert.ChangeType(value, type);
return true;
}
catch
{
return false;
}
}
regards
modified 12-Sep-18 21:01pm.
|
|
|
|
|
Thanks guys - but I found the cause of the problem... P.E.B.K.A.C.!
I was actually rewriting the routine to use Convert() (thanks Greeeg), when I noticed that I my error message was printing out the wrong info - instead of saying that the parm was "of type passedParmType; requiredParmType was expected", it said it was of "type requiredParmType; passedParmType was expected"!
That led to finding other places where I had mixed up the two references (due to an ambiguous naming convention). Once I fixed that I found that my code was actually working correctly and warning me that I was trying to use an Int32 as a value to an Int16 parameter.
Perhaps I should consider a change of career. I hear that Air Traffic Control is less stressful... and apparently the FAA is much more lenient about minor errors than IT managers.
Clive Pottinger
Victoria, BC
|
|
|
|
|
I have managed to customize the error message if a valid integer is not input for the propertyGrid field. But how can i display the old values (whatever was entered) because after putting an invalid Integer i see "0" in the propertyGrid field. I guess it's because i am sending a null.
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
object obj = null;
try
{
obj = base.ConvertFrom(context, culture, value);
}
catch (Exception e)
{
if (_hasShownErrorMsg==false)
{
_hasShownErrorMsg = true;
MessageBox.Show("not a valid number.");
}
}
_hasShownErrorMsg = false;
return obj;
}
|
|
|
|
|
after validating a value, store it somewhere:
try
{
obj = base.ConvertFrom(context, culture, value);
lastValidValue = value;
}
...
then then next time around if the call to base.ConvertFrom throws an exception you can restore to lastValidValue
|
|
|
|
|
hello friends,
how can i make a simple, soft and nice brush like that is in the microsoft paint?
My solution was to draw consecutive circles in my mouse drag event and add them to the array list and then repaint all circles in the array list. but some of the events of mouse drag are missed and this make my brush dotted. i want to know how can i make it more smooth. please guide me.
thanks
modified on Wednesday, September 17, 2008 1:41 PM
|
|
|
|
|
Sajjad Izadi wrote: My solution was to draw consecutive circles in my mouse drag event and add them to the array list and then repaint all circles in the array list.
Seems you will also need to join the circles to get an smooth effect.
Regards,
Syed Mehroz Alam
|
|
|
|
|
yes yes, that's it. but the way to solve...?
|
|
|
|
|
your in the wrong forum, try graphics
Harvey Saayman - South Africa
Junior Developer
.Net, C#, SQL
you.suck = (you.Passion != Programming & you.Occupation == jobTitles.Programmer)
1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111
|
|
|
|
|
Harvey Saayman wrote: 1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111
Yes, it does. But you spelled "I'm" as "im"...
44 6F 20 79 6F 75 20 72 65 61 64 20 68 65 78 20 61 6C 73 6F 3F
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
Guffa wrote: 44 6F 20 79 6F 75 20 72 65 61 64 20 68 65 78 20 61 6C 73 6F 3F
apparently i can octal too if i really have to
Harvey Saayman - South Africa
Junior Developer
.Net, C#, SQL
you.suck = (you.Passion != Programming & you.Occupation == jobTitles.Programmer)
1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111
|
|
|
|
|
i have a string that always is 6 chars long. If it is not then zeros are added to it. I am pullinging this info out of the database and i need to add 1 to it.
Example:
I get "000456" and need to add 1 to it so its "000457"
Is there an easy way to do that?
|
|
|
|
|
Yes, try this:
string s = "000456";
int i = -1;
if (Int32.TryParse(s, out i))
{
i +=1;
s = String.Format("{0:000000}", i);
} This takes your string and tries to convert it to an integer value. If that succeeds, it adds 1 to it and then formats it back as a string to 6 characters padded with zeroes.
Scott Dorman Microsoft® MVP - Visual C# | MCPD
President - Tampa Bay IASA
[ Blog][ Articles][ Forum Guidelines] Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai
|
|
|
|
|
Another way:
<br />
int Intvalue = Convert.ToInt32("000456") + 1;<br />
string Stringvalue = Intvalue.ToString("000000");
I Love T-SQL
"Don't torture yourself,let the life to do it for you."
If my post helps you kindly save my time by voting my post.
|
|
|
|
|
What is your approach to software design?
Do you have meetings?
Write Design Documents?
Something else?
I'm really curious to find out what others find effective in a team development environment?
|
|
|
|
|
Usually a combination of meetings, design documents, whiteboard sessions, and prototyping.
Scott Dorman Microsoft® MVP - Visual C# | MCPD
President - Tampa Bay IASA
[ Blog][ Articles][ Forum Guidelines] Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai
|
|
|
|
|
If I design it... I do it pretty much like a school project, I take the general requirements and design as I go.
If others design it, there'd better be a specification, but...
All too often the time spent writing up a design spec is completely wasted.
I can think of only four times I was given a design spec:
1) The spec concerned changes to an existed program -- I did a complete re-write instead.
2) It was rubbish, there were severe security issues -- I implemented something else entirely.
3&4) The business needs (and personnel) had changed a great deal after the design was created.
|
|
|
|
|
I always make sure that i use pencil and eraser.
|
|
|
|
|
This isn't really a C# question. You should really have posted it in something like the General Discussions forum or possibly even the Lounge, but since you asked:
JPWheeler wrote: Do you have meetings?
Yes - how else does the client tell you their requirements?
JPWheeler wrote: Write Design Documents?
Yes - how else do you ensure that you're writing what you're supposed to?
JPWheeler wrote: Something else?
Acceptance documentation? How else do you and the client ensure you're delivering what you're supposed to.
More importantly, we use TDD and are investigating MDD, possibly even BDD.
|
|
|
|
|
Hi,
I want to monitor the health of a process on a Windows computer (XP, Server 2003) using WMI, and for this I want to get it's processor usage in percent (same as process listed in the Task Manager with CPU percentage) with using C# (> 2.0).
I tried naively to use the Win32_PerfFormattedData_PerfOS_Processor classes using the PercentProcessorTime property but this gives me only 0% or 100% values.
I red on forums that a calculation must be done to get the correct percentage and found this VB script below (http://msdn.microsoft.com/en-us/library/aa394597(VS.85).aspx).
I tried to apply this code into the following C# code with the help of some article of The Code Project, but without success as I have strange values out for the Timestamp_Sys100NS property (null, big numbers that give wrong calculation).
Many thanks for your help.
VB scrip code :
Set object1 = objWMIService.Get( _
"Win32_PerfRawData_PerfOS_Processor.Name='_Total'")
N1 = object1.PercentProcessorTime
D1 = object1.TimeStamp_Sys100NS
Wscript.Sleep(1000)
set object2 = objWMIService.Get( _
"Win32_PerfRawData_PerfOS_Processor.Name='_Total'")
N2 = object2.PercentProcessorTime
D2 = object2.TimeStamp_Sys100NS
' CounterType - PERF_100NSEC_TIMER_INV
' Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
PercentProcessorTime = (1 - ((N2 - N1)/(D2-D1)))*100
C# code :
mgmtScope = new ManagementScope("\\\\" + hostName + "\\root\\cimv2");
try {
mgmtScope.Connect();
}
...
string searchQuery = "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process WHERE Name = 'MyProcess'";
ObjectQuery oq = new ObjectQuery(searchQuery);
ManagementObjectSearcher query = new ManagementObjectSearcher(mgmtScope, oq);
try {
ManagementObjectCollection servicesCollection = query.Get();
foreach (ManagementObject service in servicesCollection) { // seems not possible to do servicesCollection[0]
percentProcessorTime = double.Parse(service.Properties["PercentProcessorTime"].Value.ToString());
}
}
...
string searchQuery = "SELECT * FROM Win32_PerfRawData_PerfOS_Processor WHERE Name = 'MyProcess'";
ObjectQuery oq = new ObjectQuery(searchQuery);
ManagementObjectSearcher query = new ManagementObjectSearcher(mgmtScope, oq);
try {
ManagementObjectCollection servicesCollection = query.Get();
foreach (ManagementObject service in servicesCollection) {
timeStampSysNS100 = double.Parse(service.Properties["Timestamp_Sys100NS"].Value.ToString());
}
}
...
double d1 = this.getPercentProcessorTime();
double n1 = this.getTimeStampSysNS100();
Thread.Sleep(1000);
double d2 = this.getPercentProcessorTime();
double n2 = this.getTimeStampSysNS100();
double percentPT = (1 - ((n2 - n1) / (d2 - d1))) * 100;
string res = "Process CPU usage : " + percentPT;
|
|
|
|
|
I won't claim to know anything about this, but
based on the docs, I tried this (in a C# console app):
for (int i = 0; i < 100; i++)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfProc_Process WHERE Name = 'MFCTester'");
ManagementObjectCollection.ManagementObjectEnumerator enumerator = searcher.Get().GetEnumerator();
if (enumerator.MoveNext())
{
Console.WriteLine("MFCTester PercentProcessorTime: {0}", enumerator.Current["PercentProcessorTime"].ToString());
}
Thread.Sleep(100);
}
Seems to give the same results as the system monitor.
Notes:
My 'MFCTester' app is single threaded.
I forced CPU use by dragging it around the screen rapidly.
It looks like the result is the percentage of one processor - if I
divide the displayed percentages by 4 (the number of processors on my
system) I get the same values as the CPU column of the task manager.
Mark Salsbery
Microsoft MVP - Visual C++
|
|
|
|
|
Mark Salsbery wrote: divide the displayed percentages by 4 (the number of processors on my
system)
Show off
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Expect everything to be hard and then enjoy the things that come easy. (code-frog)
|
|
|
|
|
Well...two physical
Mark Salsbery
Microsoft MVP - Visual C++
|
|
|
|