VB.NET Variable is used before - vb.net

I have usual peace of code for VB.NET, such this:
Dim ds = New DataSet
Using mCon As NpgsqlConnection = dbUtil.getConnection()
Using t As NpgsqlTransaction = mCon.BeginTransaction()
... some code ...
t.Commit()
End Using
End Using
With this code I have in "mCon.BeginTransaction()" mCon underlined with green and warning message is "Variable 'mCon' is used before it has been assigned a value. A null reference exception could result at runtime".
Why is that and how to get rid of this?

Related

Creating a Windows Restore Point?

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.

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

Reflection Optimization

I've recently implemented reflection to replace the more tedious aspects of our data retrieval from a SQL database. The old code would look something like this:
_dr = _cmd.ExecuteReader (_dr is the SQLDataReader)
While _dr.Read (_row is a class object with public properties)
_row.Property1 = Convert.ToInt16(_dr("Prop1"))
_row.Property2 = Convert.ToInt16(_dr("Prop2"))
_row.Property3 = Convert.ToInt16(_dr("Prop3"))
If IsDBNull(_dr("Prop4")) = False Then _row.Prop4 = _dr("Prop4")
...
Since my code base has a lot of functionality like this, reflection seemed like a good bet to simplify it and make future coding easier. How to assign datareader data into generic List ( of T ) has a great answer that was practically like magic for my needs and easily translated into VB. For easy reference:
Public Shared Function GenericGet(Of T As {Class, New})(ByVal reader As SqlDataReader, ByVal typeString As String)
'Dim results As New List(Of T)()
Dim results As Object
If typeString = "List" Then
results = New List(Of T)()
End If
Dim type As Type = GetType(T)
Try
If reader.Read() Then
' at least one row: resolve the properties
Dim props As PropertyInfo() = New PropertyInfo(reader.FieldCount - 1) {}
For i As Integer = 0 To props.Length - 1
Dim prop = type.GetProperty(reader.GetName(i), BindingFlags.Instance Or BindingFlags.[Public])
If prop IsNot Nothing AndAlso prop.CanWrite Then
props(i) = prop
End If
Next
Do
Dim obj = New T()
For i As Integer = 0 To props.Length - 1
Dim prop = props(i)
If prop Is Nothing Then
Continue For
End If
' not mapped
Dim val As Object = If(reader.IsDBNull(i), Nothing, reader(i))
If val IsNot Nothing Then SetValue(obj, prop, val)
Next
If typeString = "List" Then
results.Add(obj)
Else
results = obj
End If
Loop While reader.Read()
End If
Catch ex As Exception
Helpers.LogMessage("Error: " + ex.Message + ". Stacktrace: " + ex.StackTrace)
End Try
Return results
End Function
The only caveat with this is that it is somewhat slower.
My question is how to optimize. Sample code I find online is all in C# and does not convert neatly into VB. Scenario 4 here seems like exactly what I want, but converting it to VB gives all kinds of errors (Using CodeFusion or converter.Telerik.com).
Has anyone done this in VB before? Or can anyone translate what's in that last link?
Any help's appreciated.
Couple ideas for you.
Don't use the DataReader when reading ALL records at once, it is slower than using a DataAdapter.
When you use the DataAdapter to fill a DataSet, you can iterate through the rows and columns which does NOT use reflection and will be much faster.
I have a program I created (and many other programmers do this too) that generate the code from a database for me. Each table and row is a class that is specifically named an generated in such a way that I can use intellisense and prevents many run-time errors by making them compile-time errors when data changes. This is very much like the EntityFramework but lighter because it fits MY specific needs.

LINQ Query Causing Exit Sub or Swallowing Error

My code is as follows:
Using _EntityModel As New AboveNemaSalesDatabaseEntities()
Dim _SelectActiveOptionCodes = (From _OptCodes In _EntityModel.tblOptionCodes
Where _OptCodes.fdStatus = "A"
Select _OptCodes.fdDescription, _OptCodes.fdOptionCode).ToList()
Dim _SelectActiveOptionCodes2 = (From _OptCodes In _EntityModel.tblOptionCodes
Where _OptCodes.fdStatus = "A"
Select New optionCodes With {.description = _OptCodes.fdDescription,
.optionCode = _OptCodes.fdOptionCode})
sortableOptionCodes = _SelectActiveOptionCodes2
sortedOptionCodes = _SelectActiveOptionCodes2
OptionCodeListBox.DataSource = sortedOptionCodes
OptionCodeListBox.DisplayMember = "fdDescription"
OptionCodeListBox.ValueMember = "fdOptionCode"
End Using
The first query works fine and returns a list in the format [index]{description = "descritption here", optionCode = "option code here"}
The second query creates but when it is called to save to my custom class the program exits the sub or swallows an error. Stepping through the code, the line starting with sortedOptionCodes and after never runs.
The main issue I was dealing with is that my query was producing a list of optionCodes and my variable was not prepared to store this.
Old variables:
Dim sortableOptionCodes As optionCodes
Dim sortedOptionCodes As optionCodes
New variables:
Dim sortableOptionCodes As List(Of optionCodes)
Dim sortedOptionCodes As List(Of optionCodes)
I also added a .ToList() function to the end of the second query.

Vb.net Code syntax error

I have following vb.net code and i am getting syntax error in it
Update
Protected Sub OpenLogin_Click(ByVal src As Object, ByVal e As CommandEventArgs)
Dim StrUri As String = e.CommandArgument.ToString()
Dim openid As New OpenIdRelyingParty()
Dim b = New UriBuilder(Request.Url)
With Key
.Query = ""
End With
'var b = new UriBuilder(Request.Url) { Query = "" };
Dim req = openid.CreateRequest(StrUri)
Dim fetchRequest = New FetchRequest()
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last)
req.AddExtension(fetchRequest)
req.RedirectToProvider()
End Sub
Now the error in code is "Key is Not declared" What should i do now for this
Two problems:
The Key reserved word is only to be used when identifying a multi-part key for grouping using Enumerable.GroupBy. It is not required for setting object properties inline with their constructor.
You are experiencing a problem whereby you have separated the With decorator onto a new line, which is syntactically incorrect because you are now treating it as a With block, which means that every dot access will target the variable immediately following the With statement. You need to use a line continuation character or put With on the same line as the object constructor:
Ex 1
Dim b = New UriBuilder(Request.Url) With {
.Query = ""
}
Ex 2
Dim b = New UriBuilder(Request.Url) _
With { .Query = "" }
EDIT:
You cannot use this syntax with a Visual Studio 2005/.NET 2.0 project. Just construct the object then initialize the property:
Dim b As New UriBuilder(Request.Url)
b.Query = ""
AFAIK, you don't need the curly braces.
With Something
.Property1 = True
.Property2 = "Inactive"
' And so on
End With
UPDATE
With Key
.Query = ""
End With
Why do you need a With clause here anyway ? The above is syntactically equivalent to
Key.Query = ""
Declare the Key variable or else remove it from your code.