VB.NET project threading issue - wpf

If ServerVersion > localVersion Then
Net.ServicePointManager.DefaultConnectionLimit = 20
Dim url As New Uri(sUrlToReadFileFrom)
Dim request As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
Dim response As System.Net.HttpWebResponse = CType(request.GetResponse(), System.Net.HttpWebResponse)
response.Close()
Dim iSize As Int64 = response.ContentLength
Dim iRunningByteTotal As Int64 = 0
Using client As New System.Net.WebClient()
Using streamRemote As System.IO.Stream = client.OpenRead(New Uri(sUrlToReadFileFrom))
Using streamLocal As Stream = New FileStream(sFilePathToWriteFileTo, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)
Dim iByteSize As Integer = 0
Dim byteBuffer(iSize - 1) As Byte
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Do While iByteSize > 0
streamLocal.Write(byteBuffer, 0, iByteSize)
iRunningByteTotal += iByteSize
Dim dIndex As Double = CDbl(iRunningByteTotal)
Dim dTotal As Double = CDbl(byteBuffer.Length)
Dim dProgressPercentage As Double = (dIndex / dTotal)
Dim iProgressPercentage As Integer = CInt(Math.Truncate(dProgressPercentage * 100))
bgDownloader.ReportProgress(iProgressPercentage)
iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)
Loop
streamLocal.Close()
End Using
streamRemote.Close()
End Using
End If
Using the above code in a BackgroundWorker on a VB.NET WPF Project. An error occurs when I try to start the code.
The calling thread cannot access this object because a different thread owns it.
This code works perfectly in WinForms project without any edits/modifications.

Thanks to #Cruled for providing the clue. It has been fixed.
What I did is add invokes on all things needs updating.

Related

The size of the bytearray received to the client is different from that sent from the WCF service

I have a Self Hosted WCF service which is reading a big file with binaryreader and returning bytearray to client
Service splitting file as parts and 10MB per parts( 10485860 Bytes)
But client received 13981237 Bytes per parts, why is this difference.
This making my file is corrupt
This is my code from WCF
myblocksize = 10485860
my_bytearray = my_ibinaryreader.ReadBytes(myblocksize)
my_ibinaryreader.Close()
Return my_bytearray
and This is my client code
dim myWebClient as new WebClient
bytearray = myWebClient.DownloadData("SERVICEURL?file=bla.rar&currentPartNumber=myPartNumber")
and this is my WCF service full code
Dim i As Integer = 0
my_InStream = New System.IO.FileStream("d:\temp\" + File, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim my_ibinaryreader As System.IO.BinaryReader = New System.IO.BinaryReader(my_InStream)
Dim my_splitArr As New ArrayList
'Dim ofile As FileInfo = New FileInfo(File)
Dim ofilesize As Long = my_ibinaryreader.BaseStream.Length
Dim partcount As Integer = ofilesize \ 10485860
If ofilesize Mod 10485860 <> 0 Then partcount += 1
my_ibinaryreader.BaseStream.Position = currentPartNumber * 10485860
Dim myblocksize As Long = 0
Dim my_bytearray() As Byte
If currentPartNumber = partcount - 1 Then
myblocksize = ofilesize - (currentPartNumber * 10485860)
Else
myblocksize = 10485860
End If
my_bytearray = my_ibinaryreader.ReadBytes(myblocksize)
my_ibinaryreader.Close()
my_InStream.Close()
Return my_bytearray
#AlessandroMandelli writing bytearray into file with below code
First getting filesize from WCF that (example: 425000000 Byte - 435 MB)
and calculating partcount with filesize\104857600 (43 parts example)
and getting all parts with for statement
in WCF seeking by currentpart * 104857600
please check below code
dim myfileStream as filestream = new Filestream ("C:\aa.rar", filemode.create)
dim partcount as integer = filesize \ 104857600
dim myWebClient as new WebClient
for i as integer = 0 to partcount -1
bytearray = myWebClient.DownloadData("SERVICEURL?file=bla.rar&currentPartNumber=myPartNumber")
if not isnothing(byteArray) then
myfileStream.Write(byteArray, 0 , byteArray.length)
endif
next

VB.NET For Each Loop exits prematurely / Code returns to caller before finishing

I have two forms:
Editor
Tables
On the "Editor" form I have a "KeyDown" event which opens the "Tables" form when the F5 key is down.
Private Sub DataGridView_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView.KeyDown
Select Case e.KeyCode
Case Keys.Delete
For Each Row As DataGridViewRow In DataGridView.Rows
If Row.IsNewRow Then
DataGridView.Rows.Remove(Row)
End If
Next
Case Keys.F5
Tabels.Show()
End Select
End Sub
On the "Tables" form I have some code which get's a List(Of String) and loops through it, adding rows to a datagridview on the form.
Dim Tables As List(Of String)
Tables = NAV2013BLOBReader.ReturnXML("SELECT [Metadata] FROM dbo.[Object Metadata] WHERE [Object Type] = 1")
'Sæt egenskaber på datagridview
DataGridView.AutoGenerateColumns = False
Dim Row As DataGridViewRow = DataGridView.Rows(0).Clone()
For Each Line As String In Tables
If Line.Contains("MetaTable") Then
Dim LanguageStartIndex As Integer = Line.IndexOf("CaptionML=""") + 15
Dim LanguageEndIndex As Integer = Line.IndexOf(";", LanguageStartIndex)
Dim IdStartIndex As Integer = Line.IndexOf("ID=""") + 4
Dim IdEndIndex As Integer = Line.IndexOf(""" CaptionML") - IdStartIndex
Dim NameStartIndex As Integer = Line.IndexOf("Name=""") + 6
Dim NameEndIndex As Integer = Line.IndexOf(""" LookupFormID") - NameStartIndex
'Tildel cellerne værdier
Row.Cells(0).Value = Line.Substring(IdStartIndex, IdEndIndex)
Row.Cells(1).Value = Line.Substring(NameStartIndex, NameEndIndex)
Row.Cells(2).Value = Line.Substring(LanguageStartIndex, LanguageEndIndex - LanguageStartIndex)
DataGridView.Rows.Add(Row)
DataGridView.Refresh()
End If
Next
DataGridView.AllowUserToAddRows = False
The problem is that when the loop has iterated twice, the flow will exit the loop and go back to the KeyDown event, which then finishes.
If I empty out the code in the If Line.Contains statement, and insert a MessageBox, everything iterates just fine.
I hope someone knows the answer.
Thanks and best regards!
EDIT: I can see that DataGridView.Rows.Add(Row) is at fault, I have no idea why though.
EDIT: I fixed it by changing the "For Each" loop to a "For" loop, and cloning the latest added row.
For i = 0 To Tables.Count - 1
Dim Row As DataGridViewRow = DataGridView.Rows(i).Clone()
If Tables(i).Contains("MetaTable") Then
Dim LanguageStartIndex As Integer = Tables(i).IndexOf("CaptionML=""") + 15
Dim LanguageEndIndex As Integer = Tables(i).IndexOf(";", LanguageStartIndex)
Dim IdStartIndex As Integer = Tables(i).IndexOf("ID=""") + 4
Dim IdEndIndex As Integer = Tables(i).IndexOf(""" CaptionML") - IdStartIndex
Dim NameStartIndex As Integer = Tables(i).IndexOf("Name=""") + 6
Dim NameEndIndex As Integer = Tables(i).IndexOf("""", Tables(i).IndexOf("Name=""") + 6) - NameStartIndex
'Tildel cellerne værdier
Row.Cells(0).Value = Tables(i).Substring(IdStartIndex, IdEndIndex)
Row.Cells(1).Value = Tables(i).Substring(NameStartIndex, NameEndIndex)
Row.Cells(2).Value = Tables(i).Substring(LanguageStartIndex, LanguageEndIndex - LanguageStartIndex)
'Tilføj række til DataGridView og opfrisk kontrollen, så at de nye rækker bliver vist med det samme
DataGridView.Rows.Add(Row)
DataGridView.Refresh()
End If
Next
EDIT: I fixed it by changing the "For Each" loop to a "For" loop, and cloning the latest added row.
For i = 0 To Tables.Count - 1
Dim Row As DataGridViewRow = DataGridView.Rows(i).Clone()
If Tables(i).Contains("MetaTable") Then
Dim LanguageStartIndex As Integer = Tables(i).IndexOf("CaptionML=""") + 15
Dim LanguageEndIndex As Integer = Tables(i).IndexOf(";", LanguageStartIndex)
Dim IdStartIndex As Integer = Tables(i).IndexOf("ID=""") + 4
Dim IdEndIndex As Integer = Tables(i).IndexOf(""" CaptionML") - IdStartIndex
Dim NameStartIndex As Integer = Tables(i).IndexOf("Name=""") + 6
Dim NameEndIndex As Integer = Tables(i).IndexOf("""", Tables(i).IndexOf("Name=""") + 6) - NameStartIndex
'Tildel cellerne værdier
Row.Cells(0).Value = Tables(i).Substring(IdStartIndex, IdEndIndex)
Row.Cells(1).Value = Tables(i).Substring(NameStartIndex, NameEndIndex)
Row.Cells(2).Value = Tables(i).Substring(LanguageStartIndex, LanguageEndIndex - LanguageStartIndex)
'Tilføj række til DataGridView og opfrisk kontrollen, så at de nye rækker bliver vist med det samme
DataGridView.Rows.Add(Row)
DataGridView.Refresh()
End If
Next

Import CSV into DataGrid

In winForms adding a CSV to a DataGrid was quite easy. I am now trying to add this to a Silverlight DataGrid. Here is my attempt - which yields 3 columns Capacity|Count|Items - mind you the values are correct 83|83|_ on each row. There are 83 rows, but the columns should be 23 with diff values in each. Thanks for looking and enjoy your bounty!
Code:
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
Dim srsCol As New List(Of List(Of String))
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
While Not sr.Peek = -1
srsCol.Add(New List(Of String)(sr.ReadLine.Split(","c).ToList))
End While
End Using
End Using
dgStaff.ItemsSource = srsCol
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
I decided to use the BindableDataGrid from CodePlex Since the binding is being set dynamically I had to come up with a Random string generator and assign that for the binding and all is well.
csvDs.Tables.Clear()
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
csvDs.Tables.Add(csvDt)
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
Dim i As Integer
While Not sr.EndOfStream
If i = 0 Then
Dim cols = sr.ReadLine.Split(","c)
For ii As Integer = 0 To cols.Count - 1
Dim rndValue As String = RndColName()
Dim col As New BindableDataGrid.Data.DataColumn(rndValue)
rndValues.Add(rndValue)
col.DataType = GetType(System.String)
col.Caption = ii.ToString
col.ReadOnly = True
col.AllowReorder = False
col.AllowResize = False
col.AllowSort = False
csvDt.Columns.Add(col)
AddItemsToCb(ii)
Next
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
Dim s As String = cols(_i).Replace("""", String.Empty)
row(rndValues(_i)) = s
csvValues.Add(s)
Next
csvDt.Rows.Add(row)
Else
Dim cols = sr.ReadLine.Split(","c)
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
row(rndValues(_i)) = cols(_i).Replace("""", String.Empty)
Next
csvDt.Rows.Add(row)
End If
i += 1
End While
End Using
End Using
dgStaff.DataSource = csvDs
dgStaff.DataMember = "csvTable"
dgStaff.DataBind()

Obtain the list of open ports, windows firewall

I am trying to develop a code that manages the firewall ports using vb.net. The first part is to list all ports enabled. so I am trying this code:
Function portsList()
Dim ports As INetFwOpenPorts
Dim port As INetFwOpenPort
Dim myPorts() As INetFwOpenPorts
Dim NetFwMgrType As Type = Type.GetTypeFromProgID("HNetCfg.FwMgr", False)
Dim mgr As INetFwMgr = DirectCast(Activator.CreateInstance(NetFwMgrType), INetFwMgr)
ports = DirectCast(mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts, INetFwOpenPorts)
Dim enumerate As System.Collections.IEnumerator = ports.GetEnumerator()
Dim i As Integer
While enumerate.MoveNext()
port = DirectCast(enumerate.Current, INetFwOpenPort)
myPorts(i) = port
i += 1
End While
Dim portAsString() As String
For j As Integer = 0 To i
portAsString(j) = myPorts(j).ToString
Next
Return portAsString
End Function
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim ports() As String = portsList()
Dim n As String = ports.Length
Dim newString As String = ""
For h As Integer = 0 To n
newString = ports(h) & vbNewLine
Next
RichTextBox1.Text = newString
End Sub
What I want to do is list all the ports in Richtextbox1 after clicking Button4. The error that I am getting is:
NullReferenceException was unHandled. Object reference not set to an instance of an object.
I am new to Vb, how can I get over this?
Try this:
For port As Integer = 1 to maxPorts
Dim host As String = "192.168.1.7"
Dim hostadd As Net.IPAddress = Net.Dns.GetHostEntry(host).AddressList(0)
Dim EPhost As New Net.IPEndPoint(hostadd, port)
Dim s As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
Try
s.Connect(EPhost)
Catch
End Try
If s.Connected Then
'Port opened
Else
'Port closed
End If
Next
Here you have the complete project.

Unzip a zip file in silverlight

I am trying to develop code to unzip file from the zip file in Silverlight 5. The files are in a directory within the zip file.
I translated this code I found elsewhere from c# to VB since we are a VB shop. It is failing on the fourth line "Object reference not set to an instance of an object.".
I realize now that the problem is that the third line is expecting a relative uri and I am passing it a file, but I don't know how to fix this.
Can you tell me what is wrong with this code. I will also welcome other ideas.
Thanks.
Public Shared Function GetZipContents(ByVal filename As String) As String()
Try
Dim zipStream As System.IO.Stream = New System.IO.MemoryStream()
Dim zipInfo As New StreamResourceInfo(zipStream, Nothing)
Dim streamInfo As StreamResourceInfo = Application.GetResourceStream(zipInfo, New Uri(filename, UriKind.Relative))
Dim fileStream As Stream = streamInfo.Stream
Dim names As New List(Of String)()
Dim reader As New BinaryReader(fileStream)
Do While reader.ReadUInt32() = &H4034B50
' Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current)
Dim compressedSize As UInteger = reader.ReadUInt32()
Dim uncompressedSize As UInteger = reader.ReadUInt32()
Dim nameLength As Integer = reader.ReadUInt16()
Dim extraLength As Integer = reader.ReadUInt16()
Dim nameBytes() As Byte = reader.ReadBytes(nameLength)
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength))
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current)
Loop
' Move the stream back to the begining
fileStream.Seek(0, SeekOrigin.Begin)
Return names.ToArray()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
There is quick and dirty way to unzip in Silverlight.
Use Application.GetResourceStream Method.
http://msdn.microsoft.com/en-us/library/cc190632(v=vs.95).aspx
Check out my blogpost on this: http://www.sharpgis.net/post/2010/08/25/REALLY-small-unzip-utility-for-Silverlight-e28093-Part-2.aspx
Sorry I would have time to explore the suggestions. I did find a way to accomplish my goal on my own. See the code below. I would be using this code either because the Technical Leader here prefers I do it a different way using a WCF service. Warning I was not able to test this code 100% since I am not planning to use it, but it is close to being right.
Imports ICSharpCode.SharpZipLib.Zip
Public Shared Sub UnZip(ByVal SrcFile As String, ByVal DstFile As String, ByVal BufferSize As Integer)
Try
Dim _FileName As String
Dim _ZipEntry As ZipEntry
Dim _FileStreamOut As FileStream = Nothing
Dim _Done As Boolean = False
Dim _FileStreamIn As New FileStream(SrcFile, FileMode.Open, FileAccess.Read)
Dim _ZipInStream As New ZipInputStream(_FileStreamIn)
Do Until _Done = True
_ZipEntry = _ZipInStream.GetNextEntry()
If IsNothing(_ZipEntry) Then
_Done = True
Exit Do
End If
_FileName = DstFile & "\" & _ZipEntry.Name
_FileName = _FileName.Replace("/", "\")
If Right(_FileName, 1) = "\" Then
If Directory.Exists(_FileName) = False Then
Directory.CreateDirectory(_FileName)
End If
Else
_FileStreamOut = New FileStream(_FileName, FileMode.Create, FileAccess.Write)
Dim size As Integer
Dim buffer(BufferSize - 1) As Byte
Do
size = _ZipInStream.Read(buffer, 0, buffer.Length)
_FileStreamOut.Write(buffer, 0, size)
Loop While size > 0
End If
Loop
_ZipInStream.Close()
_FileStreamOut.Close()
_FileStreamIn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Resources