|
Oh, you're right that's a stackoverflow. Well, I guess you need to check your data. And look at the control, it should handle it better IMO.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
My program request data over the internet, I need to request this data back to back using the same array and changing the data within it (basically the handle). When I get the data coming from the internet I have already removed the handle from my array and cleared the info from the program through which I requested it. I found the following code (see below) in the help files for delaying the request until I receive the first request. But this does not work either, was this designed for use over the internet or just on the local computer. How can I have my request delayed until I have received all data.
Thanks in advance,
Michael
// Timer
The Elapsed event is raised on a ThreadPool thread, so the event-handling
method might run on one thread at the same time that a call to the Stop
method runs on another thread. This might result in the Elapsed event being
raised after the Stop method is called. The code example for this topic shows
one way to prevent the race condition.
Example
The following code example shows one way to prevent the thread that calls the
Stop method from continuing until a currently executing Elapsed event ends,
and also to prevent two Elapsed events from executing the event handler at the
same time (often referred to as reentrancy).
The example executes 100 test runs. Each time the test is run, the timer is
started with an interval of 150 milliseconds. The event handler uses the
Thread.Sleep method to simulate a task that randomly varies in length from 50
to 200 milliseconds. The test method also starts a control thread that waits
for a second and then stops the timer. If an event is being handled when the
control thread stops the timer, the control thread must wait until the event
is finished before proceeding.
The Interlocked.CompareExchange(Int32,Int32,Int32) method overload is used to
avoid reentrancy and to prevent the control thread from continuing until an
executing event ends. The event handler uses the CompareExchange(Int32,Int32,
Int32) method to set a control variable to 1, but only if the value is
currently zero. This is an atomic operation. If the return value is zero, the
control variable has been set to 1 and the event handler proceeds. If the
return value is non-zero, the event is simply discarded to avoid reentrancy.
(If it were necessary to execute every event, the Monitor class would be a
better way to synchronize the events.) When the event handler ends, it sets
the control variable back to zero. The example records the total number of
events that executed, that were discarded because of reentrancy, and that
occurred after the Stop method was called.
The control thread uses the CompareExchange(Int32,Int32,Int32) method to set
the control variable to -1 (minus one), but only if the value is currently
zero. If the atomic operation returns non-zero, an event is currently
executing. The control thread waits and tries again. The example records the
number of times the control thread had to wait for an event to finish.
[MTAThread]
public static void Main()
{
Timer1.Elapsed += new ElapsedEventHandler(Timer1_ElapsedEventHandler);
Timer1.Interval = timerInterval;
Console.WriteLine();
for(int i = 1; i <= testRuns; i++)
{
TestRun();
Console.Write("\rTest {0}/{1} ", i, testRuns);
}
Console.WriteLine("{0} test runs completed.", testRuns);
Console.WriteLine("{0} events were raised.", numEvents);
Console.WriteLine("{0} events executed.", numExecuted);
Console.WriteLine("{0} events were skipped for concurrency.", numSkipped);
Console.WriteLine("{0} events were skipped because they were late.", numLate);
Console.WriteLine("Control thread waited {0} times for an event to complete.", numWaits);
}
public static void TestRun()
{
// Set syncPoint to zero before starting the test
// run.
syncPoint = 0;
Timer1.Enabled = true;
// Start the control thread that shuts off the timer.
Thread t = new Thread(ControlThreadProc);
t.Start();
// Wait until the control thread is done before proceeding.
// This keeps the test runs from overlapping.
t.Join();
}
|
|
|
|
|
Hi everybody,
I have a simple application with a couple of dlls and an OCX.
I have created a standard installer, which works fine under administrator priviledges.
Problem is, when running under a "limited user account" (windows xp), i get a System.Security.SecurityException.
Do not understand why and all i get is a standard windows error reporting screen. it is not possible to install Visual studio on the machine i am testing on.
any ideas?
i have tried setting the register property of each of the Dlls to "COM", the OCX defaults to "COMSelfReg".
your thoughts and comments and much appreciated,
many thanks
Jonathan Harker
|
|
|
|
|
I suspect the limited user is not allowed to register the dll.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
just to note also on the machine i am testing, i am using an administrator account to actually perform the installation. then i am attempting to run on the limited account
thanks again
Jonathan Harker
|
|
|
|
|
If you could only get a hold on the "System" user account you'd be all set
To Christian:
LOL @ you still using that as your sig! ROFL
Christian Graus FTW!
It needs a link to the original post though
|
|
|
|
|
Hi all,
thanks a lot for your posts.
Just to let you know that the issue wasnt with the installer, but actually when the program was attempting to access the registry on load.
was getting Security.SecurityException because my program was attempting to access the "LocalMachine [HKLM]" Key. A quick change to "CurrentUser" resolved the issue.
Thanks windows error reporting [not]. actually took quite a few [several] hours to work this out
Thanks again guys
Jonathan Harker
|
|
|
|
|
jharker1987 wrote: was getting Security.SecurityException because my program was attempting to access the "LocalMachine [HKLM]" Key
jharker1987 wrote: hanks windows error reporting [not]. actually took quite a few [several] hours to work this out
One could also say the time it took you to find the reason resulted from poor error handling...
A simple try/catch around your registry accessing code would have done the trick.
Regards,
mav
--
Black holes are the places where God divided by 0...
|
|
|
|
|
Being a person who's never needed a listview until now (crappy open file dialog in windows mobile!!!!)
What is the best option of interacting with a listview that uses .CheckBoxes=true; list view showing files (this is in Windows Mobile 6)
This listbox is one that shows a list of offline created files and allows the user to select the ones they wish to upload to their web database.
1) Add an event for when as each item is checked, add it to a dictionary collection so you have an updated view at all times.
2) Let the user check away all the items to their hearts desire, then loop though the itemcollection searching/processing each one that has the property checked=true
3) Use delegates to point to diffrent functions in the procrssing script based if the list is long or short. If the number of files in the DirectoryInfo.GetFiles() is long add the "check" event handler else pint it to a loop though function.
4) Some other strategy
To me option one is attractive if there will be LOTs of options to select or if I needed to dynamically edit look at the contencts they have selected. (which I don't)
I think option two would make the UI interaction faster, but the processing longer as it looks though EVERY option in the list. Which would make it better if the list was always small.
The third option sure is "enterpriseish" but most likly be a waste of time to code :/
As to how many offline files the user will have? Beats me I wouldn't think "too" many... The thing is you never know with end users... They might save a years worth of data to upload "at once" for all I know/expect heh... (thus there is a max MB upload)
|
|
|
|
|
Hello everyone,
I'm building a modular application that dynamically loads assemblies from a predefined folder. These assemblies are modules that the application runs using an interface to access each module.
The main idea is a timer launches all modules that do some work.
The module interface defines an event which fires when the module is done working. The host application, prior to launching module's StartWork() method, registers a handler for the OnModuleDoneWorking event. Then it launches the module in a separate thread.
When the OnModuleDoneWorking event is fired, the host application collects the data from the module (which is passed as the sender object).
Here my problem begins, i need to know when all modules are done working so i can compile all of their data into a single report and send it.
I thought about starting another timer to monitor the status of all modules. Or maybe each time an OnModuleDoneWorking event is fired i can check the status of all modules, but this will be happening on the module 's thread and i don't want to launch the report method from a module thread.
I can also set a loop in the module launching method (the host timer event) but that will hold the main thread and a misbehaving module could mess everything up (this is a really ugly way to handle this).
If anyone has any ideas i'd be happy to hear.
thanks,
darthBug
Join the dark side of the code
|
|
|
|
|
Hi,
there are many ways to do this. Here is one, maybe not optimal:
- have a single variable "runningModules" that gets incremented each time a module gets
started, and gets decremented each time a module finishes (have a look at Interlocked class);
- have a Windows.Forms.Timer that periodically watches the runningModules variable,
and starts the summary reporter when it reaches zero.
You can replace the periodic timer by an event mechanism that gets fired when the
counter decrements to zero. That takes some more code, but gives a cleaner design
Potential problem: a module might crash or hang, preventing the runningModules variable
from ever reaching zero.
Here is another one:
- have a collection of running modules; add to them on start, remove on dome;
- periodically inspect the collection; when empty report; when taking too long, try
to figure out if the module is still alive (you could add something akin an heartbeat
monitor in every module).
Warning: to be thread-safe, you should lock the collection when modifying it.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Nice answer. The only thing I think I could do differently in the first option is use an AutomaticResetEvent or a ManualResetEvent to specify a drop dead time, that way you can track which modules didn't complete as well as not worry about the decrement variable not reaching zero. And definitely use the Interlocked class. The second option would probably be more reliable. IMHO.
Scott P
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
Thanks guys, sound like really good ideas to try.
Scott, i read about the AutoResetEvent and ManualResetEvent but i don't understand what it does and how to use it in my case. Could you please give an example?
How does the event thing works in this case:
The host creates a new thread for the StartWork() method of the module class.
At the end of the method it fires an event which is handled by the host.
Now in this case as i understand the event handler is run in the module thread, am i correct?
What i thought about is to go with the collection idea first and add an event handler to the OnRemoved event (assuming there is one, otherwise i can build my own collection class). If the OnRemoved event is handled in the parent thread then this is perfect but otherwise it's a problem.
What do you think?
darthBug
Join the dark side of the code
|
|
|
|
|
Read the source code below. Not quite production, but you'll get the idea on how the ManualResetEvents work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ManualResetExample {
public class MockModule {
public MockModule(String name) {
Name = name;
}
public String Name { get; private set; }
private Object syncLock = new Object();
private EventHandler onDone;
public event EventHandler OnDone {
add {
lock (syncLock) {
onDone += value;
}
}
remove {
lock (syncLock) {
onDone -= value;
}
}
}
private void FireOnDone(Object sender, EventArgs args) {
if (onDone != null) {
onDone(sender, args);
}
}
public void StartWork() {
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkThread));
}
private void WorkThread(Object arg) {
try {
for (int i = 0; i < 5; i++) {
Thread.Sleep(250);
Console.WriteLine("{0} working", Name);
}
} finally {
FireOnDone(this, new EventArgs());
}
}
}
public class WorkCompleteEventArgs : EventArgs {
public WorkCompleteEventArgs(Boolean wasSuccessful) {
Success = wasSuccessful;
}
public Boolean Success { get; private set; }
}
internal class ModuleSyncBlock {
public ModuleSyncBlock(MockModule module) {
Reset = new ManualResetEvent(false);
MockModule = module;
}
public ManualResetEvent Reset { get; set; }
public MockModule MockModule { get; set; }
}
public class ModuleManager {
List<modulesyncblock> modules;
List<mockmodule> mocks;
public ModuleManager() {
modules = new List<modulesyncblock>();
mocks = new List<mockmodule>();
mocks.Add(new MockModule("One"));
mocks.Add(new MockModule("Two"));
mocks.Add(new MockModule("Three"));
mocks.Add(new MockModule("Four"));
mocks.Add(new MockModule("Five"));
}
public void StartAll() {
ThreadPool.QueueUserWorkItem(new WaitCallback(RunInternal));
}
private void RunInternal(Object arg) {
List<manualresetevent> manuals = new List<manualresetevent>();
mocks.ForEach(m => modules.Add(new ModuleSyncBlock(m)));
modules.ForEach(m => manuals.Add(m.Reset));
modules.ForEach(m => {
m.MockModule.OnDone += new EventHandler(MockModule_OnDone);
m.MockModule.StartWork();
});
if (WaitHandle.WaitAll(manuals.ToArray(), new TimeSpan(0, 0, 30), false)) {
FireOnWorkComplete(this, new WorkCompleteEventArgs(true));
} else {
FireOnWorkComplete(this, new WorkCompleteEventArgs(false));
}
}
void MockModule_OnDone(object sender, EventArgs e) {
ModuleSyncBlock msb = modules.Find(m => ReferenceEquals(sender, m.MockModule));
if (msb != null) {
Console.WriteLine(msb.MockModule.Name + " Finished");
msb.Reset.Set();
}
}
private Object syncLockA = new Object();
private EventHandler<workcompleteeventargs> onWorkComplete;
public event EventHandler<workcompleteeventargs> OnWorkComplete {
add {
lock (syncLockA) {
onWorkComplete += value;
}
}
remove {
lock (syncLockA) {
onWorkComplete -= value;
}
}
}
private void FireOnWorkComplete(Object sender, WorkCompleteEventArgs args) {
if (onWorkComplete != null) {
onWorkComplete(sender, args);
}
}
}
}
</workcompleteeventargs></workcompleteeventargs></manualresetevent></manualresetevent></mockmodule></modulesyncblock></mockmodule></modulesyncblock>
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
Where do you guys (and girls) typically put the definition of an enum in your code? I have generally placed mine just inside the namespace instead of inside a class. It seems like the namespace is getting cluttered with enumerations.
Thanks for your comments!
Hogan
|
|
|
|
|
I typically create them in the namespace. I like having them seperated one class/enum per file so I can easily find them if I need to update them.
Broken Bokken
You can't carry out a ninja-style assasination dressed as an astronaut. It's the luminous fabric; too visible. - Tripod
http://www.brokenbokken.com
|
|
|
|
|
Hey,
I keep 'em the same way, one class per file and a bunch of enums in their own file under the same namespace.
darthBug
Join the dark side of the code
|
|
|
|
|
Interesting idea. Currently we just throw em at the top of whatever file they are needed at. It forces us to search through the code more. I'll have to look into that one file for enums idea.
Hogan
|
|
|
|
|
Same here, all in one file. I typically twiddle with enums much less, and it cuts down on the clutter in the project.
Scott P
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
Hi Guys. I am trying to match some input from a text box to an if statement. Now, I am doing this from following some ARL code and I get a build error. Error message is "Operator '>=' cannot be applied to operands of type 'string' and 'string'"
The ARL code looks something like this.
if ws_holder_pcode >= 4731 and ws_holder_pcode <= 6499
begin
move 1 to ws_holder_province
finish
end
What I have written in the button click event.
private void btnValidate_Click(object sender, EventArgs e)
{
if (txtboxPcode.Text >= "4731" && txtboxPcode.Text <= "6499")
{
MessageBox.Show("Eastern Cape");
}
}
How can I do this correctly? Any suggestions would be greatly appreciated.
Excellence is doing ordinary things extraordinarily well.
|
|
|
|
|
To compare strings, try the String.Compare() method.
private void btnValidate_Click(object sender, EventArgs e)<br />
{<br />
<br />
if (String.Compare(txtboxPcode.Text,"4731") == 0 && String.Compare(txtboxPcode.Text,"6499") == 0)<br />
{<br />
MessageBox.Show("Eastern Cape");<br />
}<br />
}
Just because we can; does not mean we should.
|
|
|
|
|
Thanks mate. I actualy want to check that the value entered falls in the range of 4731 and 6499.
KaptinKrunch wrote: if (String.Compare(txtboxPcode.Text,"4731") == 0 && String.Compare(txtboxPcode.Text,"6499") == 0)
I have tried the suggestion that you made but I keep getting "Invalid Pcode" message returned from the else statement meaning that I am not making a match. So, what I want to do is something like this.
if (txtboxPcode.Text >= 4731 && txtboxPcode.Text <= 6499)
{
MessageBox.Show("Eastern Cape");
}
Any further suggestions appreciated.
Excellence is doing ordinary things extraordinarily well.
|
|
|
|
|
You could change your strings "6499" to Int32's and convert the contents of your text boxes to int's by Int32.Parse(box.Text);
and don't forget to put in the IFormatProvider to the Parse method.
Scott P
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
Keep in mind too that your if logic is stating that your textbox value needs to equal both 4731 and 6499. If you need to match one or the other, change the operator to "||"(OR) vs "&&"(AND).
Just because we can; does not mean we should.
|
|
|
|
|
If the value entered falls within the range of 4731 and 6499 i.e. the user enters 5000 then a amtch is made. Maybe I am writing it wrong. If the value entered falls anywhere inbetween then we have match.
Excellence is doing ordinary things extraordinarily well.
|
|
|
|