[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

7.0

System.Reflection.TargetInvocationException was unhandled - In Visual Basic 2008, Threaded Windows App

Asked by megnin in Visual Basic Programming, .NET Framework 3.x versions, .NET

Tags: Multi-Thread, Visual Basic, VB 2008, Exception

I'm getting an error I don't know how to fix.  I'm kind of a beginner at programming and have pieced together a multi-threaded Windows app in Visual Basic 2008 that's a bit beyond my experience level.

Overview of the app:
The app is basically a control panel to set useage timers on a room full of computers and when the 0 to 60 minute timer runs down sends a "shutdown -r" command to restart the computer.

It creates an array of button click events, one button per computer, and uses the indexes to keep track of a timer for each computer.

There is a BackgroundWorker that Just constantly Loops through all the computers, pings them and sets an indicator "light" as appropriate, Green if ping is successful, Red if not using PictureBoxes.

The BackgroundWorker also checks if there is a "reset pending" flag set using this array, arrIsPending(k) and if the computer is in a reset pending state (the timer is running) it checks to see if the timer has reached 0 or not and if so resets the arrIsPending flag to False and sets up a secondary "Warning Timer".

That all seems to work okay until the timer reaches zero then I get the Exception:
I could sure use some help on this.  I thought I was finished with this app until I discovered the Exception when the timer hit zero.  I hope it's something simple. I can attach any other parts of the solution if necessary.  The entire VB code is below in the Code: box.

#############################################
  Message="Exception has been thrown by the target of an invocation."
  Source="mscorlib"
  StackTrace:
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThrSystem.Reflection.TargetInvocationException was unhandledeadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.MessageBox(HandleRef hWnd, String text, String caption, Int32 type)
       at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)
       at System.Windows.Forms.MessageBox.Show(String text)
       at SouthUCClaims.Form1.btn_Click(Object sender, EventArgs e) in D:\0-VisualStudioProjects\ComputerShutdownSouthUCClaims\Form1.vb:line 271
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at SouthUCClaims.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.ArgumentOutOfRangeException
       Message="Value of '3600' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'. Parameter name: Value"
       ParamName="Value"
       Source="System.Windows.Forms"
       StackTrace:
            at System.Windows.Forms.ProgressBar.set_Value(Int32 value)
            at SouthUCClaims.Form1.SetLights(LightStatus ls) in D:\0-VisualStudioProjects\ComputerShutdownSouthUCClaims\Form1.vb:line 446
            at SouthUCClaims.Form1.BackgroundWorker1_ProgressChanged(Object sender, ProgressChangedEventArgs e) in D:\0-VisualStudioProjects\ComputerShutdownSouthUCClaims\Form1.vb:line 427
            at System.ComponentModel.BackgroundWorker.OnProgressChanged(ProgressChangedEventArgs e)
            at System.ComponentModel.BackgroundWorker.ProgressReporter(Object arg)
       InnerException:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
537:
538:
539:
540:
541:
542:
543:
544:
545:
546:
547:
548:
549:
550:
551:
552:
553:
554:
555:
556:
557:
558:
559:
560:
561:
562:
563:
564:
565:
566:
567:
568:
569:
570:
571:
572:
573:
574:
575:
576:
577:
578:
579:
580:
581:
582:
583:
584:
585:
586:
587:
588:
589:
590:
591:
592:
593:
594:
595:
596:
597:
598:
599:
600:
601:
602:
603:
604:
605:
606:
607:
608:
609:
610:
611:
612:
613:
614:
Imports System.Management
Imports System.Threading
 
Public Class Form1
    Private Enum Command
        Restart
        ShutDown
        Abort
        View
    End Enum
 
    Private Class LightStatus
        Public Index As Integer
        Public Red As Boolean
        Public Yellow As Boolean
        Public Green As Boolean
 
        Public Sub New(ByVal Index As Integer, ByVal Red As Boolean, ByVal Yellow As Boolean, ByVal Green As Boolean)
            Me.Index = Index
            Me.Red = Red
            Me.Yellow = Yellow
            Me.Green = Green
        End Sub
    End Class
    'See http://www.experts-exchange.com/Programming/Languages/.NET/Class_Libraries/Windows_Forms/Q_23384379.html#discussion
    Private Function ControlCounter(ByVal control As Control) As Integer
        Dim count As Integer = 0
        For Each ctrl As Control In control.Controls
            If TypeOf ctrl Is Button Then 'OrElse TypeOf ctrl Is PictureBox Then
                count += 1
            End If
            'If ctrl.HasChildren Then   'For recursiveness.  If a  panel with buttons has another panel inside it with more buttons.
            'count = ControlCounter(ctrl) + count
            'End If
        Next
        Return count
    End Function
    'See http://www.experts-exchange.com/Programming/Languages/.NET/Class_Libraries/Windows_Forms/Q_23384379.html#discussion
    Dim Cnt As Integer
    Private CurrentCommand As Command
    Private NumCompArray As String()
    Private TimerLapse As DateTime()
    Private WarningLapse As DateTime()        'To keep light yellow until the warning timer is up and shutdown.exe shuts down computer.
    Private arrIsPending As Boolean()
    Private arrWarningIsPending As Boolean()  'To keep light yellow until the warning timer is up and shutdown.exe shuts down computer.
 
    Private ProgressTimerMax As Integer() ' I already have TimerLapse and WarningLapse
 
    Dim ComputersXML As String = "Path Exists Check is in Form1_Load"
    Dim ComputerNumber As Integer()  'Not working so well
 
    Dim SelectedButton As Integer() ' Trying
    Dim CurrentButton As Integer
 
    Dim TimerMinutes As Int32 = 60
    Dim WarningMinutes As Integer = 5
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
        Control.CheckForIllegalCrossThreadCalls = False 'Try this and see if it solves the cross thread problem with the progress bar.
        'Path Exists Check:
        If My.Computer.FileSystem.FileExists("\\storserve\common\onestop_app\SouthUCClaims\Computers.xml") Then
            ComputersXML = "\\storserve\common\onestop_app\SouthUCClaims\Computers.xml" ' <--- Set path to Computers.xml in this one place.
        Else
            ComputersXML = "C:\Users\User\Documents\Visual Studio 2008\Projects\South UC Claims\Computers.xml"
        End If
 
        Cnt = ControlCounter(Me)
        NumCompArray = New String(Cnt - 3) {}
        TimerLapse = New DateTime(Cnt - 3) {}
        WarningLapse = New DateTime(Cnt - 3) {}          'To keep light yellow between TimerLapse ending and shutdown of computer
        arrIsPending = New Boolean(Cnt - 3) {}
        arrWarningIsPending = New Boolean(Cnt - 3) {}    'To keep light yellow between TimerLapse ending and shutdown of computer
        ProgressTimerMax = New Integer(Cnt - 3) {}
        ComputerNumber = New Integer(Cnt - 3) {}
        SelectedButton = New Integer(Cnt - 3) {}
        CurrentButton = New Integer
        ProgressBar1.Maximum = 3600
        ProgressBar1.Height = 20
        lblProgressBar1.Text = ""
        ProgressBar1.Style = ProgressBarStyle.Continuous  'It still shows blocks.  Even with the property set in VS.
 
        BackgroundWorker1.WorkerReportsProgress = True
 
        'GetXMLDataFromFile()  '<-- Opens Computers.xml to get the list of computer names for the array.
        Call GetXMLDataFromFile()
 
        ' Wire up Button1 thru Button39 so they all fire "btn_Click" below
        ' Set the DateTime to 10 minutes from Now
        ' Set the Pending Status to 0 (zero)
        'AddHandler Me.MouseEnter, AddressOf Me.form1_MouseEnter  '####See line 210###################################### Trying to add the Mouse Roll Over event (MouseEnter) for Status
 
        Dim btn As Button
        For i As Integer = 1 To Cnt - 2 '21         'Buttons Button1 - Button11   Adjust here for number of computers 'It counts the automatically now. Cnt -2 takes the two extra buttons out of the count
            btn = CType(Me.Controls("Button" & i), Button)
            AddHandler btn.Click, AddressOf btn_Click
            AddHandler btn.MouseEnter, AddressOf btn_MouseEnter   '####See line 210###################################### Trying to add the Mouse Roll Over event (MouseEnter) for Status
            TimerLapse(i - 1) = DateTime.Now.AddMinutes(60)  ' I think this is set to the Warning Slider value when it needs to be.  The value of 60 is just default, probably.
            WarningLapse(i - 1) = DateTime.Now.AddMinutes(60) ' just default setting on Form1 Load.
            arrIsPending(i - 1) = False  'nothing is pending yet.
            arrWarningIsPending(i - 1) = False
        Next i
        For j As Integer = 1 To Cnt - 2
            btn = CType(Me.Controls("Button" & j), Button)
            btn.Image = My.Resources._59PC
            btn.FlatAppearance.BorderSize = 0
            btn.FlatStyle = FlatStyle.Flat
            btn.TextAlign = ContentAlignment.TopLeft
            btn.Font = New System.Drawing.Font("Microsoft Sans Serif", 6)
            btn.ForeColor = Color.White
            ProgressTimerMax(j - 1) = 60
        Next j
 
        'This just pops the current deployment version number into that label in the top right corner e.g. v1.0.0.51
        If System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed Then
            lblVersion.Text = "v" & _
            System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString
        Else
            lblVersion.Text = "v" & My.Application.Info.Version.ToString
        End If
 
        BackgroundWorker1.RunWorkerAsync() ' Start the Process Rolling...
    End Sub
    Private Sub GetXMLDataFromFile()
        Dim ds As New DataSet
        'ds.ReadXml("\\storserve\Common\onestop_app\NorthResourceRoom\Computers.xml") ' Set this to the path of your XML file
        ds.ReadXml(ComputersXML) ' Set this to the path of your XML file.  Use variable so you only have to set the path in the variable declaration.
 
        NumCompArray = New String(ds.Tables(0).Rows.Count - 1) {}
 
        Dim i As Integer = 0
        Dim dr As DataRow
        For Each dr In ds.Tables(0).Rows
            ' Process each row here...
            NumCompArray(i) = CStr(dr.Item("ComputerName"))
            i += 1
        Next
    End Sub
 
    Private Sub radRestart_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radRestart.CheckedChanged
        If radRestart.Checked Then
            CurrentCommand = Command.Restart
        End If
    End Sub
 
    Private Sub radShutDown_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radShutDown.CheckedChanged
        If radShutDown.Checked Then
            CurrentCommand = Command.ShutDown
        End If
    End Sub
 
    Private Sub radAbort_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radAbort.CheckedChanged
        If radAbort.Checked Then
            CurrentCommand = Command.Abort
        End If
    End Sub
 
    Private Sub radView_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radView.CheckedChanged
        If radView.Checked Then
            CurrentCommand = Command.View
        End If
    End Sub
 
    Private Sub TrackBarTimer_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBarTimer.Scroll
        'Dim TimerMinutes As Int32 = TrackBar1.Value
        TimerMinutes = TrackBarTimer.Value
        lblTimer.Text = CStr(TimerMinutes) & " Minutes"
        'lblTimer.Text = TimerMinutes.ToString
        'GroupBox4.Text = "Use Timer " & CStr(TimerMinutes) & " Minutes"
        Select Case TimerMinutes
            Case 60
                lblTimerSixty.ForeColor = Color.Green
                lblTimerZero.ForeColor = Color.DarkGray
            Case 0
                lblTimerZero.ForeColor = Color.Red
                lblTimerSixty.ForeColor = Color.DarkGray
            Case 1
                lblTimer.Text = CStr(TimerMinutes) & " Minute"
                lblTimerSixty.ForeColor = Color.DarkGray
                lblTimerZero.ForeColor = Color.DarkGray
            Case Else
                lblTimerZero.ForeColor = Color.DarkGray
                lblTimerSixty.ForeColor = Color.DarkGray
        End Select
    End Sub
 
    Private Sub TrackBarWarning_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBarWarning.Scroll
        WarningMinutes = TrackBarWarning.Value
        lblWarning.Text = CStr(WarningMinutes) & " Minutes"
        Select Case WarningMinutes
            Case 5
                lblWarningZero.ForeColor = Color.DarkGray
                lblWarningFive.ForeColor = Color.Green
                lblWarningTen.ForeColor = Color.DarkGray
            Case 10
                lblWarningZero.ForeColor = Color.DarkGray
                lblWarningFive.ForeColor = Color.DarkGray
                lblWarningTen.ForeColor = Color.Green
            Case 1
                lblWarning.Text = CStr(WarningMinutes) & " Minute"
                lblWarningZero.ForeColor = Color.DarkGray
                lblWarningFive.ForeColor = Color.DarkGray
                lblWarningTen.ForeColor = Color.DarkGray
            Case 0
                lblWarningZero.ForeColor = Color.Red
                lblWarningFive.ForeColor = Color.DarkGray
                lblWarningTen.ForeColor = Color.DarkGray
            Case Else
                lblWarningZero.ForeColor = Color.DarkGray
                lblWarningFive.ForeColor = Color.DarkGray
                lblWarningTen.ForeColor = Color.DarkGray
        End Select
    End Sub
    Private Sub btn_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Handles btn.MouseEnter
        '#######See line 88 ################################### Trying to add the Mouse Roll Over event (MouseEnter) for Status
        Dim btn As Button = DirectCast(sender, Button)
        Dim Index As Integer
        If Integer.TryParse(btn.Name.Substring("Button".Length), Index) Then
            Dim NumComp As String = NumCompArray(Index - 1)
            'L1.Text = CStr(Index)  ' Just the label changes now.  If it works make this update the StatusBar1.Max and StatusBar1.Value. '####### see lines 88 and 210 or 211
            'Okay, it worked great.  Now add the StatusBar stuff.
            If arrIsPending(Index - 1) Then
                CurrentButton = Index - 1
                btn.FlatAppearance.BorderColor = Color.Red
                TrackBarTimer.Value = ProgressTimerMax(Index - 1)               ' Trying this to see if it will set the Timer Slider to the value of the Status Computer.
                lblTimer.Text = CStr(ProgressTimerMax(Index - 1)) & " Minutes"               ' Okay, that worked, now set TimerMinutes and the label to the same value.
                'TimerLaps time only --> 'lblProgressBar1.Text = "Computer #" & CStr(Index) & " will restart in " & CInt(-1 * DateTime.Now.Subtract(TimerLapse(Index - 1)).TotalMinutes) & " Minutes. At " & TimerLapse(CurrentButton).ToString("T")
                lblProgressBar1.Text = "Computer #" & CStr(Index) & " Warning will start in " & CInt(-1 * DateTime.Now.Subtract(TimerLapse(Index - 1)).TotalMinutes) & " Minutes. At " & TimerLapse(CurrentButton).ToString("T")
            Else
                CurrentButton = Index - 1
                btn.FlatAppearance.BorderColor = Color.Red
 
                'TrackBarTimer.Value = ProgressTimerMax(Index - 1)               ' Trying this to see if it will set the Timer Slider to the value of the Status Computer.
                'lblTimer.Text = CStr(ProgressTimerMax(Index - 1)) & " Minutes"               ' Okay, that worked, now set TimerMinutes and the label to the same value.
 
                lblProgressBar1.Text = "Computer #" & CStr(Index) & " is Available"
            End If
        End If
    End Sub
    Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim btn As Button = DirectCast(sender, Button)
        Dim Index As Integer
        If Integer.TryParse(btn.Name.Substring("Button".Length), Index) Then
            Dim NumComp As String = NumCompArray(Index - 1)
            Select Case CurrentCommand  'Case Current Command may can go where the flags are set so the shutdown command doesn't start until the timer ends.
                Case Command.Restart
                    Try
                        If My.Computer.Network.Ping(NumComp) Then
                            'SetLights(New LightStatus(Index, False, True, False))  'If it doesn't set the light yellow more reliably at the bottom try doing it in both places.
                            arrIsPending(Index - 1) = True
                            arrWarningIsPending(Index - 1) = True
                            TimerLapse(Index - 1) = DateTime.Now.AddMinutes(TimerMinutes) ' Minutes the Timer Slider is set to...
                            WarningLapse(Index - 1) = DateTime.Now.AddMinutes(TimerMinutes + WarningMinutes) 'Total Timer and Warning Sliders time to change light to green.
                            MessageBox.Show("Computer #" & Index & " is starting " & TimerMinutes & " minute 'In-Use' Timer." & vbCrLf & "At the end of this Timer the 'Shutdown Warning' Timer will start with " & WarningMinutes & " minutes." & vbCrLf & "The PC will then restart automatically. (" & TimerMinutes + WarningMinutes & " minutes, total, from now.)")  'Changed minute report to TimerMinutes variable
 
                            ProgressTimerMax(Index - 1) = TimerMinutes ' + WarningMinutes
 
                            ' #############################################################
                            ' Create and set a Warning Timer time variable to use as the Shutdown.exe time and add the same time to the Yellow light time so it
                            ' doesn't turn green between the use timer expiring and the Shutdown command firing.
                            ' Maybe add another slider for the warning time with 0 to 10 minutes as max on the slider.
                            ' #############################################################
                            btn.FlatAppearance.BorderColor = Color.Red
                            'ComputerNumber = Index
                            CurrentButton = Index - 1
                            SetLights(New LightStatus(Index, False, True, False))
                        Else
                            MessageBox.Show("Computer # " & Index & " is not responding.")
                        End If
                    Catch ex As Exception
                        MessageBox.Show("Computer #" & Index & " is not responding.")
                    End Try
 
                Case Command.ShutDown 'Show ProgressBar Status.  All this does is select the computer to check it's status on the ProgressBar
                    Try
                        If My.Computer.Network.Ping(NumComp) Then
                            CurrentButton = Index - 1
                            btn.FlatAppearance.BorderColor = Color.Red
                            TrackBarTimer.Value = ProgressTimerMax(Index - 1)               ' Trying this to see if it will set the Timer Slider to the value of the Status Computer.
                            lblTimer.Text = CStr(ProgressTimerMax(Index - 1)) & " Minutes"               ' Okay, that worked, now set TimerMinutes and the label to the same value.
                            ' Change Minutes to Minutes if timermax = 1
                            ' Add a label over the ProgressBar to display the minutes remaining.
                            ' See what L3.text is and display that divided by 60 to show the minutes remaining.
                        Else
                            MessageBox.Show("Computer #" & Index & " is not responding.")
                        End If
                    Catch ex As Exception
                        MessageBox.Show("Computer #" & Index & " is not responding.")
                    End Try
 
                Case Command.Abort
                    Try
                        If My.Computer.Network.Ping(NumComp) Then
                            ProgressTimerMax(Index - 1) = 60  'This caused the ProgressBar1.value to reset to the full 60 minutes when the Abort was selected.
                            Shell("shutdown.exe -a -m \\" & NumComp)
                            SetLights(New LightStatus(Index, False, True, False))
                            arrIsPending(Index - 1) = False
                            arrWarningIsPending(Index - 1) = False
                            TimerLapse(Index - 1) = DateTime.Now.AddMinutes(60) ' Minutes the Timer Slider is set to...
                            WarningLapse(Index - 1) = DateTime.Now.AddMinutes(60 + 10) 'Total Timer and Warning Sliders time to change light to green.
                            '###########################################
                            ' Try setting a label instead of the MessageBox so that user action is not required every time.  It's a pain to have to click each Abort window.
                            'MessageBox.Show("Shutdown of Computer #" & Index & " Aborted. Timer canceled.")
                            lblProgressBar1.Text = "Computer #" & Index & " RESTART ABORTED. Timer canceled."
                            '###########################################
 
                            'ComputerNumber = Index
                            CurrentButton = Index - 1
                            btn.FlatAppearance.BorderColor = Color.Green
                        Else
                            MessageBox.Show("Computer #" & Index & " is not responding.")
                        End If
                    Catch ex As Exception
                        MessageBox.Show("Computer #" & Index & " is not responding.")
                    End Try
 
                Case Command.View
                    Dim myCommand As String = "C:\Program Files\Radmin Viewer 3\Radmin.exe"
                    Dim myOptions As String = " /connect:" & NumComp & " /noinput"
                    Try
                        If My.Computer.Network.Ping(NumComp) Then
                            Shell(myCommand & myOptions)
                            btn.FlatAppearance.BorderColor = Color.Orange
                            CurrentButton = Index - 1
                        Else
                            MessageBox.Show("Computer #" & Index & " is not responding.")
                        End If
                    Catch ex As Exception
                        MessageBox.Show("Computer #" & Index & " is not responding." & vbCrLf & ex.ToString & vbCrLf & myCommand & vbCrLf & myOptions)
                    End Try
 
            End Select
        End If
    End Sub
 
    Private Sub btnShutDownAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShutDownAll.Click
        'The "Shut Down All" button.  Loop through all the computers and shut them down with at 2 minute warning.
        '  Adjust here for number of computers
        Dim s As Integer
        s = MsgBox("Are You Sure?", MsgBoxStyle.OkCancel, " Really Restart ALL Computers in " & TimerMinutes & " minutes?")
        If s = 1 Then
            For i As Integer = 1 To Cnt - 2 '21 '39   'loop through all the computers, if ping is successfull shut it down and turn light yellow otherwise turn light red
                If My.Computer.Network.Ping(NumCompArray(i - 1)) Then
                    Shell("shutdown.exe -r -m \\" & NumCompArray(i - 1) & " -t  " & TimerMinutes & "  -c ""Thank you for using our Resource Center. Please finish all work prior to system shutdown in  " & TimerMinutes & "  minutes.""")
                    'If Ping is successful make pb[i]Yellow visible
                    SetLights(New LightStatus(i, False, True, False))
                    arrIsPending(i - 1) = True
                    TimerLapse(i - 1) = DateTime.Now.AddMinutes(2) ' two minutes from now...
                Else
                    SetLights(New LightStatus(i, True, False, False))
                    MessageBox.Show("Computer # " & i & " is not responding.")
                End If
            Next i
        Else
            Exit Sub
        End If
    End Sub
 
    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
 
        'Just constantly Loop through all computers, ping them and set indicator "light" as appropriate.
        Dim sw As New Stopwatch()
        sw.Start()
        Do Until sw.Elapsed.TotalMilliseconds > TimeSpan.FromHours(12).TotalMilliseconds ' 12 hours then computers shut down.
            'loop through computers.
            For i As Integer = 1 To Cnt - 2 '21 '39  ' 1 through total number of Computers/buttons  changed 39 to 11  Adjust here for number of computers
                For k As Integer = 0 To Cnt - 3 '20   'Zero Based - Total number of computers minus 1  changed 38 to 10  Adjust here for number of computers
                    If arrIsPending(k) Then
                        ' reset the Pending Flag is we have passed the "target" time
                        If DateTime.Now.Subtract(TimerLapse(k)).TotalMilliseconds > 0 Then '-5000 > 0 Then  'Check Timer for countdown from Timer to Zero, fire Shutdown.exe (-5000 gives it an extra 5 seconds so the dialog boxes pop up in the right order.)
                            arrIsPending(k) = False 'Set your flag back to 0 ' Set flag to False after Timer plus Warning time.  Move this to second Check.
                            ' #############################################################
                            ' Timer has counted down.
                            ' Put Shutdown.exe command here with 0-10 minute warning:
                            ' #############################################################
                            Shell("shutdown.exe -r -m \\" & NumCompArray(k - 0) & " -t " & WarningMinutes * 60 & " -c ""Thank you for using our Resource Center. So we can serve other customers, please finish all work and save any files you may be working on. This computer will automatically shut down in " & WarningMinutes & " minutes.""")
                            MessageBox.Show("Computer #" & k + 1 & " (" & NumCompArray(k - 0) & ") has completed " & TimerMinutes & " minute In-Use Timer." & vbCrLf & "Starting " & WarningMinutes & " minute 'Shutdown Warning' Timer." & vbCrLf & "In " & WarningMinutes & " minutes the PC will restart automatically.")
                            ' #############################################################
                            ' Create and set a Warning Timer time variable to use as the Shutdown.exe time and add the same time to the Yellow light time so it
                            ' doesn't turn green between the use timer expiring and the Shutdown command firing.
                            ' #############################################################
                        End If
                    Else
                        TimerLapse(k) = DateTime.Now.AddMinutes(60)    'Testing this Else clause to keep the timers resetting to 60 until arrIsPending = True
                    End If
                Next k
 
                If Not arrIsPending(i - 1) Then
                    For p As Integer = 0 To Cnt - 3
                        If arrWarningIsPending(p) Then
                            If DateTime.Now.Subtract(WarningLapse(p)).TotalMilliseconds > 0 Then
                                arrWarningIsPending(p) = False
                            End If
                        End If
                    Next p
                End If
 
                'If Not arrIsPending(i - 1) Then   'If the Timer has reached 0...  
                If Not arrWarningIsPending(i - 1) Then   'If the Warning has reached 0...  
                    'If the computer is online turn the Green PictureBox visible and the Red and Yellow ones not visible.
                    Try
                        If My.Computer.Network.Ping(NumCompArray(i - 1), 50) Then  '  (i - 1),100) miliseconds timeout value.  set back to 500 or 1000 when everthing works, or just remove it.
                            BackgroundWorker1.ReportProgress(0, New LightStatus(i, False, False, True))
                        Else
                            BackgroundWorker1.ReportProgress(0, New LightStatus(i, True, False, False))
                        End If
                    Catch ex As Exception
                        BackgroundWorker1.ReportProgress(0, New LightStatus(i, True, False, False))
                    End Try
                End If
 
                'Wait 1 second between computer pings.
                Threading.Thread.Sleep(50) '(1000)
            Next i
        Loop
        sw.Stop()
        MessageBox.Show("All Done. ALL Computer shut down command should go here.") ' put 12 hour shut down command here
    End Sub
 
    Private Sub btnResetScanLights_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResetScanLights.Click
        For i As Integer = 1 To Cnt - 2 '21 '39   'loop through all PictureBoxes and set all the Yellow visible.  -  changed 39 to 11  Adjust here for number of computers
            SetLights(New LightStatus(i, False, True, False))
        Next i
    End Sub
 
    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        SetLights(DirectCast(e.UserState, LightStatus))
    End Sub
 
    Private Sub SetLights(ByVal ls As LightStatus)
        Me.Controls("pb" & ls.Index & "Red").Visible = ls.Red
        Me.Controls("pb" & ls.Index & "Yellow").Visible = ls.Yellow
        Me.Controls("pb" & ls.Index & "Green").Visible = ls.Green
 
        L1.Text = CStr(DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalMilliseconds) ' "CurrentButton " & "  = " & CStr(CurrentButton + 1)
        L2.Text = "TimerMinutes  = " & CStr(TimerMinutes)
        L3.Text = "TimerLapse(CurrentButton)  = " & TimerLapse(CurrentButton)
        L4.Text = "ProgressTimerMax(CurrentButton)  = " & CStr((ProgressTimerMax(CurrentButton)) * 60)
        L5.Text = "Now.Subtract(TimerLapse(CurrentButton)  = " & CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds)
 
        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = ProgressTimerMax(CurrentButton) * 60
 
        If CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds) > 0 Then
            'TimerLapse time only --> 'ProgressBar1.Value = CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds)
            ProgressBar1.Value = CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds)
        Else
            ProgressBar1.Value = ProgressTimerMax(CurrentButton) * 60
        End If
 
        'End If
    End Sub
 
    Private Sub lblVersion_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lblVersion.DoubleClick
 
        Dim s As Integer
        s = MsgBox("Are You Sure?", MsgBoxStyle.OkCancel, " Edit Computer Name List?")
        If s = 1 Then
            'Process.Start("\\storserve\Common\onestop_app\Notepad++\notepad++.exe", "\\storserve\Common\onestop_app\NorthResourceRoom\Computers.xml")
            'Process.Start("\\storserve\Common\onestop_app\EditPadPro\EditPadPro.exe", "\\storserve\Common\onestop_app\NorthResourceRoom\Computers.xml")
            Process.Start("notepad.exe", ComputersXML)  '<-- Open Computers.xml in Notepad.
 
            Dim t As Integer
            t = MsgBox("You need to exit and restart the application to pick up any changes?", MsgBoxStyle.OkCancel, " Exit the Application Now?")
            If t = 1 Then
                Application.Exit()
            Else
                Exit Sub
            End If
        Else
            Exit Sub
        End If
 
    End Sub
 
End Class
 
'Class CodeExampleOnly
 
'    'You have to use a Delegate and the Invoke method to marshal the call onto the controls thread if necessary.
 
'    'Here is a simple example...
 
'    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'        Dim t As New System.Threading.Thread(AddressOf Me.NewThread)
'        t.Start()
'    End Sub
 
'    Private Delegate Sub UpdateLabelDelegate(ByVal value As String)
 
'    Private Sub NewThread()
'        Dim i As Integer
'        For i = 1 To 5
'            UpdateLabel("Test" & i)
'            System.Threading.Thread.Sleep(1000)
'        Next i
'    End Sub
 
'    Private Sub UpdateLabel(ByVal value As String)
'        If Label1.InvokeRequired Then
'            Dim uld As New UpdateLableDelegate(AddressOf UpdateLabel)
'            Label1.Invoke(uld, New Object() {value})
'        Else
'            Label1.Text = value
'        End If
'    End Sub
 
'End Class
 
'Class CodeExampleOnly
'    '    I assume you mean Application.DoEvents... The official explaination is this:
'    'When you run a Windows Form, it creates the new form, which then waits for events to handle. Each time
'    'the form handles an event, it processes all the code associated with that event. All other events wait
'    'in the queue. While your code handles the event, your application does not respond. For example, the
'    'window does not repaint if another window is dragged on top.
'    'If you call DoEvents in your code, your application can handle the other events. For example, if you
'    'have a form that adds data to a ListBox and add DoEvents to your code, your form repaints when another
'    'window is dragged over it. If you remove DoEvents from your code, your form will not repaint until the
'    'click event handler of the button is finished executing.
'    'The most common use of Application.DoEvents is when you are in a subroutine that takes some time to
'    'complete, and you want to make sure that your program does not stay unresponsive (can't move forms,
'    'click buttons etc) while the code completes.
 
'    'Also, the DoEvents has been changed. It is now practically the same as the System.Threading.Thread.Sleep(0) command.
'    'Seems like a lot, but if you import System.Threading, you just have to call Thread.Sleep(0):
 
'Imports System.Threading
 
'    Public Sub DoEvents()
 
'        Thread.Sleep(0)
 
'    End Sub
 
'    'This is better suited for new, .Net applications. It is also compatible for Multi-threading.
 
'    'Yes, the correct way to repaint a control is Object.Invalidate()
 
'End Class
 
'Class CodeExampleOnly
 
'    'There are a number of ways to modify the value displayed by the ProgressBar other than changing the Value property directly.
'    'You can use the Step property to specify a specific value to increment the Value property by, and then call the PerformStep method
'    'to increment the value. To vary the increment value, you can use the Increment method and specify a value with which to increment
'    'the Value property.
'    'here is some code to illustrate progress bar!!
 
'private void CopyWithProgress(string[] filenames)
'      {
'         // Display the ProgressBar control.
'         pBar1.Visible = true;
'         // Set Minimum to 1 to represent the first file being copied.
'         pBar1.Minimum = 1;
'         // Set Maximum to the total number of files to copy.
'         pBar1.Maximum = filenames.Length;
'         // Set the initial value of the ProgressBar.
'         pBar1.Value = 1;
'         // Set the Step property to a value of 1 to represent each file being copied.
'         pBar1.Step = 1;
 
'         // Loop through all files to copy.
'         for (int x = 1; x <= filenames.Length; x++)
'         {
'            // Copy the file and increment the ProgressBar if successful.
'            if(CopyFile(filenames[x-1]) == true)
'            {
'               // Perform the increment on the ProgressBar.
'               pBar1.PerformStep();
'            }
'         }
'      }
 
'End Class
 
 
'Public Class CodeExampleOnly
 
'    'Instead of calling the progressbar.performstep directly, you can also call a custom method inside of form2
'    'which could do all the work you need. You can also pass in parameters if you need:
 
 
'    Dim f As Form2
 
'    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'        f = New Form2
'        f.Show()
'    End Sub
 
'    Private Delegate Sub MyDelegate(ByVal a As Integer, ByVal b As Integer)
 
'    Public Sub DoWork()
'        For i As Integer = 1 To 10
'            f.Invoke(New MyDelegate(AddressOf f.UpdateProgress), 1000, 400)
'            Threading.Thread.Sleep(500)
'        Next
'    End Sub
 
'End Class
 
'Public Class Form2
 
'    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'        Dim t As New Threading.Thread(AddressOf Form1.DoWork)
'        t.Start()
'    End Sub
 
'    Public Sub UpdateProgress(ByVal a As Integer, ByVal b As Integer)
'        ProgressBar1.Maximum = a
'        ProgressBar1.Value = b
'    End Sub
 
'End Class
'Open in New Window
 
Related Solutions
Keywords: System.Reflection.TargetInvocation…
 
Loading Advertisement...
 
[+][-]08/06/09 09:09 AM, ID: 25035073Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: Visual Basic Programming, .NET Framework 3.x versions, .NET
Tags: Multi-Thread, Visual Basic, VB 2008, Exception
Sign Up Now!
Solution Provided By: Idle_Mind
Participating Experts: 1
Solution Grade: A
 
[+][-]08/05/09 04:14 PM, ID: 25028897Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/06/09 03:52 AM, ID: 25031856Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 03:58 AM, ID: 25031891Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 06:27 AM, ID: 25033007Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 09:48 AM, ID: 25035515Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 10:03 AM, ID: 25035646Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 10:10 AM, ID: 25035714Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 11:56 AM, ID: 25036817Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 03:46 PM, ID: 25038812Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091118-EE-VQP-93 - Hierarchy / EE_QW_3_20080625