Pass Dynamic connection string to another Windows Form (VB.NET) - vb.net

I am creating a windows application which required Dynamic Connection String in the app starting (user need to provide db credentials through a form), After entering the connection credentials user redirected to new win form
Everything is working fine but how can I pass my dynamic connection to another form.
I tried to save it to App variable but I couldn't (I think its read only)
Also I tried save it to registry but can't retrieve values.
Is there any other option available ? like writing & retrieving ConString to a text file or XML
Thanks

This how you can get and set registry values :
Public Function GetRegistryValue(ByVal KeyName As String, Optional ByVal DefaultValue As Object = Nothing) As Object
Dim res As Object = Nothing
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
res = k.GetValue(KeyName, DefaultValue)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
Return res
End Function
Public Sub SetRegistryValue(ByVal KeyName As String, ByVal _Value As Object)
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
k.SetValue(KeyName, _Value)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
k.SetValue(KeyName, _Value)
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
End Sub
It's working a 100%, If you please mark this answer as Right

Related

How do I save objects in Configuration of Winforms application?

I'm trying to implement functionality to allow the user to select his favorite forms. Favorite forms are forms he/she needs quick access to. To avoid browsing for too long through the ToolStripMenu's.
I try to save a reference to a form in the application configuration. But I'm getting the error
Value of type 'System.Windows.Forms.Form' cannot be converted to
'String'.
Public Sub SetSetting(ByVal pstrKey As String, ByVal frmFavorite As Form)
Dim keyExists As Boolean = False
For Each strKey As String In configuration.AppSettings.Settings.AllKeys
If strKey.Equals(pstrKey) Then
configuration.AppSettings.Settings.Item(pstrKey).Value = frmFavorite
keyExists = True
End If
Next
If Not keyExists Then
configuration.AppSettings.Settings.Add(pstrKey, frmFavorite)
End If
configuration.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
End Sub
You can only store string values in the application config file, no objects.
But just store the name of the Form in the config file.
When starting your application create the form via reflection like shown in this Object Factory example.
Public Class ObjectFactory
Public Shared Function CreateAnObject(ByVal ObjectName As String) As Object
Dim Assem = [Assembly].GetExecutingAssembly()
Dim myType As Type = Assem.GetType(ObjectName.Trim)
Dim o As Object = Nothing
Try
o = Activator.CreateInstance(myType)
Catch oEx As TargetInvocationException
MessageBox.Show(oEx.ToString)
End Try
Return o
End Function
End Class
...
Dim formName as String = configuration.AppSettings.Settings.Item(<YourSettingKey>)
Dim oForm As Form = _
ObjectFactory.CreateAnObject(formName)

Added functionality not showing up in a COM object

I have created a dll in VB.Net that is used in a Visual Foxpro application. Recently I added a few functions to help in sanitizing data and clearing input from a user-control and re-built the project. I am currently using Regasm to register the dll's and this seems to work fine. However when i register the dll, the new functionality does not show, making it seem like one is still using the old, previously registered dll. Is there something i'm not doing right?
Here's an excerpt of the code.
<ClassInterface(ClassInterfaceType.AutoDispatch), ProgId("LPFPasserelle.FicheEtablissement")>
Public Class FicheEtablissement
Private mCreateInstitution As New CreateInstitution
<ComRegisterFunction()>
Public Shared Sub RegisterClass(ByVal key As String)
Dim sb As StringBuilder = New StringBuilder(key)
sb.Replace("HKEY_CLASSES_ROOT\", "")
'// Open the CLSID\{guid} key for write access
Dim k As RegistryKey = Registry.ClassesRoot.OpenSubKey(sb.ToString(), True)
Dim ctrl As RegistryKey = k.CreateSubKey("Control")
ctrl.Close()
'// Next create the CodeBase entry - needed if not string named and GACced.
Dim inprocServer32 As RegistryKey = k.OpenSubKey("InprocServer32", True)
inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase)
inprocServer32.Close()
k.Close()
End Sub
<ComUnregisterFunction()>
Public Shared Sub UnregisterClass(ByVal key As String)
Dim sb As StringBuilder = New StringBuilder(key)
sb.Replace("HKEY_CLASSES_ROOT\", "")
'// Open HKCR\CLSID\{guid} for write access
Dim k As RegistryKey = Registry.ClassesRoot.OpenSubKey(sb.ToString(), True)
'// Delete the 'Control' key, but don't throw an exception if it does not exist
If k Is Nothing Then
Return
End If
k.DeleteSubKey("Control", False)
'// Next open up InprocServer32
Dim inprocServer32 As RegistryKey = k.OpenSubKey("InprocServer32", True)
'// And delete the CodeBase key, again not throwing if missing
inprocServer32.DeleteSubKey("CodeBase", False)
'// Finally close the main key
inprocServer32.Close()
k.Close()
End Sub
The function for sanitizing string data that I added is below.
Function SanitizeStringData(ByVal StringToSanitize As String)
Dim mSanitizedString As String = String.Empty
mSanitizedString = Trim(StringToSanitize)
If Trim(StringToSanitize).Contains("'") Then
mSanitizedString = Trim(StringToSanitize).Replace("'", "''")
End If
Return mSanitizedString
End Function
Not sure about your sanitizing dll/COM issue, but for your sanitize string, I don't know why you are not just using VFP's function STRTRAN()
someString = [What's goin' on]
? STRTRAN( someString, "'", "''" )
will result in
What''s goin'' on
Help on StrTran() function
Another cool one is CHRTRAN() and has a wide range of benefits from stripping invalid characters from strings to a pseudo encryption by replacing every character in a string to something else...

Form crashes when uploading file on background thread

I am trying to upload a file using a thread. I have placed a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
Method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When someone clicks on the same button simultaneously the thread behavior works in a different way, some time page crashes.
When this process I have tested on multi-user environment with 60 users and file size is 25 mb each user the page crashed.
I have to use .NET 3.5 so I cannot use the advanced version of file upload in 2010 or later.
Error : 1-File uploding is more than 15 minutes but still in progress 2- Internet explorer cannot explore the page -Diagnose Internet problems 3- some user get login probem to the server on which the site has hosted
The course I usually take in .NET is to use ThreadPool.QueueUserWorkItem
If you do this with anonymous lambdas, I find it makes the syntax and life rather nice. You can do something like this:
btnUpload.Enabled = False
ThreadPool.QueueUserWorkItem(Sub()
SaveFileByBuffering(FldUploadThreading.FileName)
RaiseEvent EnableButton
End Sub)
With this event handler:
Public Sub EnableButton() Handles EnableButton
If Me.InvokeRequired Then
Me.BeginInvoke(Sub() EnableButton())
Else
btnUpload.Enabled = True
EndIf
EndSub
My .NET is rusty and I don't have a compiler anywhere, but doing something like this should handle most of your issues.

Visual basic "Unhandled exception"

Hello I'm getting this error, while trying to save serial number to XML File.
If the file doesn't exist, it saves the file fine, but if i change Registered tag to False in Xml file, and try again, it says "The Process Cannot acces the file ... because it is being used by another process".
In my main form i read the information from XML, and in my regform (which i open if registered tag in xml is false) i write to the file. is it because of that?! I don't think so.
Here is my Registration class:
Imports System.IO
Imports System.Xml
Public Class RegistrationClass
Public Property SerialNumber As String
Public Property Registered As Boolean = False
Public Sub Write_Reg(ByVal FileString As String, ByVal RegisterName As String, ByVal RegisterCompany As String, ByVal RegisterSerialNumber As String)
Dim Registered As Boolean = False
Dim Comment As String = "StroySoft 2012 Register Database"
Dim SerialNumber As String = "dev-xxx-123"
Dim ClientOS As String = Trim(My.Computer.Info.OSFullName)
If RegisterSerialNumber = SerialNumber Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
' Initialize the XmlWriter.
Dim XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
With XmlWrt
' Write the Xml declaration.
.WriteStartDocument()
' Write a comment.
.WriteComment(Comment)
' Write the root element.
.WriteStartElement("Data")
' Start our first person.
.WriteStartElement("Register")
' The person nodes.
.WriteStartElement("Name")
.WriteString(RegisterName.ToString())
.WriteEndElement()
.WriteStartElement("Company")
.WriteString(RegisterCompany.ToString())
.WriteEndElement()
.WriteStartElement("SerialNumber")
.WriteString(RegisterSerialNumber.ToString())
.WriteEndElement()
Registered = True
.WriteStartElement("Registered")
.WriteString(Registered)
.WriteEndElement()
.WriteStartElement("ClientOS")
.WriteString(ClientOS)
.WriteEndElement()
' The end of this person.
.WriteEndElement()
' Close the XmlTextWriter.
.WriteEndDocument()
.Close()
End With
MsgBox("Успешна регистрация! Благодарим Ви!")
MainForm.РегистрацияToolStripMenuItem.Visible = False
Else
MsgBox("Невалиден сериен номер!")
End If
End Sub
Public Sub Check_Reg(ByVal FileString As String)
If (System.IO.File.Exists(FileString)) Then
Dim document As XmlReader = New XmlTextReader(RegForm.RegFile)
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Registered") Then
If document.ReadInnerXml.ToString() = "True" Then
Registered = True
Else
Registered = False
End If
End If
If (document.Name = "SerialNumber") Then
SerialNumber = document.ReadInnerXml.ToString()
End If
End If
End While
Else
MessageBox.Show("The filename you selected was not found.")
End If
End Sub
End Class
is it because of that?! I don't think so.
It's exactly because of that.
You should always make sure to properly dispose IDisposable resources such as Streams and Writers/Readers by wrapping them in a Using block. In your case I don't see you closing your reader. But if you wrap it in a Using block you shouldn't worry about it. Even if an exception is thrown the resource will be properly released.
Example:
Using XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
...
End Using
You should do the same with your XmlReader:
Using document As XmlReader = XmlReader.Create(RegForm.RegFile)
...
End Using

Check proxy's from listbox

So i have a listbox that i have there for a list of proxies. I have 4 buttons pertaining to it. they are find, load, save and check
I have the first 3 finished and working but i haven't found anything useful pertaining to checking the proxies, the only one that i found took like 6 seconds per proxy so it took a lot of time for a decent sized list.
So how could i make it that on the press of that button, it checks all of the proxies in the listbox and it deletes the slow ones and the ones that flat out do not work. and does this at a decent pace(so it would probably be multi threaded)
and since i can not figure this out i have no code pertaining to this except for the sub for the button click i do not feel there is a need to post code
My suggestion for you is :
1)use a timer control and set it's Tick property to an appropriate value such 500;
2) create an array of BackGroudWorkers for example BackGroudWorker[20];
3)when your app start run all BackGroudWorkers in array and in tick event of Timer check if any of this BackGroudWorker completed or not.If completed and you have other item in list then run it with new Item.Do this until all list Items checked
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim prx As Uri = Nothing
If Uri.TryCreate(Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
ElseIf Uri.TryCreate("http://" & Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
Else
Return False
End If
End Function
Public Shared Function CheckProxy(ByVal Proxy As Uri) As Boolean
Dim iProxy As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
iProxy.ReceiveTimeout = 500 : iProxy.SendTimeout = 500
Try
'' Connect using a timeout (1/2 second)
Dim result As IAsyncResult = iProxy.BeginConnect(Proxy.Host, Proxy.Port, Nothing, Nothing)
Dim success As Boolean = result.AsyncWaitHandle.WaitOne(500, True)
If (Not success) Then
iProxy.Close() : Return False
End If
Catch ex As Exception
Return False
End Try
Dim bytData() As Byte, strData As String
Dim iDataLen As Integer = 1024
strData = String.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", "www.google.com", 80, vbNewLine)
bytData = System.Text.ASCIIEncoding.ASCII.GetBytes(strData)
If iProxy.Connected Then
iProxy.Send(bytData, bytData.Length, SocketFlags.None)
ReDim bytData(1024)
Do
Try
iDataLen = iProxy.Receive(bytData, bytData.Length, SocketFlags.None)
Catch ex As Exception
iProxy.Close() : Return False
End Try
If iDataLen > 0 Then
strData = System.Text.ASCIIEncoding.ASCII.GetString(bytData)
Exit Do
End If
Loop
Else
Return False
End If
iProxy.Close()
Dim strAttribs() As String
strAttribs = strData.Split(" "c)
If strAttribs(1).Equals("200") Then
Return True
Else
Return False
End If
End Function
You should manage your code for threads etc, as suggested by #Nima for your proxy checking problem I have 2 methods here One asks proxy string and tries to connect it.
e.g.
ProxyStatus = CheckProxy("http://192.168.1.1:8080/")
ProxyStatus is True/False depending on if proxy works or Not