My StreamReader ReadLine is reading every other line - vb.net

I am looping through a text file and reading and then parsing each line.. then, inserting into a sql server. The problem is, I am getting every other line. Any thoughts?
I read another post on here that is similar and it says that that person was calling the ReadLine twice... which makes sense. I just cannot spot where it is happening.
Private Sub btnUpdateRSR_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdateRSR.Click
' Get RSR File
lblStatus.Text = "Getting RSR File"
Application.DoEvents()
If chkDLRSR.Checked = True Then
ftpGetRSR()
End If
Application.DoEvents()
lblStatus.Text = "Got RSR File"
' Whack existing data
killRSRData()
' Run Update of Invnetory
Dim sCmd As New SqlCommand()
Dim fp As StreamReader
Dim MyFile As String = String.Empty
Dim dblRecordCount As Double
Try
'Open file with StreamReader
fp = File.OpenText("c:\ct_info\rsr.txt")
Catch err As Exception
lblStatus.Text = "File Read Failed! Reason: " & err.ToString()
End Try
sCmd.Connection = New System.Data.SqlClient.SqlConnection("Data Source=vortx-sql01.vortx.com;Initial Catalog=expresspolicesupply;Persist Security Info=True;User ID=expresspolicesupply;Password=blahblah")
sCmd.Connection.Open()
Dim strArr() As String
While String.IsNullOrEmpty(fp.ReadLine) = False ' fp.ReadLine.IsNullOrEmpty = False
MyFile = fp.ReadLine
strArr = MyFile.Split(";")
'Show what is in the second position of the array.
'MessageBox.Show(strArr(1))
Try
Dim RSRstocknumber As String = strArr(0)
Dim UPCcode As String = strArr(1)
Dim ProductDescription As String = Replace(strArr(2), "'", """")
Dim DepartmentNumber As String = strArr(3)
Dim ManufacturerID As String = strArr(4)
Dim RetailPrice As String = strArr(5)
Dim RSRRegularPrice As String = strArr(6)
Dim Weight As String = strArr(7)
Dim InventoryQuantity As String = strArr(8)
Dim Model As String = Replace(strArr(9), "'", """")
Dim FullManufacturerName As String = Replace(strArr(10), "'", """")
Dim ManufacturerPartNo As String = strArr(11)
Dim AllocatedCloseoutDeleted As String = strArr(12)
Dim ExpandedProductDescription As String = Replace(strArr(13), "'", """")
Dim ImageName As String = strArr(14)
lblStatusPrevious.Text = "Previous one: " & lblStatus.Text
lblStatus.Text = strArr(0)
Application.DoEvents()
With sCmd
.CommandText = "INSERT into rsr (rsrstocknumber, upccode, productDescription, departmentnumber, ManufacturerID, RetailPrice, RSRRegularPrice, Weight, InventoryQuantity, Model, FullManufacturerName, ManufacturerPartNo, AllocatedCloseoutDeleted, ExpandedProductDescription, ImageName) " & _
" Values('" & RSRstocknumber & "', '" & UPCcode & "', '" & ProductDescription & "', '" & DepartmentNumber & "', '" & ManufacturerID & "', '" & _
RetailPrice & "', '" & RSRRegularPrice & "', '" & Weight & "', '" & InventoryQuantity & "', '" & Model & "', '" & FullManufacturerName & "', '" & ManufacturerPartNo & "', '" & _
AllocatedCloseoutDeleted & "', '" & ExpandedProductDescription & "','" & ImageName & "');"
'MessageBox.Show(sCmd.CommandText.ToString)
.CommandType = CommandType.Text
.ExecuteNonQuery()
' Update record counter
dblRecordCount = dblRecordCount + 1
lblRecordCount.Text = dblRecordCount
Application.DoEvents()
End With
Catch ex As Exception
lblErrorLabel.Text = "Error on thown on " & lblRecordCount.Text
'MessageBox.Show("Error occurred! Details: " & ex.Message)
End Try
End While
fp.Close() 'Close file with StreamReader
sCmd.Connection.Close()
lblStatus.Text = "Updating website for RSR"
lblStatusPrevious.Text = ""
spUpdateRSR()
lblStatus.Text = "Done"
lblStatusPrevious.Text = ""
End Sub

That's because you're calling ReadLine() twice.
Every other line gets swallowed by String.IsNullOrEmpty(fp.ReadLine) = False.

You are calling ReadLine twice.
While String.IsNullOrEmpty(fp.ReadLine) = False ' fp.ReadLine.IsNullOrEmpty = False
MyFile = fp.ReadLine
Once in the IsNullOrEmpty check and once on MyFile = fp.ReadLine

This line is reading the file, and then you read the next one in the while loop:
While String.IsNullOrEmpty(fp.ReadLine) = False
You are calling it twice :)
You need to use this to check whether it is the end of the file:
While fp.EndOfStream = False

Related

Shows Error Conversion from String to type Double is not Valid, Input String is not in correct Format

Following are my codes Pls Help me
I found this error on updating the Table
Private Sub UpdateInventory()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MainConString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim Query1 As String
Try
Dim Result As DialogResult
Result = MessageBox.Show(" Update this Record ?", "Save ! ", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Result = DialogResult.Yes Then
For J As Integer = 0 To DataGridStock.Rows.Count - 1 Step +1
Query1 = "Update Tempstock Set Type='" & LabelTrancode.Text & "', Prefix='" & Lblprefix.Text & "', Srl='" & TextINVNo.Text & "',
DOcDate='" & TextBoxdocdate.Text & "',Sno='" & DataGridStock.Rows(J).Cells(0).Value & "', Hsncode='" & DataGridStock.Rows(J).Cells(4).Value & "',
Branch='" & LBLBranchcode.Text & "',Taxcode='" & DataGridStock.Rows(J).Cells(5).Value & "',Code='" & DataGridStock.Rows(J).Cells(2).Value & "',
Qty='" + (DataGridStock.Rows(J).Cells(6).Value) + "',Rate='" + Int(DataGridStock.Rows(J).Cells(8).Value) + "',Unit='" & DataGridStock.Rows(J).Cells(7).Value & "'"
Dim query = String.Concat(Query1, ";")
con.Open()
cmd = New SqlCommand(query, con)
reader = cmd.ExecuteReader
reader.Close()
con.Close()
Next
MessageBox.Show(" Stock Updated")
End If
Catch ex As Exception
End Try
End Sub

Update query makes the fields empty in the database

I asked a question previously concerning updating data in a datagridview with phpMyAdmin. You can refer to it by following link -->Updating data in phpmyadmin part 1
The code works quite OK, but now the problem is that when I check for the updated data in localhost all I see are empty fields. Below is the screenshot of my vb in design. I have labelled the textboxes as per my database. The textboxes in the screenshot are set to be invisible on running my winform.
What exactly could be the problem?
#Kakarot
Here is what I initially had
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim rabit As MySqlDataReader
MysqlConn.Open()
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET (Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "') WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
Try
con = New MySqlCommand(pin, MysqlConn)
rabit = con.ExecuteReader
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
And here is what I currently have (credit goes to one Mr. ekad for it)
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET Employee_ID = #Employee_ID, Nat_ID = #Nat_ID, First_Name = #First_Name, Middle_Name = #Middle_Name, Surname = #Surname, NSSF_No = #NSSF_No, KRA_Pin = #KRA_Pin, NHIF_No = #NHIF_No, Residence = #Residence, Mobile_No = #Mobile_No, Email = #Email, Job_Group = #Job_Group, Employment_Date = #Employment_Date WHERE Employee_ID like '%{0}%'"
Try
Using MysqlConn As New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
MysqlConn.Open()
Using con As New MySqlCommand(pin, MysqlConn)
With con
con.Parameters.AddWithValue("#Employee_ID", txtemployeeid.Text)
con.Parameters.AddWithValue("#Nat_ID", txtnatid.Text)
con.Parameters.AddWithValue("#First_Name", txtfirstname.Text)
con.Parameters.AddWithValue("#Middle_Name", txtmiddlename.Text)
con.Parameters.AddWithValue("#Surname", txtsurname.Text)
con.Parameters.AddWithValue("#NSSF_No", txtnssfno.Text)
con.Parameters.AddWithValue("#KRA_Pin", txtkrapin.Text)
con.Parameters.AddWithValue("#NHIF_No", txtnhifno.Text)
con.Parameters.AddWithValue("#Residence", txtresidence.Text)
con.Parameters.AddWithValue("#Mobile_No", txtmobileno.Text)
con.Parameters.AddWithValue("#Email", txtemail.Text)
con.Parameters.AddWithValue("#Job_Group", cbojobgroup.Text)
con.Parameters.AddWithValue("#Employment_Date", dtpemploymentdate.Text)
End With
con.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
The first code gave me an error (refer to the link above). The second code works but it's emptying my fields instead of updating.
How did you updated your tables in your database? It should be like:
(Im gonna take my code for an old project that I did)
Private Sub disconnect()
conn.Close()
End Sub
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub btnSaveEdit_Click(sender As Object, e As EventArgs) Handles btnSaveEdit.Click
connect()
Dim query as string
Dim command As New MySqlCommand
query = "Update `tblcandidates` set firstname = '" & txtEditFname.Text & "', lastname = '" & txtEditLName.Text & "', position='" & cboEditPosition.Text & "', fullname = '" & fullname & "' where recNum = '" & txtRec.Text & "'"
command.Connection = conn
command.CommandText = query
command.ExecuteNonQuery()
disconnect()
End Sub
First things first, just a simple question, is heavisa_database.new_employee a table? It's really wise to properly name them, you can put tbl before your desired name if its a table, and db before the name if its a database. Just to prevents confusions. And I think you dont need a reader when updating records in your table, correct me if I'm wrong :p
Okay, to be honest, I don't really understand much the code that Mr. ekad provided. Here's a code you can try. And oh, you don't really need the bracket after the SET.
//Global Vars
Dim connectionString As String = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim conn As New MySqlConnection
First, let's make some functions for ease (you can put this anywhere in your code):
//remember that conn is our MySqlConnection
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub disconnect()
conn.Close()
End Sub
So, event for your update button:
connect()
Dim pin As String
pin = "UPDATE new_employee SET Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "' WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
//lets create new command
Dim command As New MySqlCommand
//sets the connection for our command
command.Connection = conn
command.CommandText = pin
command.ExecuteNonQuery()
disconnect()
MessageBox.Show("Record saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Try the given code above and I'm pretty sure It'll work. Goodluck!

OleDbDataReader and DataSet

How do i change this code to VB.NET? So i want to use a DataSet instead of the ADODB.Recordset and an OleDb.OleDbConnection instead of ADODB.Connection.
Set oRs = New ADODB.Recordset
oRs.Open ("Select * from Login Where Username= '" & txtUsername.Text & "'"),oCn, adOpenStatic, adLockOptimistic, _
adCmdText
If txtPassword.Text <> oRs.Fields("Password") Then
Call MsgBox("Incorrect Password", vbOKOnly, "Login Error")
txtPassword.Text = ""
txtPassword.SetFocus
Exit Sub
Else
strUserName = txtUsername.Text 'May need in the future project
strName = oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
frmInstruction.Show
This is what I have tried so far:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Login WHERE Username= '" & txtUsername.Text & "' AND password = '" & txtPassword.Text & "' ", oCn)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
If (sdr.Read() = True) Then
strUserName = txtUsername.Text
frmInstruction.Show()
'but am having issue with this line of code:
strName = oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
'but am having issue with this line of code: strName =
oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
You could use OledbDataReader.GetString to read the FirstName and LastName fields:
Dim firstName = sdr.GetString(sdr.GetOrdinal("FirstName"))
Dim lastName = sdr.GetString(sdr.GetOrdinal("LastName"))
strName = firstName & " " & lastName

ACCESS DENIED error from stream file open

I have create my code in order to write images in a remote sql server
All the details of accessing and writing are fine until now, including the system account right now i'm in the command of:
SqlFileStream = New SqlFileStream(filePathName, fileToken, FileAccess.Write)
and when i'm trying to execute it the Server returns the error 'Access denied' I have try all the posible ( those which i know) combinations to overcome this error but nothing Please give me the best assistance you may have
I've put a sniffer in my PC to lookup the packages between Server and my PC, so here what i got: the first addres is the Server address and the second is my PC address.
*"10.93.1.29","10.93.1.10","SMB","Tree Connect AndX Request, Path: \DEVELOPER\SQLEXPRESS "
"10.93.1.10","10.93.1.29","SMB","Tree Connect AndX Response"
"10.93.1.29","10.93.1.10","SMB","Trans2 Request, QUERY_PATH_INFO, Query File Basic Info, Path: \v1\RemoteDB\dbo\tPImages\tPImages_Image\DB6F1B11-2FAF-4326-8E44-FBA71DA94CEC\b8010a0f1aaf47c1888aab2e830dff43"
"10.93.1.10","10.93.1.29","SMB","Trans2 Response, QUERY_PATH_INFO, Error: STATUS_ACCESS_DENIED"
"10.93.1.29","10.93.1.10","SMB","NT Trans Request, NT CREATE"
"10.93.1.10","10.93.1.29","SMB","NT Trans Response, NT CREATE, FID: 0x0000, Error: STATUS_ACCESS_DENIED"*
I dare to say that this error comes from the Windows program when the SQL 2008 tries to write some DATA to the filies which creates on C:\sqlRemData..... (but finally i'm not sure even for that)
PLEASE if anyone knows?
Try this..
public static bool SetAcl(string filename, string account)
{
FileSystemAccessRule rule = new FileSystemAccessRule(account, FileSystemRights.Write, AccessControlType.Allow);
PermissionSet fp = new PermissionSet(PermissionState.Unrestricted);
fp.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, new string[] { filename }));
fp.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.PathDiscovery, new string[] { filename }));
fp.Assert();
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(filename));
bool what = false;
DirectorySecurity security = di.GetAccessControl();
security.ModifyAccessRule(AccessControlModification.Add, rule, out what);
di.SetAccessControl(security);
return what;
}
Public Sub WriteFileStream(ByVal imSource As Byte(), ByVal imSize As Integer, ByVal imTy As Type, ByVal sender As Object, ByVal e As EventArgs)
Dim subProvider As String = Nothing
Dim subDataSource As Object = Nothing
Dim subUid As String = Nothing
Dim subPwd As String = Nothing
Dim subDataBase As String = Nothing
Dim subPSI As Boolean = Nothing
Dim ParamXML() As String = Nothing
Dim TypeOfServer As String = "Remote"
Dim imParam(3) As String
Dim imTable(1) As String
Dim RemoteSQLcmd As SqlCommand = New SqlCommand
Dim tokenReader As SqlDataReader
'-------------------------------------------------'
Dim AbsRecord As Int64 = 0
Dim VarString(10) As String
Dim VarInt(10) As Integer
'-------------------------------------------------'
ParamXML = Split(loadXmlFile(TypeOfServer, sender, e), "|")
subUid = ParamXML(3)
subProvider = ParamXML(0)
subDataSource = ParamXML(1)
subDataBase = ParamXML(2)
subPwd = ParamXML(4)
subPSI = ParamXML(5)
Dim SchemaID As String = Convert.ToInt16(ParamXML(8))
Dim SchemaName As String = Nothing
If SchemaID = 1 Then
SchemaName = subUid
ElseIf SchemaID = 2 Then
SchemaName = "dbo"
ElseIf SchemaID = 0 Then
SchemaName = "dbo"
End If
'-------------------------------------------------'
imTable(0) = "tPDetails"
imTable(1) = "tPImages"
Try
imParam(0) = Me.TextBox1.Text.Trim.ToString 'Name'
imParam(1) = Me.TextBox2.Text.Trim.ToString 'Code'
imParam(2) = Me.TextBox3.Text.Trim.ToString 'Price'
imParam(3) = Me.TextBox4.Text.Trim.ToString 'Comments'
'========================================================'
If RemoteSQLConn.State = ConnectionState.Open Then RemoteSQLConn.Close()
SQL_Connection(TypeOfServer, TypeOfServer & "Conn.xml", sender, e)
RemoteSQLConn.open()
'----------------------'
Dim imHolder As Image = Image.FromStream(imStream)
Dim imHeight As Integer = imHolder.Height
Dim imWidth As Integer = imHolder.Width
Dim imLength As Integer = imHolder.PropertyItems.Length
Dim imType As Type = imTy
'----------------------'
Dim FirstColumnNames As String = _
imTable(0) & "_Code, " & _
imTable(0) & "_Price, " & _
imTable(0) & "_Title, " & _
imTable(0) & "_Type, " & _
imTable(0) & "_Height, " & _
imTable(0) & "_Width, " & _
imTable(0) & "_Stock, " & _
imTable(0) & "_Comments "
Dim FirstFieldsValues As String = "'" & imParam(1) & "', '" & _
imParam(2) & "', '" & _
imParam(0) & "', '" & _
imType.ToString & "', '" & _
imHeight & "', '" & _
imWidth & "', '" & _
"0', '" & _
imParam(3) & "' "
'--------------------------------------------'
RemoteSQLcmd = New SqlCommand("INSERT INTO " & _
SchemaName & "." & imTable(0) & " (" & FirstColumnNames & ") VALUES (" & FirstFieldsValues & ") ", RemoteSQLConn)
RemoteSQLcmd.ExecuteNonQuery()
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("SELECT * FROM " & SchemaName & "." & imTable(0) & _
" WHERE " & imTable(0) & "_Code = " & "'" & imParam(1) & "'", RemoteSQLConn)
AbsRecord = RemoteSQLcmd.ExecuteScalar
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("INSERT INTO " & SchemaName & "." & imTable(1) & " VALUES (newid(), " & AbsRecord & ", CAST('' as varbinary(max)))", RemoteSQLConn)
RemoteSQLcmd.ExecuteNonQuery()
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("SELECT " & imTable(1) & "_Image.PathName() FROM " & _
SchemaName & "." & imTable(1) & " WHERE " & imTable(1) & "_" & imTable(0) & "_ID = " & AbsRecord, RemoteSQLConn)
Dim filePathName As String = Nothing
Dim pathObj As Object = RemoteSQLcmd.ExecuteScalar()
'-------------------------------------------------- Path Name '
If Not pathObj.Equals(DBNull.Value) Then
filePathName = DirectCast(pathObj, String)
Else
Throw New System.Exception("Image.PathName() failed to read the path name for the Image column.")
End If
'-------------------------- GET_FILESTREAM_TRANSACTION_CONTEXT()'
Dim RemoteSQLtx As SqlTransaction = RemoteSQLConn.BeginTransaction("MainTranaction")
RemoteSQLcmd.Transaction = RemoteSQLtx
RemoteSQLcmd = New SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", RemoteSQLConn, RemoteSQLtx)
Dim tokenObject As Object = RemoteSQLcmd.ExecuteScalar()
'-------------------------------------- File Token '
tokenReader = RemoteSQLcmd.ExecuteReader(CommandBehavior.SingleRow)
tokenReader.Read()
Dim txContext As SqlBinary = DirectCast(tokenObject, Byte())
tokenReader.Close()
'-----------------------------------------------'
Try
'-------------------- Closing all connections'
If RemoteSQLConn.State = ConnectionState.Open Then RemoteSQLConn.Close()
If RemoteSQLcmd.Connection.State = ConnectionState.Open Then RemoteSQLcmd.Connection.Close()
If RemoteConnInfo.State = ConnectionState.Open Then RemoteConnInfo.Close()
RemoteSQLtx.Dispose()
'---------- Opening all connections for Indegrated Security'
ChangeLoginPerson("PRINCIDEVEL\Administrator")
RemoteConnInfo.ConnectionString = "Provider=" & subProvider & "; Data Source=" & subDataSource & _
"; Database=" & subDataBase & "; Integrated Security=" & "SSPI" & "; Persist Security Info=" & subPSI
RemoteSQLcmd.Connection.Open()
RemoteSQLConn = New SqlConnection("Server=" & subDataSource & "; Integrated Security=TRUE" & "; database=" & subDataBase)
RemoteSQLConn.Open()
RemoteSQLtx = RemoteSQLConn.BeginTransaction("MainTranaction")
RemoteSQLcmd.Transaction = RemoteSQLtx
'------------------------- Write in to file stream ---------------'
Dim imImage As Byte() = New Byte(imStream.Length) {}
Dim bytesRead As Integer = imStream.Read(imImage, 0, imStream.Length)
Dim sqlFile As New SqlFileStream(filePathName, txContext, FileAccess.ReadWrite, FileOptions.WriteThrough, 0)
Dim numBytes As Integer = 0
Dim unicode As Encoding = Encoding.GetEncoding(0)
While bytesRead > 0
sqlFile.Write(imImage, 0, bytesRead)
bytesRead = imStream.Read(imImage, 0, imSize)
End While
RemoteSQLtx.Commit()
RemoteSQLcmd.Transaction.Commit()
sqlFile.Close()
Catch FsEx As Exception
MessageBox.Show(FsEx.Message, "Write in SQL File Stream ", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finally
End Try
'--------------------------------------------------'
Catch ex As Exception
MessageBox.Show(ex.Message, "WriteFileStream ", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finalize()
Finally
RemoteSQLConn.Close()
imStream.Close()
End Try
End Sub

Open File Stream Win API

I'm trying to use the
OpenSqlFilestream
Instruction but my code did not recognise it
What dll i have to load in order to use it?
Dear marc_s look at my code
Public Sub WriteFileStream(ByVal imSource As Byte(), ByVal imSize As Integer, ByVal imTy As Type, ByVal sender As Object, ByVal e As EventArgs)
Dim subProvider As String = Nothing
Dim subDataSource As Object = Nothing
Dim subUid As String = Nothing
Dim subPwd As String = Nothing
Dim subDataBase As String = Nothing
Dim subPSI As Boolean = Nothing
Dim ParamXML() As String = Nothing
Dim TypeOfServer As String = "Remote"
Dim imParam(3) As String
Dim imTable(1) As String
Dim RemoteSQLcmd As SqlCommand = New SqlCommand
Dim tokenReader As SqlDataReader
'-------------------------------------------------'
Dim AbsRecord As Int64 = 0
Dim VarString(10) As String
Dim VarInt(10) As Integer
'-------------------------------------------------'
ParamXML = Split(loadXmlFile(TypeOfServer, sender, e), "|")
subUid = ParamXML(3)
subProvider = ParamXML(0)
subDataSource = ParamXML(1)
subDataBase = ParamXML(2)
subPwd = ParamXML(4)
subPSI = ParamXML(5)
Dim SchemaID As String = Convert.ToInt16(ParamXML(8))
Dim SchemaName As String = Nothing
If SchemaID = 1 Then
SchemaName = subUid
ElseIf SchemaID = 2 Then
SchemaName = "dbo"
ElseIf SchemaID = 0 Then
SchemaName = "dbo"
End If
'-------------------------------------------------'
imTable(0) = "tPDetails"
imTable(1) = "tPImages"
Try
imParam(0) = Me.TextBox1.Text.Trim.ToString 'Name'
imParam(1) = Me.TextBox2.Text.Trim.ToString 'Code'
imParam(2) = Me.TextBox3.Text.Trim.ToString 'Price'
imParam(3) = Me.TextBox4.Text.Trim.ToString 'Comments'
'========================================================'
If RemoteSQLConn.State = ConnectionState.Open Then RemoteSQLConn.Close()
SQL_Connection(TypeOfServer, TypeOfServer & "Conn.xml", sender, e)
RemoteSQLConn.open()
'----------------------'
Dim imHolder As Image = Image.FromStream(imStream)
Dim imHeight As Integer = imHolder.Height
Dim imWidth As Integer = imHolder.Width
Dim imLength As Integer = imHolder.PropertyItems.Length
Dim imType As Type = imTy
'----------------------'
Dim FirstColumnNames As String = _
imTable(0) & "_Code, " & _
imTable(0) & "_Price, " & _
imTable(0) & "_Title, " & _
imTable(0) & "_Type, " & _
imTable(0) & "_Height, " & _
imTable(0) & "_Width, " & _
imTable(0) & "_Stock, " & _
imTable(0) & "_Comments "
Dim FirstFieldsValues As String = "'" & imParam(1) & "', '" & _
imParam(2) & "', '" & _
imParam(0) & "', '" & _
imType.ToString & "', '" & _
imHeight & "', '" & _
imWidth & "', '" & _
"0', '" & _
imParam(3) & "' "
'--------------------------------------------'
RemoteSQLcmd = New SqlCommand("INSERT INTO " & _
SchemaName & "." & imTable(0) & " (" & FirstColumnNames & ") VALUES (" & FirstFieldsValues & ") ", RemoteSQLConn)
RemoteSQLcmd.ExecuteNonQuery()
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("SELECT * FROM " & SchemaName & "." & imTable(0) & _
" WHERE " & imTable(0) & "_Code = " & "'" & imParam(1) & "'", RemoteSQLConn)
AbsRecord = RemoteSQLcmd.ExecuteScalar
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("INSERT INTO " & SchemaName & "." & imTable(1) & " VALUES (newid(), " & AbsRecord & ", CAST('' as varbinary(max)))", RemoteSQLConn)
RemoteSQLcmd.ExecuteNonQuery()
'--------------------------------------------------'
RemoteSQLcmd = New SqlCommand("SELECT " & imTable(1) & "_Image.PathName() FROM " & _
SchemaName & "." & imTable(1) & " WHERE " & imTable(1) & "_" & imTable(0) & "_ID = " & AbsRecord, RemoteSQLConn)
Dim filePathName As String = Nothing
Dim pathObj As Object = RemoteSQLcmd.ExecuteScalar()
'-------------------------------------------------- Path Name '
If Not pathObj.Equals(DBNull.Value) Then
filePathName = DirectCast(pathObj, String)
Else
Throw New System.Exception("Image.PathName() failed to read the path name for the Image column.")
End If
'-------------------------- GET_FILESTREAM_TRANSACTION_CONTEXT()'
Dim RemoteSQLtx As SqlTransaction = RemoteSQLConn.BeginTransaction("MainTranaction")
RemoteSQLcmd.Transaction = RemoteSQLtx
RemoteSQLcmd = New SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", RemoteSQLConn, RemoteSQLtx)
Dim tokenObject As Object = RemoteSQLcmd.ExecuteScalar()
'-------------------------------------- File Token '
tokenReader = RemoteSQLcmd.ExecuteReader(CommandBehavior.SingleRow)
tokenReader.Read()
Dim txContext As SqlBinary = DirectCast(tokenObject, Byte())
tokenReader.Close()
'-----------------------------------------------'
Try
'-------------------- Closing all connections'
If RemoteSQLConn.State = ConnectionState.Open Then RemoteSQLConn.Close()
If RemoteSQLcmd.Connection.State = ConnectionState.Open Then RemoteSQLcmd.Connection.Close()
If RemoteConnInfo.State = ConnectionState.Open Then RemoteConnInfo.Close()
RemoteSQLtx.Dispose() '.Connection.State = ConnectionState.Open Then RemoteSQLtx.Connection.Close()
'-------------------- Open connections for Indegrated Security''
ChangeLoginPerson("PRINCIDEVEL\Administrator")
RemoteConnInfo.ConnectionString = "Provider=" & subProvider & "; Data Source=" & subDataSource & _
"; Database=" & subDataBase & "; Integrated Security=" & "SSPI" & "; Persist Security Info=" & subPSI
RemoteSQLcmd.Connection.Open()
RemoteSQLConn = New SqlConnection("Server=" & subDataSource & "; Integrated Security=TRUE" & "; database=" & subDataBase)
RemoteSQLConn.Open()
RemoteSQLtx = RemoteSQLConn.BeginTransaction("MainTranaction")
RemoteSQLcmd.Transaction = RemoteSQLtx
'------------------------- Write in to file stream ---------------'
Dim imImage As Byte() = New Byte(imStream.Length) {}
Dim bytesRead As Integer = imStream.Read(imImage, 0, imStream.Length)
Dim sqlFile As New SqlFileStream(filePathName, txContext, FileAccess.ReadWrite, FileOptions.WriteThrough, 0)
Dim numBytes As Integer = 0
Dim unicode As Encoding = Encoding.GetEncoding(0)
While bytesRead > 0
sqlFile.Write(imImage, 0, bytesRead)
bytesRead = imStream.Read(imImage, 0, imSize)
End While
RemoteSQLtx.Commit()
RemoteSQLcmd.Transaction.Commit()
sqlFile.Close()
Catch FsEx As Exception
MessageBox.Show(FsEx.Message, "Write in SQL File Stream ", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finally
End Try
'--------------------------------------------------'
Catch ex As Exception
MessageBox.Show(ex.Message, "WriteFileStream ", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finalize()
Finally
RemoteSQLConn.Close()
imStream.Close()
End Try
End Sub
Do you do all the necessary steps before opening the file stream? Grabbing the context inside a transaction??
Check out this article here for a detailed discussion as to how to do it. Here's another blog post with a VB.NET sample code snippet.
Update: Lefteris, your code snippet is very very hard to read and understand, I did my best, but I'm really not sure. What I'm thinking is that you close the transaction too quickly. You seem to create a connection and a transaction to get the GET_FILESTREAM_TRANSACTION_CONTEXT, but then you close that again before you actually write out your bytes. I think the transaction should span all operations - it should start before you get the transaction context, and it should stay alive for the whole write operation, and only be committed once the whole write operation is done.
I tried to come up with a simpler code snippet to show you - it's in C#, since I couldn't convert it back to VB.NET:
public static void WriteFileStream(byte[] imSource, int imSize)
{
// use your own SQL insert command here instead
const string InsertCmd = "INSERT INTO PhotoAlbum(PhotoId, Description)" +
" VALUES(#PhotoId, #Description)";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
// create transaction here and let it stay alive!
using (SqlTransaction txn = conn.BeginTransaction())
{
using (SqlCommand cmd = new SqlCommand(InsertCmd, conn, txn))
{
cmd.Parameters.Add("#PhotoId", SqlDbType.Int).Value = photoId;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = desc;
cmd.ExecuteNonQuery();
}
SafeFileHandle handle = GetOutputFileHandle(photoId, txn);
MemoryStream inputStream = new MemoryStream(imSource);
using (FileStream dest = new FileStream(handle, FileAccess.Write))
{
byte[] buffer = new byte[BlockSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
dest.Close();
}
inputStream.Close();
// commit transaction here, after all is done
txn.Commit();
}
conn.Close();
}
}
This is adapted from the blog post SQL Server 2008 FILESTREAM Part 3: OpenSqlFileStream API - check that out by all means!