SSIS Create and Attaching file to the email - vb.net

I've 2 sqlreaders and both should loop through it and second sqlreader data should create a table and inserting into the excel sheet.
Lets say
I've sqlreader and sqlreader1
sqlreader has some data which is required to get sqlreader1
I'm able to get sqlreader1 data as I expected
but once I loaded data to datatable, I'm loosing sqlreader1 and not able to see any info in sqlreader1
If SqlDataReader.HasRows Then
Do While SqlDataReader.Read()
Dim ExcelFileName As String = Dts.Variables("User::FolderPath").Value.ToString() + "Accrual_Input_Summary_Q" + SqlDataReader.Item("Accrual_Quarter").ToString() + " FY-" + SqlDataReader.Item("Accrual_FY").ToString() + ".xlsx"
'Dim recipientName As String = SqlDataReader.Item("recipient_name").ToString()
'Dim recipientEmail As String = SqlDataReader.Item("Recipient_Email").ToString()
Try
If System.IO.File.Exists(ExcelFileName) = True Then
System.IO.File.Delete(ExcelFileName)
End If
Dim SqlCmd1 As New SqlCommand("[POT].[PROC_POT_Accrual_Reminder_Summary]", SqlCon)
SqlCmd1.CommandType = CommandType.StoredProcedure
SqlCmd1.CommandTimeout = 0
SqlCmd1.Parameters.AddWithValue("#Qtype", "Accrual_Summary")
SqlCmd1.Parameters.AddWithValue("#Accrual_Created_By_Email", SqlDataReader.Item("Recipient_Email").ToString())
Dim SqlDataReader1 As SqlDataReader = SqlCmd1.ExecuteReader()
' connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
'"Data Source=" & ExcelFileName &
'";Extended Properties=Excel 12.0 Xml;HDR=YES;"
If SqlDataReader1.HasRows Then
While SqlDataReader1.Read()
Dim connectionString As String
Dim excelConnection As OleDbConnection
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & ExcelFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"""
excelConnection = New OleDbConnection(connectionString)
Dim Excel_OLE_Cmd As OleDbCommand = New OleDbCommand()
Dim recipientName As String = SqlDataReader1.Item("Created_By_Name").ToString()
Dim recipientEmail As String = SqlDataReader1.Item("CostCenterAnalyst").ToString()
Dim costCenterOwner As String = SqlDataReader1.Item("CostCenterOwner").ToString()
Dim TableColumns As String = ""
Dim dtCustomers As New DataTable("sqlDataTable")
**dtCustomers.Load(SqlDataReader1)**
For Each column As DataColumn In dtCustomers.Columns
TableColumns += column.ToString() & "],["
Next
TableColumns = ("[" & TableColumns.Replace(",", " Text,").TrimEnd(","c))
TableColumns = TableColumns.Remove(TableColumns.Length - 2)
excelConnection.ConnectionString = connectionString
excelConnection.Open()
Excel_OLE_Cmd.Connection = excelConnection
Excel_OLE_Cmd.CommandText = "Create table " & "Sheet1" & " (" & TableColumns & ")"
Excel_OLE_Cmd.ExecuteNonQuery()
Dim sqlCommandInsert As String = ""
Dim sqlCommandValue As String = ""
For Each dataColumn As DataColumn In dtCustomers.Columns
sqlCommandValue += dataColumn.ToString() & "],["
Next
sqlCommandValue = "[" & sqlCommandValue.TrimEnd(","c)
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2)
sqlCommandInsert = "INSERT into " & "Sheet1" & "(" & sqlCommandValue & ") VALUES("
Dim columnCount As Integer = dtCustomers.Columns.Count
For Each row As DataRow In dtCustomers.Rows
Dim columnvalues As String = ""
For i As Integer = 0 To columnCount - 1
Dim index As Integer = dtCustomers.Rows.IndexOf(row)
columnvalues += "'" & dtCustomers.Rows(index).ItemArray(i).ToString() & "',"
Next
columnvalues = columnvalues.TrimEnd(","c)
Dim command As String = sqlCommandInsert & columnvalues & ")"
Excel_OLE_Cmd.CommandText = command
Excel_OLE_Cmd.ExecuteNonQuery()
Next
excelConnection.Close()
StrMailBody_Inner = " Hello Cost Center Analyst (" & recipientName & "), <br/><br/> PFA accrual inputs for the current quarter. Please review & take appropriate action click <a href='http://podashboarddev/' target='_blank'>here</a>.<br/><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <u>Note</u><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <ol>"
StrMailBody_Inner = StrMailBody_Inner + " <li>The accrual inputs provided doesn't interface with SAP. You will still need to post the necessary accrual JV.</li>"
StrMailBody_Inner = StrMailBody_Inner + " <li>CCA can leverage the tool for accrual tracking.</li>"
StrMailBody_Inner = StrMailBody_Inner + " </ol>"
Using myMessage As New MailMessage(Dts.Variables("email_from").Value, recipientEmail)
Dim copy As MailAddress = New MailAddress(costCenterOwner)
myMessage.CC.Add(copy)
myMessage.IsBodyHtml = True
myMessage.Subject = Dts.Variables("email_subject").Value
myMessage.Body = StrMailBody.ToString().Replace("$$$$Mail_Body$$$$", StrMailBody_Inner)
myMessage.Priority = System.Net.Mail.MailPriority.High
myMessage.Attachments.Add(New Attachment(ExcelFileName))
mySmtpClient = New SmtpClient("mailserver.amat.com")
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
'mySmtpClient.Send(myMessage)
Dim str_SQL As String
str_SQL = "INSERT INTO [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] ([Recipient_Email], [Reminder_Type]) VALUES ('" + SqlDataReader.Item("recipient_email").ToString() + "', 'Accrual_Summary');"
Dim SqlCmdHist As New SqlCommand(str_SQL, SqlCon)
SqlCmdHist.CommandType = CommandType.Text
SqlCmdHist.CommandTimeout = 0
SqlCmdHist.ExecuteNonQuery()
SqlCmdHist.Dispose()
End Using
End While
SqlDataReader1.Close()
End If
Once I load data to Datatable using this
dtCustomers.Load(SqlDataReader1)
before load data:
after load data:
I'm missing the sqlreader1 and i'm unable to loop through it.
it is giving Invalid attempt to call Read when reader is closed.
Note: I've enabled MultipleActiveResultSets
can we do any other things that we can do to resolve this issue

Related

Type mismatch error while using VBA

I'm using VBA and I have an error while running the attached code, it says Type mismatch.
Can someone help me where to find the mistake?
please
Private Sub List1_DblClick()
Dim val As String
Dim val2 As String
Dim i As Integer
Dim rs As ADODB.Recordset
Set GSBMconn = New ADODB.Connection
'Set rs = New ADODB.Recordset
For i = 0 To List1.ListCount - 1
If List1.Selected(i) Then
val = List1.List(i)
Debug.Print (val)
Set rs = Grid.DataSource
rs.AddNew
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=cmd\cmd.mdb;Persist Security Info=False;Jet OLEDB:Database Password="
With Adodc1
.RecordSource = "SELECT *" & _
"FROM StockLevel3 " & _
"WHERE ItemName = '" & val & "'; "
End With
Set Grid.DataSource = Adodc1
Adodc1.Refresh
End If
Next
End Sub

Can't Update Values In Microsoft Access

I have a problem that when I try updating data the the program doesn't save it in the database.
This is the current code:
Dim y As Byte = Convert.ToByte(lblID.Text) - 1
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("dset").Rows(y).Item(1) = txtname.Text
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Else
MdAlertBox1.Text = "Please Select A Class The Class Box"
MdAlertBox1.Visible = True
End If
MdAlertBox1.Text = "Data Sucessfully Updated !"
MdAlertBox1.kind = MDAlertBox._Kind.Success
MdAlertBox1.Visible = True
getinfo.Start()
updatedata.Stop()
And the declared variables:
Dim conn As New OleDb.OleDbConnection
Dim DbProv As String = "PROVIDER=microsoft.ACE.OLEDB.12.0;"
Dim Src As String = " data source = c:\users\kingo\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\BigGymDB.accdb"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Put a debug.print to see the values you are passing to the Database. Like this:
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
'your code ---^
debug.print txtname.Text; txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text;
debug.print txtnotes.Text; txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
'your code ---v
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Then in two lines in the Immdiate Window, you should see whether these txtsub.Text and the other 3 inputs actually have something.

vbtab issue in a do until loop in vb.net

hey guys i am having a problem in my application with the vbtab
can anyone know what is the problem
this is my code:
txtshowpayments.Text = "Student's ID" & vbTab & "Student's Name" & vbTab & "Total Payment" & vbCrLf
Class217FileReader = New StreamReader("class217.txt")
PaymentsFileReader = New StreamReader("payments.txt")
Do Until PaymentsFileReader.EndOfStream
Do Until Class217FileReader.EndOfStream
Dim aline As String = Class217FileReader.ReadLine
Dim aline1 As String = PaymentsFileReader.ReadLine
Dim fields() As String = aline.Split(","c)
Dim fields1() As String = aline1.Split(","c)
Dim StudentId As Integer = Convert.ToInt32(fields1(0))
Dim studentId1 As Integer = Convert.ToInt32(fields(0))
Dim StudentName As String = fields(1) & " " & fields(2)
Dim totalpayment As Integer = Convert.ToInt32(fields1(1)) + Convert.ToInt32(fields1(2)) + Convert.ToInt32(fields1(3))
If ShouldDisplay(StudentId, studentId1) Then
txtshowpayments.Text &= StudentId & vbTab & StudentName & vbTab & String.Format("{0:C}", totalpayment) & vbCrLf
End If
Loop
Loop
Thank you for the help
Use a Format String:
Dim formatString As String = "{0,-12} {1,-14} {2}" & vbCrLf
txtshowpayments.Text = String.Format(formatString, "Student's ID", "Student's Name", "Total Payment")
formatString = String.Replace("{2}", "{2:C}")
Class217FileReader = New StreamReader("class217.txt")
PaymentsFileReader = New StreamReader("payments.txt")
Do Until PaymentsFileReader.EndOfStream
Do Until Class217FileReader.EndOfStream
Dim aline As String = Class217FileReader.ReadLine
Dim aline1 As String = PaymentsFileReader.ReadLine
Dim fields() As String = aline.Split(","c)
Dim fields1() As String = aline1.Split(","c)
Dim StudentId As Integer = Convert.ToInt32(fields1(0))
Dim studentId1 As Integer = Convert.ToInt32(fields(0))
Dim StudentName As String = fields(1) & " " & fields(2)
Dim totalpayment As Integer = Convert.ToInt32(fields1(1)) + Convert.ToInt32(fields1(2)) + Convert.ToInt32(fields1(3))
If ShouldDisplay(StudentId, studentId1) Then
txtshowpayments.Text &= String.Format(formatString, StudentId, StudentName, totalpayment)
End If
Loop
Loop
Even better... look into a DataGrid control.

VB.net Faster way of creating folders, subfolders and Excel files within those folders

I'm using VB 2010, SQL Server 2012 Excel 2010.
The users at my company have a requirement to use specific Excel report for hospitals and doctors.
I have a table in SQL Server that contains certain data and also the name of the person who is assigned to that hospital/doctor office, hospital name and lastly the address of the hospital name/doctor office.
The folders can have the following structure:
C:\Test\assignee name\hospital name\hospital or doctor address\hospital or doctor address.xlsx
Alternatively the hospital name could be blank ending with the following structure:
C:\Test\assignee name\hospital or doctor address\hospital or doctor address.xlsx
Here is the code I have until now, but it takes 4 hours to get only 4 of these assignee folders and reports generated.
I need to have 26 assignee folders, 3831 subfolders, 7281 files.
I'm looking for a faster way of doing this, please.
Here is my code:
Private Sub Create_CQM_Folders_VB()
Private Sub Create_CQM_Folders_VB()
Dim t1 As DateTime = DateTime.Now
Dim t2 As DateTime
Dim duration As TimeSpan
Dim connectionString As String = "server=SERVER1;Initial Catalog=DATABASE1;Integrated Security=SSPI"
Using conn As New SqlConnection(connectionString)
Dim command As New SqlCommand("SELECT distinct [Chase Assignment],[folder grouping],standardprovideraddress2 from SITES_Assigned", conn)
Dim count As Integer = 1
conn.Open()
Dim myReader As SqlDataReader = command.ExecuteReader()
//myReader = command.ExecuteReader
While (myReader.Read())
stringvar = Trim(myReader(0).ToString)
stringvar2 = Trim(myReader(1).ToString)
stringvar3 = Trim(myReader(2).ToString)
If String.IsNullOrEmpty(stringvar2) Then
MkDir("C:\test\" & stringvar & "\" & stringvar3)
Call Create_Main_CQM_Report()
If Val(xlAppSumm.Version) < 12 Then
//You use Excel 2000-2003
FileExtStr = ".xls" : FileFormatNum = -4143
Else
//You use Excel 2007
FileExtStr = ".xlsx" : FileFormatNum = 51
End If
//save each of the reports to their corresponding paths
Dim xlsxfilename As String
xlsxfilename = stringvar3
xlWorkBookSumm.SaveAs("C:\test\" & stringvar & "\" & stringvar3 _
& "\" & xlsxfilename & FileExtStr, FileFormat:=FileFormatNum)
xlWorkBookSumm.Close()
xlAppSumm.Quit()
// End If
Else
MkDir("C:\test\" & stringvar & "\" & stringvar2 & "\" & stringvar3)
Call Create_Main_CQM_Report()
If Val(xlAppSumm.Version) < 12 Then
//You use Excel 2000-2003
FileExtStr = ".xls" : FileFormatNum = -4143
Else
//You use Excel 2007
FileExtStr = ".xlsx" : FileFormatNum = 51
End If
//save each of the reports to their corresponding paths
Dim xlsxfilename As String
xlsxfilename = stringvar3
xlWorkBookSumm.SaveAs("C:\test\" & stringvar & "\" & stringvar2 & "\" & stringvar3 _
& "\" & xlsxfilename & FileExtStr, FileFormat:=FileFormatNum)
xlWorkBookSumm.Close()
xlAppSumm.Quit()
//End If
count = count + 1
End If
End While
conn.Close()
End Using
t2 = DateTime.Now
duration = t2.Subtract(t1)
//Get the difference and display it
MessageBox.Show(String.Format("Elapsed time: {0} Hours, {1} Minutes, {2} Seconds", duration.Hours, duration.Minutes, duration.Seconds))
MessageBox.Show("All reports have been created")
End Sub
Private Sub Create_Main_CQM_Report()
Private Sub Create_Main_CQM_Report()
//show CQM report in datagridview
Try
Dim connString As String = "server=SERVER1;Initial Catalog=DATABASE1;Integrated Security=SSPI"
Dim conn As New SqlConnection(connString)
Dim dbComd As New SqlClient.SqlCommand("select * from RPT_ASSIGNED_REPORTS order by [chase assignment], [folder grouping], standardprovideraddress2", conn)
conn.Open()
dbComd.CommandType = CommandType.Text
// dbComd.CommandTimeout = 900
Dim adapters As New SqlDataAdapter(dbComd)
Dim dset As New DataSet()
adapters.Fill(dset)
DataGridView1.DataSource = dset.Tables(0)
DataGridView1.AllowUserToAddRows = False
Dim dv As New DataView()
dv = dset.Tables(0).DefaultView
// get the DataView from a DataTable
If String.IsNullOrEmpty(stringvar2) Then
dv.RowFilter = "[chase assignment] = '" & stringvar & "' and standardprovideraddress2 = '" & stringvar3 & "'"
Else
dv.RowFilter = "[chase assignment] = '" & stringvar & "' and [folder grouping] = '" & stringvar2 & "' and standardprovideraddress2 = '" & stringvar3 & "'"
End If
conn.Close()
Catch ex As Exception
MessageBox.Show("Error while retrieving records from table..." & ex.Message, "Retrieve Records")
Finally
//System.Windows.MessageBox.Show("Records retrieved")
End Try
Dim misValue As Object = System.Reflection.Missing.Value
Dim lastrow As Long
Dim curr_date As String = DateTime.Now.ToString("MM.dd.yyyy HH.mm.ss")
copyAlltoClipboard()
xlAppSumm = New Excel.Application()
xlWorkBookSumm = xlAppSumm.Workbooks.Add(misValue)
xlWorkSheetSumm = xlWorkBookSumm.Sheets("Sheet1")
xlWorkSheetSumm.Range("A1").PasteSpecial(Excel.XlPasteType.xlPasteAll)
//xlWorkSheetSumm.Columns("A:A").Delete()
xlAppSumm.Visible = False
With xlWorkSheetSumm
//save each of the reports to their corresponding paths
.Columns("A:AN").EntireColumn.AutoFit()
End With
My.Computer.Clipboard.Clear()
//Clear datagridview for next sheet
Call Clear_DGV1()
End Sub

VB.net Retrieving dataset values from a particular column into a string

I need to copy structure of selected database to a new database. How is it possible? I am not able to retrieve the DataSet value. I need to use this value to retrieve the table names associated with the database. Here is my code.
cmd.CommandText = "create database " & txtCustId.Text & "AAA"
cmd.ExecuteNonQuery()
Dim dtadapt As New SqlDataAdapter("select table_name from " & name & ".INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'", comm_con)
Dim dtset As New DataSet
dtadapt.Fill(dtset)
Dim dttb As DataTable = dtset.Tables(0)
'Dim row As Integer = 1
Dim arrS As String = ""
while dttb.Rows.Count > 0
'arrS =Convert.ToString(dtset.Tables[i].Rows[0]["table_name"])
arrS = dttb("table_name").ToString
cmd.CommandText = " SELECT * INTO " & txtCustId.Text & "AAA.dbo." & arrS & " FROM " & name & ".dbo." & arrS & " where 1=1"
cmd.ExecuteNonQuery()
'MessageBox.Show("done")
End while