Creating a Windows Restore Point? - vb.net

So I have this code, and am running into some issues that I haven't so far been able to sort out:
Anywhere there are Parameters, i.e. "CreateRestorePoint", or the inParams params, I get the green squiggly underline that says to use (ex.) "NameOf(CreateRestorePoint) instead of specifying the program element name".
However, whether I do so or leave it, I get the same error:
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: path'
The code:
Public Function CreateRestorePoint(Description As String, EventType As Integer, RestorePointType As Integer) As Integer
Try
Dim classInstance As New ManagementObject("root\DEFAULT", "SystemRestore", Nothing)
' Obtain [in] parameters for the method
Dim inParams As ManagementBaseObject = classInstance.GetMethodParameters("CreateRestorePoint")
' Add the input parameters
inParams("Description") = Description
inParams("EventType") = EventType
inParams("RestorePointType") = RestorePointType
' Execute the method and obtain the return values
Dim outParams As ManagementBaseObject = classInstance.InvokeMethod("CreateRestorePoint", inParams, Nothing)
' List outParams
Debug.Print("Out parameters: ")
Debug.Print("ReturnValue: {0}", outParams("ReturnValue"))
CreateRestorePoint = 1
Catch err As ManagementException
Debug.Print(String.Format("An error occurred while trying to execute the WMI method: {0}", err.Message))
End Try
Return CreateRestorePoint
End Function
Here's how I'm calling the function:
Dim CRP As New JSEWindowsRestore.WindowsRestoreFunctions
CRP.CreateRestorePoint(String.Format("Test Restore Point: {0}", DateTime.Now), 100, 12)
Anyone spot the problem?

Everything looks pretty good. The only thing that you need to change is ManagementObject in the first couple lines to ManagementClass.
Dim classInstance As New ManagementClass("root\DEFAULT", "SystemRestore", Nothing)
ManagementObject refers to an instance of a class and ManagementClass refers to the class itself. The path error you were receiving was because the code was expecting a path to an instance and not a class itself.
As for the green squiggly lines, they shouldn't prevent you from compiling but its possible Visual Studio will like this syntax better.
inParams.Properties("Description").Value = Description
inParams.Properties("EventType").Value = EventType
inParams.Properties("RestorePointType").Value = RestorePointType
Also, make sure the application has administrator privileges or you'll get an access denied when you try to invoke this method.

Related

Why am I receiving an ArrayTypeMismatchException error despite the providing the current return type?

I am trying to add an item to a List. However everytime I try to add something to that list I face an ArrayTypeMismatchException error with the error message being "Attempted to access an element as a type incompatible with the array".
Dim params as New List(of OracleParameter)
params.Add(OracleParameterFactory.CreateIn(usedId, OracleDbType.Varchar2))
The method "CreateIn" has a return type of OracleParameter. I'm not sure why I'm getting this error at all. Any help will be much appreciated.
Here's the definition for CreateIn
Public Shared Function CreateIn(ByVal name as String, ByVal type as OracleDbType) As OracleParameter
Dim p as New OracleParameter()
p.ParameterName = name
p.Direction = ParameterDirection.Input
p.OracleDbType = type
If type = OracleDbType.Varchar2 Then
p.Size = 4000
End If
p.Value = DBNull.Value
Return p
End Function
The same definition and implementation is working in another application without issue if that's any help.
Till now I have cleaned and rebuilt the solution, removed the System library from the project, manually deleted the bin and obj folders but nothing has yet fixed the problem.

Getentity method in vb.net + Autocad?

ACADAPP = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application")
ACADDOC = ACADAPP.Documents.ActiveDocument
second_POINT = ACADDOC.Utility.GetEntity(select_object, , "Select Object <Enter to Exit> : ")
ACADDOC.Utility.GetEntity returns an error as
type mismatch
in vb.net autocad,when I'm trying with vb6 it works fine.
What about that 2nd empty parameter - is that correct? According to the specification, it expects an object - a point.
object.GetEntity Object, PickedPoint [, Prompt]
Such as...
ThisDrawing.Utility.GetEntity returnObj, basePnt, "Prompt, i.e. Select an object"
By the way - is that really a VB.NET? Or Visual Basic for Application (VBA)? Notice, there are significant differences in syntax and capabilities... The AutoDesk general documentation (incl. online) would be for VBA, not VB.NET.
EDIT:
Dim returnObj As AcadObject
Dim basePnt As Variant
ThisDrawing.Utility.GetEntity returnObj, basePnt, "Select an object"
Note, that this example is for VBA, I've never worked with VB.NET and ACAD, I'm not even sure how it is supported.
Make sure you handle empty selection too...
Here's a simple function that will return a selected object.
The PromptEntityResult's ObjectId Property is the actual returned entity, which you will have to get to with a transaction.
Public Shared Function GetEntity() As PromptEntityResult
Dim retVal As PromptEntityResult = Nothing
Dim oDoc As Document = Core.Application.DocumentManager.MdiActiveDocument
Dim oEd As Editor = oDoc.Editor
Dim oPeo As New PromptEntityOptions(Environment.NewLine & "Please select an object")
With oPeo
.SetRejectMessage(Environment.NewLine & "Cannot select that object.")
.AllowNone = False
.AllowObjectOnLockedLayer = True
End With
retVal = oEd.GetEntity(oPeo)
Return retVal
End Function

Public member 'ToCSVValue' on type 'Integer' not found for VB Extension method

I am trying to write a ToCSV() extension in VB based on Scott Hanselman's blog. It could be that my C# to VB is not correct, but it all seems right.
I added a module with:
<System.Runtime.CompilerServices.Extension>
Public Function ToCSV(Of T)(items As IEnumerable(Of T)) As String
Try
Dim csvBuilder = New StringBuilder()
Dim properties = GetType(T).GetProperties()
For Each item As T In items
'' Test Code
Dim newline As String = ""
For Each l2 As Reflection.PropertyInfo In properties
' This works
newline &= l2.GetValue(item, Nothing)
' This works too
Dim int As Integer = 1234
Dim s As String = int.ToCSVValue()
'This works
Dim nl = l2.GetValue(item, Nothing)
' This blows up with "Public member 'ToCSVValue' on type 'Integer' not found."
' The Debugger type shows "Object {Integer}" which I assume to mean that the debugger interprets the object as an integer.
nl = nl.ToCSVValue()
Next
' Original code
Dim line As String = String.Join(",", properties.Select(Function(p) p.GetValue(item, Nothing).ToCSVValue()).ToArray())
csvBuilder.AppendLine(line)
Next
Return csvBuilder.ToString()
Catch ex As Exception
Throw
End Try
End Function
<System.Runtime.CompilerServices.Extension>
Private Function ToCSVValue(Of T)(item As T) As String
If item Is Nothing Then
Return """"""
End If
If TypeOf item Is String Then
Return String.Format("""{0}""", item.ToString().Replace("""", "\"""))
End If
Dim dummy As Double
If Double.TryParse(item.ToString(), dummy) Then
Return String.Format("{0}", item)
End If
Return String.Format("""{0}""", item)
End Function
When I call it with something like:
Dim s As String = ctx.Customers.Where(Function(x) x.CustomerID = 123456).Select(Function(x) New With {.CustomerID = x.CustomerID, .CustomerName = x.CustomerName}).ToCSV()
it gets to the function ToCSV just fine. It recognizes the items passed in. It pulls out the first item and sees that there are the 2 fields in it. All good!
The GetValue() works just fine.
If I create a static integer and call ToCSVValue on it, it works fine.
If I create a static string and call ToCSVValue on it, it works fine.
When I call ToCSVValue on the GetValue() I get:
Public member 'ToCSVValue' on type 'Integer' not found.
Likewise, if I have just strings in the dataset, I get:
Public member 'ToCSVValue' on type 'String' not found.
Ideally this would work as it is in the "Original code" section and I can kill all this other test code.
Can anyone tell me what is happening and why the "(Of T)" is not working the get GetValue() types, but it is for the directly cast types?
You need to have 'Option Infer On'.
When I use Option Infer On, it works fine.
If you don't use this, then VB is using 'Object' whenever you leave off the type.
Also, although this isn't causing your problem, the proper conversion of the ToCSV method is:
Public Function ToCSV(Of T As Class)(items As IEnumerable(Of T)) As String
The short answer is that calling it as a method ToCSVValue(p.GetValue(item, Nothing)) will work as in the C# version.
The longer answer is that you can't call extension methods on Object in VB. In VB Object is treated more like dynamic in C#. For example:
<Extension()> Function toStr(Of T)(item As T) As String
Return item.ToString
End Function
then this will result in compile-time Warning "Late bound resolution; runtime errors could occur." and a run-time Error "Public member 'toStr' on type 'Integer' not found.", but it will work in C#:
Dim i As Object = 123
Dim s = i.toStr

NullReferenceException was unhandled in small loop

Hello I recieve a "nullreferenceexception was unhandled" error when I try to run this code:
For i As Integer = 1 To aantaltags
csvopc(i) = csvtagssplit(17 * i)
csvsql(i) = csvtagssplit(17 * i + 15)
Next
Background:
I read a csv file that I clean up and split into csvtagssplit()
csvopc and csvsql are both declared as string() at the top of the program.
anything dumb I did and I'm not noticing?
replicate it if you want to:
code:
http://pastebin.com/JDPa6FSB
csv:
http://pastebin.com/2e66i9EB
Your problem is in the intial part of your code where you declare the two variables cvsopc and cvssql,
As from your comment you write
Dim csvopc As String()
Dim csvsql As String()
But this only declares the two variables without any dimension.
So when you try to reach csvopc(i) you are effectively referencing a index that doesn't exist
Why use arrays when you don't know the exact size of your elements?.
You can easily switch to a List(Of String) where you can dinamically add elements
Dim csvopc As List(Of String) = new List(Of String)
Dim csvsql As List(Of String) = new List(Of String)
and then in your loop
For i As Integer = 0 To aantaltags - 1
csvopc.Add(csvtagssplit(17 * i))
csvsql.Add(csvtagssplit(17 * i + 15))
Next
A List(Of String) could also be referenced by Index as in
Dim aValue = csvopc(0)
You should step through your code with a debugger in order to inspect the data as the code runs. You could put a breakpoint at a place where everything should be initialized but before the exception happens and then see what the values are.
Which iteration of the loop fails, and what line specifically fails? Put a breakpoint on that line and see what all the values are immediately before the line executes. If this debugging doesn't reveal the error to you, update your post with the data you find during debugging and maybe we can get somewhere.

Strange error reported in this code, please explain?

I put together this bit of code from a few other samples, and I am getting an error I cant understand. On this line in the code below, on the word Observer,
Dim Results As ManagementObjectCollection = Worker.Get(Observer)
I get the error
"Value of type 'System.Management.ManagementOperationObserver' cannot be converted to 'Integer'"
Can somebody explain what this means?
There are two signatures for ManagementObjectSearcher.Get(), one has no parameters and the other has one parameter, a ManagementOperationObserver for async operation. That is what I am providing, yet the error indicates conversion involving an integer?
Public Shared Sub WMIDriveDetectionASYNC(ByVal args As String())
Dim Observer As New ManagementOperationObserver()
Dim completionHandler As New MyHandler()
AddHandler Observer.Completed, AddressOf completionHandler.Done
Dim Machine = "192.168.0.15"
Dim Scope = New ManagementScope("\\" & Machine & "\root\cimv2")
Dim QueryString = "select Name, Size, FreeSpace from Win32_LogicalDisk where DriveType=3"
Dim Query = New ObjectQuery(QueryString)
Dim Worker = New ManagementObjectSearcher(Scope, Query)
Dim Results As ManagementObjectCollection = Worker.Get(Observer) 'use parameter to make async
For Each item As ManagementObject In Results
Console.WriteLine("{0} {2} {1}", item("Name"), item("FreeSpace"), item("Size"))
Dim FullSpace As Long = (CLng(item("Size")) - CLng(item("FreeSpace"))) \ 1000000
Console.WriteLine(FullSpace)
Next
End Sub
Public Class MyHandler
Private _isComplete As Boolean = False
Public Sub Done(sender As Object, e As CompletedEventArgs)
_isComplete = True
End Sub 'Done
Public ReadOnly Property IsComplete() As Boolean
Get
Return _isComplete
End Get
End Property
End Class
Thanks for any advice!
I think that uses a reference type to get the result and put it in the object you sent as a parameter. So I think it just needs to look like:
Worker.Get(Observer)
instead of trying to set something = to that since it isn't a function that returns a value.
Then use the events you hook up to the object to handle whatever you need to do with the items you find.