how to run Cmd command(chkdsk) on selected drive in a dataGridView - visual-studio

I am building a program in visual-studio to check and fix drive using the cmd chkdsk command
I have been able to display the list of drive available is a dataGridview
I want to run chkdsk command on any selected drive(by the user) please how do I achieve that successfully. Furthermore I want the process and result of the chkdsk to be displayed on a textbox.
problem is the drives are displaying but when one is select and i click on the button fix is dose not execute(i.e fix the drive and show result&process in the textbox) Any help/code/suggestion will b appreciated, please note this is note a console application. My code are on is posted here as requested. i added the subs were i feel the problem could be from. , but if you want me to add more of my other subs i will.
Public Class Form2
Private binder As New BindingSource
Private drives As New BindingList(Of DriveInfo)
Private psi As ProcessStartInfo
Private cmd As Process
Private Delegate Sub invokeWithString(ByVal text As String)
Dim BackgrounndWorker1 As New BackgroundWorker
Private Shadows Sub OnClick(sender As Object, e As EventArgs) Handles btnfix.Click
If TypeOf sender Is Button Then
Dim btn = DirectCast(sender, Button)
btn.Enabled = False
If btn.Equals(btnfix) Then
Ddrives.Enabled = False
pgb.Visible = True
BackgroundWorker1.RunWorkerAsync(New List(Of DriveInfo)(From drive As DriveInfo In cldrive.CheckedItems Select drive))
End If
End If
End Sub
Private Sub OnDoWOrk(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If TypeOf sender Is BackgroundWorker Then
Dim worker As BackgroundWorker = DirectCast(sender, BackgroundWorker)
If e.Argument IsNot Nothing AndAlso TypeOf e.Argument Is IEnumerable(Of DriveInfo) Then
Dim drives As IEnumerable(Of DriveInfo) = DirectCast(e.Argument, IEnumerable(Of DriveInfo))
For Each drive As DriveInfo In drives
Try
cmd.Kill()
Catch ex As Exception
End Try
TextBox1.Text = ""
psi = New ProcessStartInfo("Chkdsk /f")
Dim systemcoding As System.Text.Encoding =
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemcoding
.StandardErrorEncoding = systemcoding
End With
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_data_received
AddHandler cmd.OutputDataReceived, AddressOf Async_data_received
Try
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
Catch ex As System.ComponentModel.Win32Exception
End Try
Next
End If
End If
End Sub
Private Sub Async_data_received(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Me.Invoke(New invokeWithString(AddressOf Sync_output), e.Data)
End Sub

Related

Failed to create component 'BindingNavigator'

Here's what error I got while connecting the Access database to my Visual Studio.
I am confused about what to do next.
Public Class main
Const WM_NCHITTEST As Integer = &H84
Const HTCLIENT As Integer = &H1
Const HTCAPTION As Integer = &H2
Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DoubleBuffered = True
Timer1.Start()
Label1.Text = "Locker"
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Location = New Point(Label1.Location.X + 15, Label1.Location.Y)
If (Label1.Location.X >= 330) Then
Timer1.Stop()
Timer2.Start()
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
DoubleBuffered = True
GroupBox1.Size = New Size(GroupBox1.Size.Width, GroupBox1.Size.Height + 10)
If (GroupBox1.Size.Height >= 298) Then
Timer2.Stop()
End If
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case WM_NCHITTEST
MyBase.WndProc(m)
If m.Result = IntPtr.op_Explicit(HTCLIENT) Then m.Result = IntPtr.op_Explicit(HTCAPTION)
Case Else
MyBase.WndProc(m)
End Select
End Sub
End Class
Try removing it from Resources from Properties(Alt+Enter). And Re-open it. I think whenever you delete any resource file which is been used by a form then the form designer code can not locate it so try this one also by removing the line of code from Form[Designer].vb (opening in Notepad++).

How to display selected features in ArcGIS Identify Dialog using Visual Studio 2010/ArcObjects?

I'm brand new to ArcObjects SDKs and am struggling. I have a Python Add-in performing a query to select records (works great)and now trying to call the identify dialog via an .NET addin button that displays the identify dialog box to show attributes of the selected records. Below is the code I have at this point. I currently have the identify dialog displaying, but no records appearing. I know I need to input the selected records somewhere....but not sure where. Any thoughts would be appreciated. (I'm using Visual Studio/Microsoft Visual Basic 2010 and ArcGIS 10.2.1)
Imports ESRI.ArcGIS.ArcMapUI
Imports ESRI.ArcGIS.Carto
Public Class Identify_Button
Inherits ESRI.ArcGIS.Desktop.AddIns.Button
Dim pMxDoc As IMxDocument
Dim activeView As IMap
Public Sub DoIdentify(ByVal activeView As ESRI.ArcGIS.Carto.IActiveView, ByVal x As System.Int32, ByVal y As System.Int32)
pMxDoc = My.ArcMap.Application.Document
activeView = pMxDoc.FocusMap
If activeView Is Nothing Then
Return
End If
Dim map As ESRI.ArcGIS.Carto.IMap = activeView.FocusMap
Dim identifyDialog As ESRI.ArcGIS.CartoUI.IIdentifyDialog = New ESRI.ArcGIS.CartoUI.IdentifyDialogClass
identifyDialog.Map = map
'Clear the dialog on each mouse click
identifyDialog.ClearLayers()
Dim screenDisplay As ESRI.ArcGIS.Display.IScreenDisplay = activeView.ScreenDisplay
Dim display As ESRI.ArcGIS.Display.IDisplay = screenDisplay ' Implicit Cast
identifyDialog.Display = display
Dim identifyDialogProps As ESRI.ArcGIS.CartoUI.IIdentifyDialogProps = CType(identifyDialog, ESRI.ArcGIS.CartoUI.IIdentifyDialogProps) ' Explicit Cast
Dim enumLayer As ESRI.ArcGIS.Carto.IEnumLayer = identifyDialogProps.Layers
enumLayer.Reset()
Dim layer As ESRI.ArcGIS.Carto.ILayer = enumLayer.Next
Do While Not (layer Is Nothing)
identifyDialog.AddLayerIdentifyPoint(layer, x, y)
layer = enumLayer.Next()
Loop
identifyDialog.Show()
End Sub
Public Sub New()
End Sub
Protected Overrides Sub OnClick()
DoIdentify(activeView, 300, 100)
End Sub
Protected Overrides Sub OnUpdate()
Enabled = My.ArcMap.Application IsNot Nothing
End Sub
End Class
Give the code below a try. This is executed from the OnClick event from an ArcMap command button that Inherits from BaseCommand. It displays the selected features in the map in the identifyDialog just as you were needing it to except I used AddLayerIdentifyOID() instead of AddLayerIdentifyPoint() although both should work.
Public Overrides Sub OnClick()
'VBTest.OnClick implementation
Try
Dim mxDoc As IMxDocument = m_application.Document
Dim map As ESRI.ArcGIS.Carto.IMap = mxDoc.FocusMap
Dim layer As ESRI.ArcGIS.Carto.ILayer
Dim flayer As ESRI.ArcGIS.Carto.IFeatureLayer
Dim featSelection As ESRI.ArcGIS.Carto.MapSelection = map.FeatureSelection
Dim feat As ESRI.ArcGIS.Geodatabase.IFeature = featSelection.Next()
Dim count As Int16 = 0
While feat IsNot Nothing
count += 1 ' flag for clearing layers
flayer = New ESRI.ArcGIS.Carto.FeatureLayer()
flayer.FeatureClass = feat.Class
layer = flayer
DoIdentify(layer, feat.OID, (count = 1))
feat = featSelection.Next()
End While
Catch ex As Exception
' handle error
MsgBox("Error: " + ex.Message)
End Try
End Sub
Private Sub DoIdentify(ByVal layer As ESRI.ArcGIS.Carto.ILayer, ByVal OID As Int32, Optional ByVal clearLayers As Boolean = True)
If layer Is Nothing Or OID <= 0 Then
Return
End If
Dim pMxDoc As IMxDocument = m_application.Document
Dim activeView As ESRI.ArcGIS.Carto.IActiveView = pMxDoc.ActiveView
Dim map As ESRI.ArcGIS.Carto.IMap = activeView.FocusMap
Dim identifyDialog As ESRI.ArcGIS.CartoUI.IIdentifyDialog = New ESRI.ArcGIS.CartoUI.IdentifyDialogClass()
Dim screenDisplay As ESRI.ArcGIS.Display.IScreenDisplay = activeView.ScreenDisplay
Dim display As ESRI.ArcGIS.Display.IDisplay = screenDisplay
identifyDialog.Map = map ' REQUIRED
identifyDialog.Display = display ' REQUIRED
' Clear the dialog
If clearLayers Then
identifyDialog.ClearLayers()
End If
' Add our selected feature to the dialog
identifyDialog.AddLayerIdentifyOID(layer, OID)
' Show the dialog
identifyDialog.Show()
End Sub

Custom MsgBox without form activate being fired

I have developed a custom MsgBox that works fine in almost every way. The only problem is that when the MsgBox closes the parent form runs the Form_Activate code. A normal MsgBox does not run that code (again).
I know i could add a boolean variable to Form_Activate to check if it has fired already, but that's not the best solution when you have a dozen forms.
So, is there a way to not run Form_Activate after closing my custom MsgBox? Does the MsgBox form need to be of some special type or something? I tried all BorderStyles but that doesn't make any difference.
Are you using another form to make custom MsgBox?
You shouldn't use directly other form to show a custom messagebox.
You should create an Activex control, and Activate event won't fire again when the MsgBox is closed.
Within the control you can use a form if you want it. (Probably just have to place your code inside an ActiveX control project and use it in your forms)
I use it that way.
This is a custom MsgBox example using Activex Control, with a test form too.
http://www.codeguru.com/code/legacy/vb_othctrl/2166_CustomMsgBox.zip
I created a Class for a Custom MsgBox.
Public Class CustomMsgBox
'Creates the Main form
Dim Main As New Form
'Creates the buttons
Dim Btn1, Btn2, Btn3 As New Button
'Creates the label
Dim Lbl As New Label
'Creates the Output variable
Dim Output As Integer = 0
Private Sub Load()
'Btn1 properties
Btn1.Location = New Point(168, 69)
Btn1.AutoSize = True
Btn1.AutoSizeMode = AutoSizeMode.GrowOnly
'Btn2 properties
Btn2.Location = New Point(87, 69)
Btn1.AutoSize = True
Btn1.AutoSizeMode = AutoSizeMode.GrowOnly
'Btn3 properties
Btn3.Location = New Point(6, 69)
Btn1.AutoSize = True
Btn1.AutoSizeMode = AutoSizeMode.GrowOnly
'Lbl properties
Lbl.Location = New Point(12, 19)
Lbl.AutoSize = True
Lbl.AutoEllipsis = True
'Main form properties
Main.Size = New Size(211, 129)
Main.AutoSize = True
Main.AutoSizeMode = AutoSizeMode.GrowOnly
Main.ShowIcon = False
Main.Controls.Add(Btn1)
Main.Controls.Add(Btn2)
Main.Controls.Add(Btn3)
Main.Controls.Add(Lbl)
'Adds Handlers to the buttons
AddHandler Btn1.Click, AddressOf btn1_Click
AddHandler Btn2.Click, AddressOf btn2_Click
AddHandler Btn3.Click, AddressOf btn3_Click
End Sub
Function CstMsgBox(ByRef Msg As String, ByRef Title As String, ByRef B1 As String, Optional ByRef B2 As String = Nothing, Optional ByRef B3 As String = Nothing) As Integer
'Runs the Load() Sub
Load()
'Sets the values
Lbl.Text = Msg
Btn1.Text = B1
Btn2.Text = B2
Btn3.Text = B3
Main.Text = Title
'Checks if there is a value set to Btn2 and Btn3
If Btn2.Text = Nothing Then
Btn2.Hide()
End If
If Btn3.Text = Nothing Then
Btn3.Hide()
End If
'Shows the MsgBox
Main.Show()
'Waits until a button is pressed
Do Until Output <> 0
Application.DoEvents()
Loop
'Closes the MsgBox
Main.Close()
Return Output
End Function
Private Sub btn1_Click(ByVal sender As Object, ByVal e As EventArgs)
'Sets the Output value to 1
Output = 1
End Sub
Private Sub btn2_Click(ByVal sender As Object, ByVal e As EventArgs)
'Sets the Output value to 2
Output = 2
End Sub
Private Sub btn3_Click(ByVal sender As Object, ByVal e As EventArgs)
'Sets the Output value to 3
Output = 3
End Sub
End Class
You can use it by typing this:
Dim CMB As New CustomMsgBox
CCMB.CstMsgBox('MSG, 'TITLE, 'BUTTON1, 'Optional: BUTTON2, 'Optional: BUTTON3)
OR
Dim CMB As New CustomMsgBox
Select Case CMB.CstMsgBox('MSG, 'TITLE, 'BUTTON1, 'Optional: BUTTON2, 'Optional: BUTTON3)
Case 1
'Code to execute when button1 is pressed
Case 2
'Code to execute when button2 is pressed
Case 3
'Code to execute when button3 is pressed
End Select

Visual Studio - Perform a event action for "X" number of checkboxes?

I have 20 checkboxes.
This is the event for the checkbox nÂș1 :
Public Sub C1CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles C1CheckBox1.CheckedChanged
If C1CheckBox1.Checked = True Then My.Settings.box1_selected = "Y" Else My.Settings.box1_selected = "N"
Dim checkedpath1 = C1CheckBox1.Text
End Sub
I know I can add all the checkboxes in the "handles", but my number of checkboxes is undetermined and this is what I want to do:
(Pseudocode)
Public Sub ALL_THE_CHECKBOXES_CheckedChanged(sender As Object, e As EventArgs) Handles ALL_THE_CHECKBOXES.CheckedChanged
If ANY_CHECKBOX.Checked = True
My.Settings.boxNUMBER_OF_THIS_SELECTED_CHECKBOX_selected = "Y"
Else
My.Settings.boxNUMBER_OF_THIS_SELECTED_CHECKBOX_selected = "N"
End If
Dim checkedpathNUMBER_OF_THIS_SELECTED_CHECKBOX = C1CheckBoxNUMBER_OF_THIS_SELECTED_CHECKBOX.Text
End Sub
I need to generate a event that handles an undetermined number of checkboxes,
I need to do the same action if any of the checkboxes is selected, but only in that selected checkbox.
Basically I want to remember in the settings which checkboxes was selected and which not...
UPDATE:
At form load I create ALL the form checkboxes with this code:
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim List As Integer = 0
Dim posy As Integer = 10
filesystem = CreateObject("Scripting.FileSystemObject")
ThisDir = filesystem.GetFolder(My.Settings.folderpath)
For Each folder In ThisDir.Subfolders
List = List + 1
posy = posy + 20
Dim newCheckBox As New CheckBox()
Panel1.Controls.Add(newCheckBox)
newCheckBox.Name = "checkbox" & List.ToString()
newCheckBox.Text = folder.name
newCheckBox.Location = New Point(10, posy)
Next
End Sub
That creates a checkboxes named "checkbox1", "checkbox2", "checkbox3", etc...
All checkboxes are inside of another control. might be form, panel whatever. So you can cycle through these checkboxes and manually assign the eventhandler for each checkbox you find
Revised Sample code:
You need a setting of type StringCollection named MyCBs - or you can use whatever name you like, just make the necessary changes to the code.
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
My.Settings.Save()
End Sub
Private Sub AnyCB_CheckedChanged(sender As Object, e As EventArgs)
Dim cb = DirectCast(sender, CheckBox)
If cb.Checked AndAlso Not My.Settings.MyCBs.Contains(cb.Name) Then
My.Settings.MyCBs.Add(cb.Name)
ElseIf Not cb.Checked AndAlso My.Settings.MyCBs.Contains(cb.Name) Then
My.Settings.MyCBs.Remove(cb.Name)
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
If My.Settings.MyCBs Is Nothing Then My.Settings.MyCBs = New Collections.Specialized.StringCollection
For Each s In My.Settings.MyCBs
DirectCast(Me.Controls(s), CheckBox).Checked = True
Next
For Each cb In Me.Controls.OfType(Of CheckBox)()
AddHandler cb.CheckedChanged, AddressOf AnyCB_CheckedChanged
Next
End Sub
This sample saves the checked status of the checkboxes in my.settings inside a StringCollection. If a CB is checked it's name is added to the collection, if it's unchecked, it's name is removed. This means on startup you can simply check which CB name is in the collection and sets its checked stats to true. Finally you use AddHandler to execute the code for any CB contained in your Form.
Note that there's NO error handling inside the code, which means that this is your part ...

problem with .net windows service

have written a windows service. while the code worked for a simple form app, its not working in a windows service. here;s the code
Imports System.Text.RegularExpressions
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Service1
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://google.com"), HttpWebRequest)
myWebRequest.Proxy = New WebProxy(Proxy, False)
myWebRequest.Timeout = 10000
Try
Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)
Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream())
Return True
Catch ex As WebException
If (ex.Status = WebExceptionStatus.ConnectFailure) Then
End If
Return False
End Try
End Function
Protected Overrides Sub OnStart(ByVal args() As String)
System.IO.File.AppendAllText("C:\AuthorLog.txt",
"AuthorLogService has been started at " & Now.ToString())
MsgBox("1")
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
MsgBox("2")
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("Evoain Proxy Bot") Then
Diagnostics.EventLog.CreateEventSource("MyService", "Myservice Log") ' Create Log
End If
' Write to the Log
Diagnostics.EventLog.WriteEntry("MyService Log", "This is log on " & _
CStr(TimeOfDay), EventLogEntryType.Information)
Dim ProxyURLList As New Chilkat.CkString
Dim ProxyListPath As New Chilkat.CkString
Dim WorkingProxiesFileData As New Chilkat.CkString
Dim ProxyArray(10000000) As String
Dim event1 As New Chilkat.CkString
event1.setString("started")
event1.saveToFile("B:\serv.txt", "utf-8")
Dim ns As Integer = 0
'Read Configuration File
Dim sFileName As String
Dim srFileReader As System.IO.StreamReader
Dim sInputLine As String
sFileName = "config.ini"
srFileReader = System.IO.File.OpenText(sFileName)
sInputLine = srFileReader.ReadLine()
Dim temp As New Chilkat.CkString
Do Until sInputLine Is Nothing
temp.setString(sInputLine)
If temp.containsSubstring("proxyurllist=") = True Then
'Read Proxy-URL-List
ProxyURLList.setString(sInputLine)
If ProxyURLList.containsSubstring("proxyurllist=") = True Then
ProxyURLList.replaceFirstOccurance("proxyurllist=", "")
End If
ElseIf temp.containsSubstring("finalproxylistpath=") = True Then
'Read Proxy-List-Path
ProxyListPath.setString(sInputLine)
If ProxyListPath.containsSubstring("finalproxylistpath=") = True Then
ProxyListPath.replaceFirstOccurance("finalproxylistpath=", "")
End If
End If
sInputLine = srFileReader.ReadLine()
Loop
'*********Scrape URLs From Proxy-URL-List*********************
Dim ProxyURLFileData As New Chilkat.CkString
ProxyURLFileData.loadFile(ProxyURLList.getString, "utf-8")
Dim MultiLineString As String = ProxyURLFileData.getString
Dim ProxyURLArray() As String = MultiLineString.Split(Environment.NewLine.ToCharArray, System.StringSplitOptions.RemoveEmptyEntries)
Dim i As Integer
For i = 0 To ProxyURLArray.Count - 1
'********Scrape Proxies From Proxy URLs***********************
Dim http As New Chilkat.Http()
Dim success As Boolean
' Any string unlocks the component for the 1st 30-days.
success = http.UnlockComponent("Anything for 30-day trial")
If (success <> True) Then
Exit Sub
End If
' Send the HTTP GET and return the content in a string.
Dim html As String
html = http.QuickGetStr(ProxyURLArray(i))
Dim links As MatchCollection
links = Regex.Matches(html, "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5}")
For Each match As Match In links
Dim matchUrl As String = match.Groups(0).Value
ProxyArray(ns) = matchUrl
ns = ns + 1
Next
Next
'*************CHECK URLs*****************
Dim cnt As Integer = 0
For cnt = 0 To 1
Dim ProxyStatus As Boolean = CheckProxy("http://" + ProxyArray(cnt) + "/")
If ProxyStatus = True Then
WorkingProxiesFileData.append(Environment.NewLine)
WorkingProxiesFileData.append(ProxyArray(cnt))
End If
Next
WorkingProxiesFileData.saveToFile(ProxyListPath.getString, "utf-8")
End Sub
End Class
what are the basic thing i cannot do in a windows service? oh, and i am using the chilkat library too..
why can't i use all of my code in OnStart? i did so and the services stops just as it starts.
can i use something else except a timer and put an endless loop?
Running as a windows service typically won't let you see any popup boxes, etc since there's no UI (Unless you check the box to allow interaction with the desktop).
Try adding a Timer1.Start in your OnStart method. Then in your Timer1_Tick method, first thing stop the timer, then at the end start it back up, this way your Tick method won't fire while you're already doing work.
I realize I'm (very) late to this party, but what kind of timer are you using? A System.Windows.Forms.Timer is designed for use in a single threaded Windows Form and will not work in a Windows Service app. Try a System.Timers.Timer instead.

Resources