send each PDF file in separate email automatically using VB - asp.net

I'd like to ask you for some help with my problem.
I'm trying to automate sending emails with attachement separately using VB
There is a folder with few PDF files to attache to the mail
the file name start with a code of 4 digits XXXX_*
this code is the one to use to get the email from the DATABASE and every time I try to send an email it sends for all the recipient all the files
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New Net.Mail.MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(TextBox3.Text, TextBox4.Text)
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = TextBox1.Text
e_mail = New Net.Mail.MailMessage()
e_mail.From = New MailAddress(TextBox3.Text)
'get users emails
Dim SQL As String = "SELECT EMail , code FROM [SagePaieSQL].[dbo].[T_SAL] WHERE EMail IS NOT NULL and MatriculeSalarie IS NOT NULL"
Dim dir As String = "C:\Users\Administrateur\Desktop\fiche_de_ paie\"
Dim output As New List(Of String)()
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
Dim dr As DataRow
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Using sda As New SqlDataAdapter(cmd)
Using ds As New DataTable()
sda.Fill(ds)
sqLdr = cmd.ExecuteReader()
For i = 0 To ds.Rows.Count - 1
dr = ds.Rows(i)
Console.WriteLine(i)
e_mail.To.Add(dr("EMail").ToString())
e_mail.Subject = TextBox6.Text
e_mail.IsBodyHtml = False
e_mail.Body = (TextBox7.Text)
Dim files As String() = IO.Directory.GetFiles(dir, dr("code") & "_*")
If files.Any = False Then
MsgBox("bulltin non trouver ")
Exit Sub
Else
Button1.Enabled = False
For Each file As String In files
Dim fileName As String = IO.Path.GetFileName(file)
Dim attach As New Net.Mail.Attachment(file)
e_mail.Attachments.Add(attach)
If e_mail.Attachments.Any = True Then
MsgBox("file attached")
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Else
MsgBox("bulltin non attacher ")
End If
Next
End If
Next
End Using
End Using
Catch error_t As Exception
MsgBox(error_t.ToString)
End Try

Related

Create report dynamically using ParameterFields

I have to create crystal report dynamically by using ParameterFields. - In that a single parameter have to call particular row from MySQL database dynamically. Now I called multiple values from MySql database static and single.
I need to call particular row(dynamically) from MySQL database.
Dim sql_Sel As String
Dim hIssId As Integer = 0
Dim connectionInfo1 As New ConnectionInfo()
Dim SqlCon As String = "Data source= *****"
hIssId = Request.QueryString("patID")
Try
CrystLabl.ReportSource = Nothing
Me.SqlCon.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("xyz").ConnectionString
Me.SqlCon.Open()
Dim crystalReport As New ReportDocument()
sql_Sel = "exec DI_Details #opt=1"
Dim DA As SqlDataAdapter = New SqlDataAdapter(sql_Sel, SqlCon)
Dim DG As New DataSet
DG.DataSetName = "DataSet.xsd"
DA.Fill(DG, "DataTable1")
Dim paramFields3 As New CrystalDecisions.Shared.ParameterFields()
For Each i As String In sql_Sel
Dim paramField31 As New CrystalDecisions.Shared.ParameterField()
Dim discreteVal1 As New CrystalDecisions.Shared.ParameterDiscreteValue()
discreteVal1 = New ParameterDiscreteValue()
paramField31.ParameterFieldName = "My Parameter"
discreteVal1.Value = ((DG.Tables(0).Rows(0).Item(1)) & (DG.Tables(0).Rows(0).Item(2)) & (DG.Tables(0).Rows(0).Item(3)) >(DG.Tables(0).Rows(0).Item(6)))
paramField31.CurrentValues.Add(discreteVal1)
paramFields3.Add(paramField31)
Next
CrystLabl.ParameterFieldInfo = paramFields3
CrystLabl.ReportSource = "CrystalReport.rpt"
CrystLabl.RefreshReport()
Catch ex As Exception
Finally
End Try
End Sub

itextsharp pdfsmartcopy only returning last page

I have an issue where only the last page of my pdf is stored.
The pdf should be multiple pages long, and this works fine if I just send the pdf to the browser using Response and the mms memory stream, however I need to add it as a pdf to an email and therefore are writing mms to bytes to create a new memorystream when I create my email attachment. This is to get around the closed stream error.
This is my code
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Dim p As String
Dim reader As PdfReader
Dim mms As New MemoryStream
Dim rt() As Byte
Dim i As Integer = 0
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, System.Web.HttpContext.Current.Response.OutputStream)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using ms As New MemoryStream
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
ms.Flush()
End Using
reader = New PdfReader(ms.ToArray)
sc.AddPage(sc.GetImportedPage(reader, 1))
mms = ms
End Using
Next
End With
End Using
End Using
Dim bt() As Byte = mms.ToArray
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
I'm not sure of your exact problem but I'm pretty sure your life would be easier if you broke you giant function into smaller more specific functions that do only one thing. Also, I really recommend never writing to the raw ASP.Net stream until after you've created a PDF. Instead, always write to a MemoryStream, grab the bytes and do something with them.
The code below break it into four functions. CreatePdf() loops through the database and calls CreateSinglePdf() for each row in the table, merging them with your PdfSmartCopy. SendEmail() is blissfully unaware of iTextSharp completely and just receives a raw array of bytes that is assumed to be a PDF. This is all kicked off by SendPrePackLabels() which is where you'd probably want to also Response.BinaryWrite() your bytes.
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim bt = CreatePdf(bf_id)
Return SendEmail(bt, mail)
End Function
Public Shared Function CreateSinglePdf(dr As DataRow) As Byte()
Using ms As New MemoryStream
Using pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
Dim p As String
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function CreatePdf(ByVal bf_id As String) As Byte()
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Using ms As New System.IO.MemoryStream
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, ms)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pageBytes = CreateSinglePdf(dr)
Using reader = New PdfReader(pageBytes)
sc.AddPage(sc.GetImportedPage(reader, 1))
End Using
Next
End With
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function SendEmail(bt As Byte(), mail As String) As Boolean
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function

Web form to console application with timer

i have created a code in asp.net webform
now i want this code to be run in console application
but i don't know
how to invoke my timer
and where to place the code
can someone help me to convert
these code into a console application
Dim con1 As New SqlConnection(_start)
Dim sql12 As String = "SELECT Auction.AuctionID FROM Item INNER JOIN Auction ON Item.ItemID = Auction.ItemID Where Auction.Status='Valid' AND Auction.EndDate<=#endate "
Dim cmd12 As New SqlCommand(sql12, con1)
con1.Open()
cmd12.Parameters.AddWithValue("#endate", DateTime.Now)
Dim query As Integer = cmd12.ExecuteScalar
Dim sql123 As String = "UPDATE Auction SET Status ='Expired' WHERE AuctionID =#auction"
Dim cmd21 As New SqlCommand(sql123, con1)
cmd21.Parameters.AddWithValue("#auction", query)
cmd21.ExecuteNonQuery()
CalculateWinningPrice(query)
WinningBet()
timer1.Enabled = True
Public Sub CalculateWinningPrice(ByVal query As Integer)
Dim price As Integer
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (AuctionID = #auction)"
Dim cmd1 As New SqlCommand(sql1, con1)
cmd1.Parameters.AddWithValue("#auction", query)
Dim max As Double = Convert.ToDouble(cmd1.ExecuteScalar)
Dim cmd2 As New SqlCommand("SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (BiddingPrice <( SELECT MAX(BiddingPrice) AS Expr2 FROM BID AS BID_1 WHERE (AuctionID = #auction)))", con1)
cmd2.Parameters.AddWithValue("#auction", query)
Dim second As Double = Convert.ToDouble(cmd2.ExecuteScalar)
Dim cmd3 As New SqlCommand("SELECT BuyerID FROM BID WHERE(BiddingPrice =(SELECT MAX(BiddingPrice) AS Expr1 FROM BID AS BID_1 WHERE(AuctionID = #auction)))", con1)
cmd3.Parameters.AddWithValue("#auction", query)
Dim Buyer As Integer = Convert.ToInt32(cmd3.ExecuteScalar)
If max - second = 1 Then
price = second
Else
If max - second > 10 Then
price = second + 1
Else
If max - second > 100 Then
price = second + 10
Else
If max - second > 1000 Then
price = second + 1000
End If
End If
End If
End If
Dim cmd As New SqlCommand("INSERT INTO BID VALUES(#Date, #BiddingPrice,#Status,#AuctionID,#BuyerID,#WinningPrice)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#BiddingPrice", max)
cmd.Parameters.AddWithValue("#Status", "Won")
cmd.Parameters.AddWithValue("#AuctionID", query)
cmd.Parameters.AddWithValue("#BuyerID", Buyer)
cmd.Parameters.AddWithValue("#WinningPrice", price)
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Using
End Sub
then calculate winning price
Private Sub WinningBet()
Dim Email As String
Dim auction1 As Integer = Convert.ToInt32(lblauction.Text)
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT TOP (1) Member.Email, BID.BidID FROM BID INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN Member ON Buyer.MemberID = Member.MemberID WHERE(Auction.AuctionID = #auction) and (BID.WinningPrice <>0) ORDER BY BID.BidID DESC"
Dim sqlcommand As New SqlCommand(sql1, con1)
sqlcommand.Parameters.AddWithValue("#auction", auction1)
Email = sqlcommand.ExecuteScalar()
End Using
Dim [to] As String = Email
Dim from As String = "virgoplaza11#gmail.com"
Dim password As String = ""
Dim subject As String = "BID"
Dim body As String = "Your bid has been Successfull Login to shoppingCart to Make Payment"
Dim email1 As New Thread(Sub() SendEmail1([to], from, password, subject, body))
email1.IsBackground = True
email1.Start()
End Sub
Private Sub SendEmail1(ByVal [to] As String, ByVal from As String, ByVal password As String, ByVal subject As String, ByVal body As String)
Using mm As New MailMessage(from, [to])
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential(from, password)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
End Using
End Sub
To use the Forms timer:
Add a reference to System.Windows.Forms
Imports System.Windows.Forms
For the Web.UI timer:
Add references to System.Web and System.Web.Extensions
Imports System.Web.UI
At module level declare the new timer:
Dim timer1 As New Timer

ASP.NET/VB.NET/SQL Server 2012 - Page keeps loading

I'm trying to run this code, and whenever I press the 'Register' button, nothing is happening (the page is like loading but stays on the same page)
Code:
Public Sub register()
Dim Username As String = txtUsername.Text
Dim Surname As String = txtSurname.Text
Dim Password As String = txtPassword.Text
Dim Name As String = txtName.Text
Dim Address1 As String = txtAddress1.Text
Dim Address2 As String = txtAddress2.Text
Dim City As String = txtCity.Text
Dim Email As String = txtEmail.Text
Dim Country As String = drpCountry.Text
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.Text
Dim WorkLocation As String = txtWorkLocation.Text
Dim Age As Integer = Date.Today.Year - calDOB.SelectedDate.Year
Dim ProjectManager As String = "N/A"
Dim TeamLeader As String = "N/A"
Dim TeamLeaderID As Integer = "1"
Dim ProjectManagerID As Integer = "1"
Dim RegistrationDate As Date = DateTime.Today
Dim ContractType As String = "N/A"
Dim ContractDuration As Integer = 6
Dim Department As String = "N/A"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
Dim validateSQL As SqlCommand
Dim sqlValidate As String
sqlValidate = "SELECT * FROM users where username=" + txtUsername.Text.ToString
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
validateSQL = New SqlCommand(sqlValidate, conn)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
If dr.HasRows = False Then
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.CommandText = sqlValidate
Dim reader As SqlDataReader = validateSQL.ExecuteReader()
reader.Read()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
registerSQL.Parameters.AddWithValue("#p2", Password)
registerSQL.Parameters.AddWithValue("#p3", Name)
registerSQL.Parameters.AddWithValue("#p4", Surname)
registerSQL.Parameters.AddWithValue("#p5", Address1)
registerSQL.Parameters.AddWithValue("#p6", Address2)
registerSQL.Parameters.AddWithValue("#p7", City)
registerSQL.Parameters.AddWithValue("#p8", Country)
registerSQL.Parameters.AddWithValue("#p9", DOB)
registerSQL.Parameters.AddWithValue("#p10", Age)
registerSQL.Parameters.AddWithValue("#p11", Occupation)
registerSQL.Parameters.AddWithValue("#p12", Department)
registerSQL.Parameters.AddWithValue("#p13", WorkLocation)
registerSQL.Parameters.AddWithValue("#p14", ProjectManager)
registerSQL.Parameters.AddWithValue("#p15", TeamLeader)
registerSQL.Parameters.AddWithValue("#p16", TeamLeaderID)
registerSQL.Parameters.AddWithValue("#p17", ProjectManagerID)
registerSQL.Parameters.AddWithValue("#p18", RegistrationDate)
registerSQL.Parameters.AddWithValue("#p19", ContractType)
registerSQL.Parameters.AddWithValue("#p20", ContractDuration)
registerSQL.ExecuteNonQuery()
conn.Close()
ElseIf dr.HasRows = True Then
lblUsername.Text = "That Username (" + txtUsername.Text + ") is already registered/taken."
lblUsername.Visible = True
conn.Close()
End If
End Sub
Button event handler:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Is something wrong with the code?
From MSDN
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
It appears that you have the SqlDataReader open when you try to execute the insert command.
I will try to close it before using the insert command
If dr.HasRows = False Then
dr.Close()
' The following lines are probably a remainder of a copy/paste operation'
' They are not needed and you should remove them'
'validateSQL = New SqlCommand(sqlValidate, conn)'
'validateSQL.CommandText = sqlValidate'
'Dim reader As SqlDataReader = validateSQL.ExecuteReader()'
'reader.Read()'
' Now execute the insert command
Also your command to check for the user presence, apart from perfomance arguments, is wrong because introduces Sql Injection possibilities.
Summarizing try with these changes....
sqlValidate = "SELECT * FROM users where username=#uname"
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.Parameters.AddWithValue("#uname", txtUserName.Text)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
Dim userFound = dr.HasRows
dr.Close()
if userFound = False then
......

Sqlbulkcopy using ASP works in iis6 but fails in iis7

I am able to get sqlbulkcopy working well on iis6(testing server) and iis7(live server) but when uploading the data in iis7, the rows are cut off. It only imports ~190,000 out of 250000 in iis7. In iis 6 using the same code/page it loads all 250000 records without issues. Also both servers are updating the same SQL DB.
I have searched all over for a solution. Any help is much appreciated.
Sub UpdateData()
Dim sSQLTable As String = "Table1"
Dim sExcelFileName As String = savePath
Dim sWorkbook() As String = GetExcelSheetNames(sExcelFileName)
'Create our connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sExcelFileName & ";Extended Properties=""Excel 12.0;HDR=YES;"""
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(ConnString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)
OleDbConn.Open()
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & sWorkbook(0) & "]"), OleDbConn)
Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString, SqlBulkCopyOptions.UseInternalTransaction)
bulkCopy.BulkCopyTimeout = 2000
bulkCopy.DestinationTableName = sSQLTable
'DEMO bulkCopy.ColumnMappings.Add("Excel", "SQL")
bulkCopy.ColumnMappings.Add("Material", "Material")
bulkCopy.ColumnMappings.Add("Plnt", "Plant")
bulkCopy.ColumnMappings.Add("SLoc", "SLoc")
bulkCopy.ColumnMappings.Add("S", "S")
bulkCopy.ColumnMappings.Add("Batch", "Batch")
bulkCopy.ColumnMappings.Add("Special Stock Number", "SpecialStockNumber")
bulkCopy.ColumnMappings.Add("Material Description", "MatDesc")
bulkCopy.ColumnMappings.Add("Typ", "Type")
bulkCopy.ColumnMappings.Add("StorageBin", "StorageBin")
bulkCopy.ColumnMappings.Add("Available stock", "AvailStock")
bulkCopy.ColumnMappings.Add("BUn", "BUn")
'bulkCopy.ColumnMappings.Add("GR Date", "GRDate")
bulkCopy.WriteToServer(dr)
OleDbConn.Close()
End Sub
Thanks Andy for the ExcelDataReader tip!
Got it to work with ExcelDataReader. Looks like it was a memory issue with OleDB. Posting my code in case it will help others in future.
Sub updateData()
Dim sSQLTable As String = "Table1"
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(ConnString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
Dim stream As FileStream = File.Open(savePath, FileMode.Open, FileAccess.Read)
'1. Reading from a binary Excel file ('97-2003 format; *.xls)
'Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateBinaryReader(stream)
'2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
'3. DataSet - The result of each spreadsheet will be created in the result.Tables
'Dim ds As DataSet = excelReader.AsDataSet()
'4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = True
Dim ds As DataSet = excelReader.AsDataSet()
Dim sourceData As New DataTable()
sourceData = ds.Tables(0)
''5. Data Reader methods
'Using destinationConnection As New SqlConnection(ConnString)
' open the connection
'destinationConnection.Open()
'Using bulkCopy As New SqlBulkCopy(destinationConnection.ConnectionString)
' column mappings
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString, SqlBulkCopyOptions.UseInternalTransaction)
bulkCopy.BulkCopyTimeout = 2000
bulkCopy.DestinationTableName = sSQLTable
'DEMO bulkCopy.ColumnMappings.Add("Excel", "SQL")
bulkCopy.ColumnMappings.Add("Material", "Material")
bulkCopy.ColumnMappings.Add("Plnt", "Plant")
bulkCopy.ColumnMappings.Add("SLoc", "SLoc")
bulkCopy.ColumnMappings.Add("S", "S")
bulkCopy.ColumnMappings.Add("Batch", "Batch")
bulkCopy.ColumnMappings.Add("Special Stock Number", "SpecialStockNumber")
bulkCopy.ColumnMappings.Add("Material Description", "MatDesc")
bulkCopy.ColumnMappings.Add("Typ", "Type")
bulkCopy.ColumnMappings.Add("StorageBin", "StorageBin")
bulkCopy.ColumnMappings.Add("Available stock", "AvailStock")
bulkCopy.ColumnMappings.Add("BUn", "BUn")
'bulkCopy.ColumnMappings.Add("GR Date", "GRDate")
'bulkCopy.DestinationTableName = sSQLTable
bulkCopy.WriteToServer(sourceData)
'6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close()
End Sub

Resources