Coderush plugin not generating correct try catch end try block - vb.net

We've created a little plugin to add a block of xml comment and create a try-catch to a function. (we simply add this to each and every function we write)
But with the latest devexpress update I'm having a problem with the following code.
Private Sub cpAddComment_Apply(ByVal sender As System.Object, ByVal ea As DevExpress.CodeRush.Core.ApplyContentEventArgs) Handles cpAddXMLCommentAndTryCatch.Apply
' create elementbuilder and add current code to it
Dim objMethod As New Method
objMethod = objOldMethod.Clone()
objElementBuilder.AddStatement(Nothing, objMethod)
' add try
Dim objTry As DevExpress.CodeRush.StructuralParser.Try = objElementBuilder.AddTry(objMethod)
Dim objCatch As DevExpress.CodeRush.StructuralParser.Catch = objElementBuilder.AddCatch(objMethod, "Exception", "ex")
' add exception
Dim strErrorString As String = """Error in " + objMethod.Location + """, ex"
Dim objThrow As New DevExpress.CodeRush.StructuralParser.Throw
Dim objException As New DevExpress.CodeRush.StructuralParser.TypeReferenceExpression("Exception")
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression(strErrorString)
Dim objNewException As New DevExpress.CodeRush.StructuralParser.ObjectCreationExpression(objException)
objNewException.AddArgument(objExceptionString)
objThrow.Expression = objNewException
'objThrow.AddFooter(" ") 'This isnt working either
objElementBuilder.AddThrow(objCatch, objThrow)
' substitute code
Dim newCode As String = objElementBuilder.GenerateCode()
ea.TextDocument.Replace(objOldMethod.Range, newCode, "Update Method", True)
end sub
Instead of generating a correct Try-catch block it generates the following incorrect code:
Try
Catch ex As Exception
Throw New Exception("Error in test", ex)End Try
Strangely enough the following code seems to work(its about the same code but then for event handlers to show a messagebox instead of an exception)
If not CodeRush.Language.ActiveExtension.DotNetLanguageType = DotNetLanguageType.CSharp Then
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression("Messagebox.Show(" + strErrorString + ")" + vbCrLf)
objElementBuilder.AddStatement(objCatch, objExceptionString)
Else
This problem exists in Vb.Net but in C# the brackets are correctly placed.

I have reproduced your issue and registered it in DevExpress Support Center. You are welcome to track its status here. Once it is fixed, you can request a build containing the fix from the Support Team at support # devexpress.com. For now, as a work-around, you can replace this line of code:
objThrow.Expression = objNewException
into this:
objThrow.Expression = New SnippetExpression(CodeRush.Language.GenerateExpressionCode(objNewException) + vbCrLf)
This will generate the try/catch block correctly in Visual Basic.

Related

vb.net How to declare thread and call functions with it

I'm trying to use a thread to translate every text found in the Windows Forms to make my system multi-language.
I have a separate class named 'Language' with a sub and a function, sub reads a language source file, and function translates by receiving and returning a string.
Then I have my first Windows Form where I declare my thread:
Dim ThreadTraductor As New Thread(AddressOf ...) 'don't know how to do it
Dim cultureInfo As New System.Globalization.CultureInfo(ConfigurationManager.AppSettings('en').ToString)
ThreadTraductor.CurrentCulture = cultureInfo
ThreadTraductor.CurrentUICulture = cultureInfo
Basically I'm creating this thread to have a background process translating every Windows Form that's opened during execution, problem is I don't know how to declare it properly since I don't want to include any parameter when declaring, but I want the thread to be called from different Forms with parameters to translate, and also I want the thread to use my translate method inside Language class, is that possible? How?
Please assist, I haven't use threads before.
Public Class Lenguaje 'Class used to read language source file and translate strings
Public dicIdioma As New Dictionary(Of String, String)
Public Sub LeerArchivo(ByVal Culture As String)
Dim vectorAux() As String
dicIdioma.Clear()
Try
Dim LectorArchivo As New StreamReader("C:\Users\Joaqo\Desktop\Dorian VB\DorianBdBv1.0\UI\bin\Debug\" + Culture + ".txt")
Dim line As String
While Not LectorArchivo.Peek = -1
line = LectorArchivo.ReadLine()
vectorAux = line.Split(":")
dicIdioma.Add(vectorAux(0), vectorAux(1))
End While
Catch ex As System.IO.FileNotFoundException
MessageBox.Show("No se encuentra el archivo de idioma.")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Function Traducir(ByRef frase As String) As String
Dim StringAux As String
For Each Item As String In dicIdioma.Keys
If Item = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
ElseIf Item.Replace("_", " ") = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
End If
Next
Return frase
End Function
End Class
Then I iterate every text object in my Windows Forms to translate them:
For Each Item As Label In Me.Controls.OfType(Of Label)()
Item.Text = Traductor.Traducir(Item.Text)
Next
For Each Item As Button In Me.Controls.OfType(Of Button)()
Item.Text = Traductor.Traducir(Item.Text)
Next
And it works just fine, but I'd be calling Traductor, Lenguaje's instance declared on my first interface, from the whole app, isn't that wrong somehow?
I was told that I should use Culture and CultureUI for this, but I'm not familiarized with that. What do you think? Sorry if I'm missing something, it's my first question here.

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

How do I upload data to a server with valid SSL certificate using a client vb.net program?

I am working on a program and uploads a shipping manifest to a the shippers website. When I try to upload, I get a nondescript error back from their server, and when checking with the shipper, they tell me that "there is an issue with the SSL" I am using.
I've spent quite a bit of time piecing together code that, from what I seem to understand, is supposed to work, but I'm not making any progress. As far as I know everything else is fine with the upload, but there is a problem with my SSL certificate
If I understand what this code is supposed to do correctly, I should get a certificate from the shippers website, which allows certification to my program for a space of time during which I can upload the data. I'm really not sure that this is what my code is doing at all, but the only code examples I have seen show it something like this.
Here's my code with the URLs changed:
'This references a custom class that compiles the manifest I'm going to upload
Dim StringToUpload As String = Compile_Manifest(MyDate, UseTestDB)
Dim webClient As New System.Net.WebClient
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials
'From what I understand,
'this is supposed to set up properties used in next section of code
System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3
System.Net.ServicePointManager.ServerCertificateValidationCallback = _
AddressOf AcceptAllCertifications
'I can see that this reaches the server,
'but I don't know how it relates to the next section of code
'that actually uploads the manifest
Dim ServerRequest As System.Net.WebRequest = _
System.Net.WebRequest.Create("https://www.certify.some-shippper.com:443/somefolder")
Dim ServerResponse As System.Net.WebResponse
ServerResponse = ServerRequest.GetResponse()
ServerResponse.Close()
'This code works for the upload of the manifest,
'and it seems the above code is unrelated and does not use a SSL certificate.
'When this code runs I get the same error back from the shippers server,
'indicating an issue with my SSL, with or without the two sections of code above.
Dim StrResult As String = ""
Dim WrappedString As String = TransmitPLD.WrapPldFile(StringToUpload)
'This references a custom class that wraps the data to upload
'in information from the shipper.
Dim ByesToUpload As Byte() = _
System.Web.HttpUtility.UrlEncodeToBytes(WrappedString, _
System.Text.ASCIIEncoding.ASCII)
Dim Result As Byte() = _
webClient.UploadData("https://www.certify.some-shippper.com:443/somefolder", _
ByesToUpload)
StrResult = System.Web.HttpUtility.UrlDecode(Result, _
System.Text.ASCIIEncoding.ASCII)
MessageBox.Show(StrResult)
So it turns out I went about it the wrong way. I needed to upload my data through System.Net.WebRequest and it takes care of the certificates for me. Not implementing all the parts of the code I needed, it didn't handle the retrieval of the shipper's certificate.
In case anyone else gets confused about the matter like I did, here's my working code for anyone to see, adapt and use. My resource for fixing the code (and by that I mean starting from scratch) was the MSDN page for the WebRequest class, and it has code examples much the same as what I have below in C++, C#, and VB.NET and here is the link.
First there are some global variables that need to be set and class that needs to be created for to store the upload response:
' This is set in the function that Upload function
' and uploads the data in the ReadCallback sub
Private Shared WrappedString As String
' This is used to wait for the callback in the Upload function
Private Shared allDone As New Threading.ManualResetEvent(False)
Friend Class RequestState
' This class stores the request state of the request.
Public request As Net.WebRequest
Public Sub New()
request = Nothing
End Sub ' New
End Class ' RequestState
Then there is a sub needed for the upload part web request which will be called further below in the upload function:
Private Shared Sub ReadCallback(asynchronousResult As IAsyncResult)
Try
Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
Dim myWebRequest As Net.WebRequest = myRequestState.request
' End the request.
Dim streamResponse As IO.Stream = myWebRequest.EndGetRequestStream(asynchronousResult)
' Convert the string into a byte array.
Dim byteArray As Byte() = System.Text.Encoding.ASCII.GetBytes(WrappedString)
' Write the data to the stream.
streamResponse.Write(byteArray, 0, byteArray.Length)
streamResponse.Close()
' Allow the main thread to resume.
allDone.Set()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
End Sub ' ReadCallback
Finally, this is the function that should be called to upload the data, which uses all the code above:
Public Shared Function Upload(ByVal MyDate As Date) As String
Dim StrResult As String = ""
UploadSucess = False
Try
' This is my code that builds the manifest that I want to upload
Dim StringToUpload As String = Compile_PLD200(MyDate)
WrappedString = TransmitPLD.WrapPldFile(StringToUpload)
Dim myWebRequest As Net.WebRequest
myWebRequest = Net.WebRequest.Create("https://www.some.website.com:443/someplace")
' Create an instance of the RequestState and assign
' myWebRequest to it's request field.
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
myWebRequest.ContentType = "multipart/mixed; boundary=BOUNDARY"
myRequestState.request.Method = "POST"
' Start the asynchronous 'BeginGetRequestStream' method call.
Dim r As IAsyncResult = CType(myWebRequest.BeginGetRequestStream(AddressOf ReadCallback, myRequestState), IAsyncResult)
' Pause the current thread until the async operation completes.
allDone.WaitOne()
' Send the Post and get the response.
Dim myWebResponse As Net.WebResponse = myWebRequest.GetResponse()
Dim streamResponse As IO.Stream = myWebResponse.GetResponseStream()
Dim streamRead As New IO.StreamReader(streamResponse)
Dim readBuff(256) As [Char]
Dim count As Integer = streamRead.Read(readBuff, 0, 256)
While count > 0
Dim outputData As New [String](readBuff, 0, count)
Console.WriteLine(outputData)
count = streamRead.Read(readBuff, 0, 256)
StrResult += outputData
End While
' Close the Stream Object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse Resource.
myWebResponse.Close()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
Return StrResult
End Function ' Upload
Again here is the MSDN page for the WebRequest class which has a code example too.
Hope this helps anyone who was stuck like I was. And any criticisms as to the implementation of the code are welcome. This just happen to do what I want, I can't say it is the most efficient implementation.

VB.Net Threading and Saving Results

I'm working on the program for work, where the user is able to search AD for a asset tag of a certain computer. If it is found it will give them a list in a listbox. I have all of that working, but when they do the search the UI freezes. I'm new to VB and OO for that matter. I understand that it is freezing because the search is running on the same thread as the UI, but I cannot for the life of me get another thread to do the work. When I tried to do the search in another thread I can't update the listbox because its not on the same thread. Any help would be greatly appreciated.
Function that searches AD:
Private Function searchAd()
'clear the results from previous entries
' AdResultListBox.Items.Clear()
Try
Dim rootEntry As New DirectoryEntry("GC://mydomaininfo")
Dim searcher As New DirectorySearcher(rootEntry)
'selects the Computer Name property
searcher.PropertiesToLoad.Add("cn")
Dim compname As String = PropertyTagTextbox.Text
'searches using wildcards
compname = "*" + compname + "*"
searcher.Filter = "(&(name=" + compname + ")(objectcategory=moreADinformation))"
Dim results As SearchResultCollection
results = searcher.FindAll()
Dim result As SearchResult
For Each result In results
'this is the part i'm having trouble with
Me.AdResultListBox.Items.Add(result.Properties("cn")(0)
Next
Catch ex As Exception
End Try
End Function
Private Sub ADSearchButton_Click(sender As Object, e As RoutedEventArgs) Handles ADSearchButton.Click
AdResultListBox.Items.Clear()
'create the new thread for searching
Dim SearchThread As New Thread(AddressOf searchAd)
SearchThread.Start()
End Sub
There happens to be an MSDN article "Using System.DirectoryServices to Search the Active Directory" which shows running it in another thread at http://msdn.microsoft.com/en-us/library/ms973834.aspx#dotnetadsearch_topic9.
This is how I typically do it. The Invoke function is part of the control and that passes a delegate to the UI thread so it can be processed in the correct thread.
Invoke(Sub
Me.AdResultListBox.Items.Add(result.Properties("cn")(0)
End Sub)
http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx

VB.Net Sockets Invoke

I am using vb.net 2010 and I have created a program that uses sockets to transfer data between our windows server and a unix server. The code was originally from a Microsoft sample project hence my little understanding of it.
Everything was fine until I had the idea of changing the program into a service. The Invoke command is not accessable from a service. I think I understand why but more importantly how do I get around it or fix it?
' need to call Invoke before can update UI elements
Dim args As Object() = {command, data}
Invoke(_processInStream, args)
Someone please help I am desperate to finish this program so I can move on :)
Below is the rest of the class, there is a server socket class too but I didnt want to complicate things?
Public Class srvMain
' start the InStream code to receive data control.Invoke callback, used to process the socket notification event on the GUI's thread
Delegate Sub ProcessSocketCommandHandler(ByVal command As NotifyCommandIn, ByVal data As Object)
Dim _processInStream As ProcessSocketCommandHandler
' network communication
Dim WithEvents _serverPRC As New ServerSocket
Dim _encryptDataIn() As Byte
Dim myConn As SqlConnection
Dim _strsql As String = String.Empty
Protected Overrides Sub OnStart(ByVal args() As String)
' watch for filesystem changes in 'FTP Files' folder
Watch()
' hookup Invoke callback
_processInStream = New ProcessSocketCommandHandler(AddressOf ProcessSocketCommandIn)
' listen for Ultimate sending signatures
_serverPRC.Start(My.Settings.listen_port_prc)
myConn = New SqlConnection(My.Settings.Mill_SQL_Connect)
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub
' this is where we will break the data down into arrays
Private Sub processDataIn(ByVal data As Object)
Try
If data Is Nothing Then
Throw New Exception("Stream empty!")
End If
Dim encdata As String
' decode to string and perform split(multi chars not supported)
encdata = Encoding.Default.GetString(data)
_strsql = encdata
myConn.Open()
Dim commPrice As New SqlCommand(_strsql, myConn)
Dim resPrice As SqlDataReader = commPrice.ExecuteReader
'********************************THIS MUST BE DYNAMIC FOR MORE THAN ONE NATIONAL
If resPrice.Read = True And resPrice("ats" & "_price") IsNot DBNull.Value Then
'If resPrice("ats" & "_price") Is DBNull.Value Then
' cannot find price so error
'natPrice = ""
'natAllow = 2
'End If
natPrice = resPrice("ats" & "_price")
natAllow = resPrice("ats" & "_allow")
Else
' cannot find price so error
natPrice = ""
natAllow = 2
End If
myConn.Close()
' substring not found therefore must be a pricing query
'MsgBox("string: " & encdata.ToString)
'natPrice = "9.99"
Catch ex As Exception
ErrHandle("4", "Process Error: " + ex.Message + ex.Data.ToString)
Finally
myConn.Close() ' dont forget to close!
End Try
End Sub
'========================
'= ServerSocket methods =
'========================
' received a socket notification for receiving from Ultimate
Private Sub ProcessSocketCommandIn(ByVal command As NotifyCommandIn, ByVal data As Object)
' holds the status message for the command
Dim status As String = ""
Select Case command
Case NotifyCommandIn.Listen
'status = String.Format("Listening for server on {0} ...", CStr(data))
status = "Waiting..."
Case NotifyCommandIn.Connected
'status = "Connected to Ultimate" ' + CStr(data)
status = "Receiving..."
Case NotifyCommandIn.Disconnected
status = "Waiting..." ' disconnected from Ultimate now ready...
Case NotifyCommandIn.ReceivedData
' store the encrypted data then process
processDataIn(data)
End Select
End Sub
' called from socket object when a network event occurs.
Private Sub NotifyCallbackIn(ByVal command As NotifyCommandIn, ByVal data As Object) Handles _serverPRC.Notify
' need to call Invoke before can update UI elements
Dim args As Object() = {command, data}
Invoke(_processInStream, args)
End Sub
End Class
Any help is appreciated
Many thanks
Invoke is a member of System.Windows.Forms.Form, and it is used to make sure that a certain method is invoked on the UI thread. This is a necessity in case the method in question touches UI controls.
In this case it looks like you simply can call the method directly, i.e.
instead of
Dim args As Object() = {command, data}
Invoke(_processInStream, args)
you can simply write
ProcessSocketCommandIn(command, data)
Also, in this case you can get rid of the _processInStream delegate instance.