Disabling a checkbox by getting its name from a server - vb.net

It is quite a bit hard to explain what I have in mind but I will try my best...
I have an installer with a ton of checkboxes. Each checkbox is mod (modification for a game). At times mods interfere with a game and cause the game to crash. So I have to update the installer with either updated mod(s) or I have to temporarily disable the mod or mods that are causing the crashing.
What it will do is connect to a server that checks if a file contains "true or false" if it contains "true" it will execute code that does this:
Connects to a different server, gets the name of a checkbox, and does something like this:
NameOfCheckBox.Enabled = False
The thing is... I know how to do this, except the very last part.
How do I tell my program that the text it gets from the server is a name of checkbox that is located on the form?
This is my code:
Try
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://docs.google.com/document/d/1G3R0CoRG-LCXy-8jm-LcCJZJ9B0whsOJ64efjL0btc8/edit?usp=sharing")
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim status As String = sr.ReadToEnd()
Dim request2 As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://docs.google.com/document/d/1cYkhGTDEpxqltOvCSSD0Kw9J_1DG1dyJSV2qQ1Xekto/edit?usp=sharing")
Dim response2 As System.Net.HttpWebResponse = request2.GetResponse()
Dim sr2 As System.IO.StreamReader = New System.IO.StreamReader(response2.GetResponseStream())
Dim checkboxtodisable As String = sr2.ReadToEnd()
If status.Contains("True") Then
Dim chk As CheckBox
chk.Name = checkboxtodisable
chk.Enabled = False
Else
End If
Catch ex As Exception
MessageBox.Show("Unable to connect to server!")
MessageBox.Show(ex.Message)
End Try
The error I get is:
Object reference not set to an instance of an object
The error is located on this line of code:
chk.Name = checkboxtodisable

You can retrieve a control by name like this:
Dim MyCheckBox As Checkbox = Me.Controls("checkbox1")
So your code would look like this:
If status.Contains("True") Then
Dim chk as checkbox = Me.Controls(checkboxtodisable)
chk.Enabled = False
End If

Related

TCP Client-Side Not Recieveing Data Properly VB.NET

I'm trying to make a simple client-side application to recieve small text data, compare it and then does something on client machine depending on what server sent.
Server Logic: The server side is made in java, so can't change anything there. Server sends string "abc001" on connecting to client.
Client Logic: Client recieves the string "abc001" from server & checks if it's recieved string is the same as "abc001", then does something accordingly.
Problem: When the client recieves data, I display it in msgbox. But instead of just "abc001", there pops up an extra blank msgbox(image included).
Client Code - On Start:
Try
' declare vals
Dim ip As String = "127.0.0.1"
Dim port As Integer = 5000
' set client
_client = New TcpClient(ip, port)
' disable cross thread calls checking
CheckForIllegalCrossThreadCalls = False
' recieve msg
Threading.ThreadPool.QueueUserWorkItem(AddressOf RecieveMessages)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Client Code - Recieve Data
Private Sub RecieveMessages(state As Object)
Try
While True
Dim ns As NetworkStream = _client.GetStream()
Dim toRecieve(_client.ReceiveBufferSize) As Byte
ns.Read(toRecieve, 0, CInt(_client.ReceiveBufferSize))
Dim txt As String = Encoding.ASCII.GetString(toRecieve)
MsgBox(txt)
End While
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
MsgBox 1
MsgBox 2
How to not get the blank msgbox. Even when compared, the data recived does not match parameters. Tried to use delay, tried fixing the buffer size to 6 bytes but no use.. Any help is appreciated. Thanks.
EDIT 1: Tried my best to figure it out but can't.. Tried cleaning the returned string data and even tried storing each return data in array. Saw the stack and it says the msgbox has "nothing" in it. It's null.. I don't even know what to do.. Here's the code for strings clean:
Private Sub RecieveMessages(state As Object)
Dim message(0) As String
Dim command_raw, command_clean, command As String
Dim counter As Integer = 0
Try
While True
Dim ns As NetworkStream = _client.GetStream()
Dim toRecieve(_client.ReceiveBufferSize) As Byte
ns.Read(toRecieve, 0, CInt(_client.ReceiveBufferSize))
Dim txt As String = Encoding.ASCII.GetString(toRecieve)
message(0) = txt
command_raw = message(0)
command_clean = command_raw.Replace(vbCrLf, Nothing)
command = command_clean.Substring(0, 6)
MsgBox(command)
End While
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Need help getting Registry.GetValue to work correctly

I have a simple setup project that is no longer working and it seems like a windows update is the cause. I am using Visual Studio 2010 on Windows 7. The project is 64bit. It still works on some computers but it does not work on any computers that have had updates recently.
Here is the original code:
Dim appPath As String = Registry.GetValue("HKEY_CURRENT_USER\SOFTWARE\Our Company Inc.\SoftwareName.exe", "Path", "Not Found")
appPath &= "Colorbar.col"
Dim sid : sid = "S-1-1-0"
Dim objWMI : objWMI = GetObject("winmgmts://./root\cimv2")
Dim objSID : objSID = objWMI.Get("Win32_SID='" & sid & "'")
Dim userAccount As String = objSID.AccountName
Dim fileInfo As IO.FileInfo = New IO.FileInfo(appPath)
Dim fileAcl As New FileSecurity
fileAcl.AddAccessRule(New FileSystemAccessRule(userAccount, FileSystemRights.FullControl, AccessControlType.Allow))
fileInfo.SetAccessControl(fileAcl)
I have put the key value pair of "Path" and "[TARGETDIR]" in the registry editor and have the output from this installer class (the code above) in the Install and Commit custom actions.
This code that used to work now returns "Exception has been thrown by the target of an invocation -> C:\Windows\SYSWOW64\Colorbar.col"
I have checked the registry when this message appears and the path is correct so I don't know where SYSWOW64 is coming from.
I have tried to change getting the appPath using this code:
Dim regKey As RegistryKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)
regKey = regKey.OpenSubKey("SOFTWARE\Our Company Inc.\SoftwareName.exe")
Dim appPath As String = regKey.GetValue("Path").ToString
This returns an "Object reference not set to an instance of an object" error.
I have made a test Windows Form application and put both versions of code in a button event. Everything works as expected. Any ideas why the code does not work in a setup project anymore and what I can do to get it working again?
Thanks in advance.
Finally have it working again. I got around using the registry by using the custom action's CustomActionData and setting it to:
/name="[TARGETDIR]\"
I was then able to access it in my installer class by using this line of code:
Dim appPath As String = Context.Parameters.Item("name")
Once the path was set, everything else worked as expected. The final code looks like this:
Public Overrides Sub Commit(ByVal stateSaver As System.Collections.IDictionary)
MyBase.Commit(stateSaver)
Dim appPath As String = Context.Parameters.Item("name")
appPath = appPath.Remove(appPath.Length - 1)
appPath &= "Colorbar.col"
Dim sid : sid = "S-1-1-0"
Dim objWMI : objWMI = GetObject("winmgmts://./root\cimv2")
Dim objSID : objSID = objWMI.Get("Win32_SID='" & sid & "'")
Dim userAccount As String = objSID.AccountName
Dim fileInfo As IO.FileInfo = New IO.FileInfo(appPath)
Dim fileAcl As New FileSecurity
fileAcl.AddAccessRule(New FileSystemAccessRule(userAccount, FileSystemRights.FullControl, AccessControlType.Allow))
fileInfo.SetAccessControl(fileAcl)
End Sub

RDLC local report trying to render before loading datasource

I have created a local report that contains a few sub reports. I am trying to load the report straight to pdf based off the click of a button.
I have tried showing the report with report viewer and it shows up fine, but when I try to render directly to pdf I get an error about data source. When I debug the code I notice that my subprocessing function does run until after the button call function finishes and throws the error.
Dim reportParam As New ReportParameter("appId", appid)
Dim reportParam2 As New ReportParameter("appDate", appDate)
Dim reportParam3 As New ReportParameter("auditDate", Now)
Dim reportArray As New ReportParameterCollection
reportArray.Add(reportParam)
reportArray.Add(reportParam2)
reportArray.Add(reportParam3)
AddHandler ReportViewer1.LocalReport.SubreportProcessing, AddressOf SetSubDataSource
ReportViewer1.LocalReport.SetParameters(reportArray)
ObjectDataSource1.SelectParameters("appID").DefaultValue = appid
ObjectDataSource1.SelectParameters("appDate").DefaultValue = appDate
ObjectDataSource1.DataBind()
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Try
ReportViewer1.DataBind()
ReportViewer1.LocalReport.Refresh()
Dim byteViewer As Byte()
byteViewer = ReportViewer1.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
Response.Buffer = True
'Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", "attachment; filename=test.pdf")
Response.BinaryWrite(byteViewer)
Response.OutputStream.Write(byteViewer, 0, byteViewer.Length)
Response.Flush()
Response.Close()
Thanks for your advice in advance, I just trying to figure out how to get the report to load data sources before it renders and not after this function is complete.

Set a report datasource instance at run time

I have created a report that is based on a business object - this works great. I am now trying to add a button that renders the report directly to PDF (in a winforms application).
I know what I need to do - in code I am creating a ReportViewer, setting the DataSource, specifying the report (it's an embedded resource), then rendering the report into a byte array before using System.IO.File.WriteAllBytes to flush the byte array to disk. One thing I'm hung up on though, is how do I specify the instance of the object properly? I keep getting the "An error has occurred during the report processing" error. In IntelliTrace I can see that an exception is thrown "A data source instance has not been supplied for the data source 'IssRep'" (IssRep is the dataset name in the report. Here is the code:
Dim warning As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimetype As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim viewer As New ReportViewer
Dim bs As New BindingSource
bs.DataSource = issuedet
Dim rds As New ReportDataSource
rds.Value = bs
viewer.LocalReport.DataSources.Add(rds)
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.ReportEmbeddedResource = "FRSFE.SR.rdlc"
Dim pdfbytes As Byte()
Try
pdfbytes = viewer.LocalReport.Render("PDF", Nothing, mimetype, encoding, extension, streamids, warning)
File.WriteAllBytes("C:\Shared\FRS\SR.PDF", pdfbytes)
Catch ex As Exception
MsgBox(ex.Message)
End Try
I'm pretty sure whatever I'm stuck on is pretty simple as I'm very rusty on .NET but I just can't figure it out!
Try setting rds.Name = "IssRep" before adding it to viewer.LocalReport.DataSources.

Strange "IOException was unhandled"

(VB.NET, .NET 3.5)
I wrote the following function to read some text from txt file. It was working fine but now it's not. It keeps giving me this error message
"IOException was unhandled" and
" The process cannot access the file 'F:\kh_matt\ch1.txt' because it is being used by another process."
The ch1.txt is not even opened or being used by any program at all. I tried to move ch1.txt to another location (Drive D) still I got the same message error but just different location it says The process cannot access the file 'D:\ch1.txt' because it is being used by another process."
Here's my code block :
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim reader As StreamReader
Dim filelocation As String
filelocation = "F:\kh_matt\ch1.txt"
Dim chid As Integer
chid = 1
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
Else
MsgBox(filelocation, MsgBoxStyle.OkOnly)
End If
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Dim vArray() As String = MyStream.ReadToEnd.Split(CChar("$"))
MyStream.Close()
Dim count As Integer
For d As Integer = 0 To vArray.Length - 1 Step 1
If d = vArray.Length - 1 Then
Exit For
End If
InsertKh(chid, d + 1, vArray(d))
count = d + 1
Next
MsgBox("Done Inserting")
End Sub
It always points to this code :
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Where I debug and press the respective button. Can anyone point out what the problem is ? Thanks
I think this is your problem:
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
If the file exists it will open a StreamReader on it, then try and open another StreamReader on the same file, which will lock the file, causing this line:
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
to fail.
Also, some pointers:
consider using the System.IO.File.ReadAllText() method instead, much easier
if you must use streams, wrap them in a using block to ensure they're freed correctly, for example:
`
Dim vArray() As String
using (Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
{
vArray = MyStream.ReadToEnd.Split(CChar("$"))
}
(sorry if the above code isn't 100% correct, I don't write much VB.Net)
It seems you open the file twice, which is probably what's causing your error:
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
...
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Are you sure that's what you intend to do? It looks like you can remove MyStream and use reader instead. Also, you don't have to use Path.Combine, since filelocation is not relative.
Make sure that you close your stream & streamreader once you've finished reading the file, even when an exception is being thrown.
Use a try/finally block, and close the stream / streamreader in the finally block.
Thanks all for the reply. It's my mistake. I forgot to comment out my code that I wrote for testing earlier. After commenting this code out it works like before.
'If System.IO.File.Exists(filelocation) = True Then
' reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
'Else
' MsgBox(filelocation, MsgBoxStyle.OkOnly)
'End If
Have a good day.