Question

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

Asked by: megnin

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:

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

                                  
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:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-05 at 15:24:56ID24629789
Tags

Multi-Thread

,

Visual Basic

,

VB 2008

,

Exception

Topics

Visual Basic Programming

,

.NET Framework 3.x versions

,

.NET

Participating Experts
1
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SafeArrayTypeMismatchException was unhandled
    All, I am in the process of writing a virtual disk creator and are having some trouble. I have mostly everything working. I can create the virtual disk, but when I try to mount it, I get this error. Now when I say mount, I mean that it is basically opening the virtual dis...
  2. Unhandled Exception: System.Security.SecurityExcepti…
    Hello, I am new to C# and am trying to knock up a quick theory test. The code complies correctly and uses a number of third party dll's. When the program runs it produces the following; Unhandled Exception: System.Security.SecurityException: That assembly does not allow p...
  3. .NET assembly or a dependency not found - but assembl…
    Windows XP, .NET 1.1, developed in Visual Studio 2003. I have a .NET 1.1 application that I have on a number of users machines. Out of the 4 machines I have the application on, 3 of them run it without issue. However, 1 of them (of course, the most important one) fails with ...
  4. <add assembly="Microsoft.Office.Interop.Word, Ve…
    I'm using Visual Studio 2005 and I have a website that is using Microsoft.Office.Interop.Word assembly. I have added the reference to this assembly in my project but when I browse the website I get following error: An error occurred during the processing of a configuration f...
  5. System.ArgumentException was unhandled
    System.ArgumentException was unhandled Message="Parameter is not valid." Source="System.Drawing" StackTrace: at System.Drawing.FontFamily.GetName(Int32 language) at System.Drawing.FontFamily.get_Name() at System.Windows.Forms.Int...
  6. System.ArgumentOutOfRangeException was unhandled
    I receive the following error usually when closing the window... it occasionally happens when resizing the grid that sits inside of a tab. I have several grids on various tabs. I have made sure every event on each data event checks to make sure there are rows present before...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Idle_MindPosted on 2009-08-05 at 16:14:22ID: 25028897

That's ALOT of code to digest...

The crux of the error is here:

       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)

So you're trying to set the Value() Property of a ProgressBar to 3600 somewhere in the code and that is not valid as it is not between the Minimum() and Maximum() valuess set for the ProgressBar.

 

by: megninPosted on 2009-08-06 at 03:52:01ID: 25031856

That much I could see.

 

by: megninPosted on 2009-08-06 at 03:58:25ID: 25031891

It's in this timer here, but I don't know how to fix it so that the timer never goes into negative numbers and still works.  It could be as simple as casting it to an unsigned integer, but my head swims when I try to figure out what each part of that statement is doing to "DateTime.Now".  ;-)

 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.
                       

 

by: megninPosted on 2009-08-06 at 06:27:30ID: 25033007

Then here at arround line 432 is where the ProgressBar1.Value is set for whatever computer has a timer set on it.:

   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

        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = ProgressTimerMax(CurrentButton) * 60

        If CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds) > 0 Then
            ProgressBar1.Value = CInt(-1 * DateTime.Now.Subtract(TimerLapse(CurrentButton)).TotalSeconds)
        Else
            ProgressBar1.Value = ProgressTimerMax(CurrentButton) * 60
        End If

    End Sub

I think if I can keep that value in the positive range it may solve the problem.

 

by: Idle_MindPosted on 2009-08-06 at 09:09:14ID: 25035073

Looking at this line:

    If DateTime.Now.Subtract(TimerLapse(k)).TotalMilliseconds > 0 Then

In plain English, that line is saying:

    If the DateTime value stored in TimeLapse(k) is in the PAST Then do this...

Let me study the code to see if I can understand what you're doing with the second snippet...

 

by: megninPosted on 2009-08-06 at 09:48:22ID: 25035515

I changed the order of the timer code a bit.  It gives the exact same value, it just looks easier to read.  Still in the Private Sub SetLights...:

        If CInt(Abs(TimerLapse(CurrentButton).Subtract(Now).TotalSeconds)) > 0 Then  ' Use this format below for the timer.
            ProgressBar1.Value = CInt(Abs(TimerLapse(CurrentButton).Subtract(Now).TotalSeconds))
        Else
            ProgressBar1.Value = ProgressTimerMax(CurrentButton) * 60
        End If


I'm pretty sure my whole problem is that I'm resetting the ProgressBar1.Value back to the default 60 minutes somewhere before the ProgressBar1.Max is getting set back to the default 60 minutes after the timer reaches 0.  So there's a point when the timer has reached 0 that I'm resetting the value before resetting the max.

When I run the app, not in debug, the error I get makes it clearer:

************** Exception Text **************
System.ArgumentOutOfRangeException: Value of '3600' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value
   at System.Windows.Forms.ProgressBar.set_Value(Int32 value)
   at CentralControlPanel.Form1.SetLights(LightStatus ls)
   at CentralControlPanel.Form1.BackgroundWorker1_ProgressChanged(Object sender, ProgressChangedEventArgs e)
   at System.ComponentModel.BackgroundWorker.OnProgressChanged(ProgressChangedEventArgs e)
   at System.ComponentModel.BackgroundWorker.ProgressReporter(Object arg)


It seems like a simple problem, but the BackgroundWorker and arrays make it hard for me to figure out where and when things are happening.

 

by: megninPosted on 2009-08-06 at 10:03:32ID: 25035646

With this line commented out:

        Else
            ProgressBar1.Value = ProgressTimerMax(CurrentButton) * 60
        End If

the Catch ex As Expeption is firing here.  So there's something wrong with the timer here.

I've set some labels to monitor different values like TimerLapse, ProgressTimerMax and such, but it's still awfully confusing.

   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

                                              
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:

Select allOpen in new window

 

by: megninPosted on 2009-08-06 at 10:10:46ID: 25035714

I could also be using seconds (3600) where I should be using minutes (60).  I'll look into that.

 

by: megninPosted on 2009-08-06 at 11:56:26ID: 25036817

Would I be better of changing all my countdown timers from using "DateTime.Now.AddMinutes.AuntMarthasBirthday(TimerMinutes) to using the Stopwatch()?

It seems like that would make things look simpler.

 

by: Idle_MindPosted on 2009-08-06 at 15:46:07ID: 25038812

Is this the same app I helped you with about a year and half ago (Apr 2008)?!
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Studio_.NET_2005/Q_23308315.html

I really didn't give you much to go on this time sorry...  =\

It seems like the app might be more manageable if you wrote a UserControl or a Class to handle each Computer separately.  You can use custom Events to communicate status back to the main UI.  Doing it this way would make it much easier on you as the code in the actual form would be much reduced and the UserControl/Class would only have to deal with ONE computer.  You could encapsulate a BackgroundWorker or a manual thread in each Class.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...