ASP.NET (VB) Trying set DB connection from web.config - asp.net

I have a web form project to update columns in an Microsoft SQL 2012 database table. When I "hard code" the connection info for my SqlConnection everything works fine. However if I try going the ConfigurationManager.ConnectionStrings route I get a keyword 'id' not supported. I have included the Imports.System.Configuration code into my project. Below is the Sub where I am running into the issue
Protected Sub BtnSubmit_Click(sender As Object, e As EventArgs) Handles BtnSubmit.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring, RqType, RqLast, RqFirst, RqOrg, RqEmail, RqNeedDate, SubFirst, SubLast, RqDetails, RqGenDate, RqOperator As String
RqType = cbxRequestType.SelectedValue
RqLast = txtReqLastName.Text
RqFirst = txtReqFirstname.Text
RqOrg = txtOrganization.Text
RqEmail = txtEmail.Text
RqNeedDate = txtReqDate.Text
SubFirst = txtSubFirst.Text
SubLast = txtSubLast.Text
RqDetails = txtReqDetails.Text
RqGenDate = txtGenDate.Text
RqOperator = txtOperator.Text
If Agree.Checked = False Then
MsgBox("You must agree to the terms before proceeding")
Else
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings("PRRWeb").ConnectionString)
myConn.Open()
sqlstring = "INSERT INTO Requests (LastName, FirstName, Organization, DateRequested, DateNeeded, OperatorID, SubjectLastName, SubjectFirstName, Notes, TypeID, Email) VALUES ('" + RqLast + "','" + RqFirst + "', '" + RqOrg + "','" + RqGenDate + "', '" + RqNeedDate + "','" + RqOperator + "','" + SubLast + "','" + SubFirst + "','" + RqDetails + "','" + RqType + "','" + RqEmail + "')"
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
MsgBox("Your request has been submitted.", MsgBoxStyle.Information)
Response.Redirect(Request.RawUrl)
End If

Resolved the issue by adding a connectionstring to my web.config like so
<connectionStrings >
<add
name="PRRWeb"
connectionString="Server=server;Database=DB;Timeout=200;User ID=user; Password=Password; Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
And then added this to my vb code
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings ("PRRWeb").ConnectionString)

Related

How to upload xls file's data to SQL Server in devexpress popup control?

I have enquiry on how to insert xls file data into SQL Server. The upload button, and gridview control are placed inside the devexpress popup control and the code works without the popup control but doesn't work with popup control. When I inserted the xls file and clicked the upload button, the label display showed "Please select a file to upload!" although I have did this.
ASP.NET markup:
<dx:ASPxPopupControl ID="popupControl" ClientInstanceName="popupControl"
AllowDragging="true" ShowOnPageLoad="false" runat="server" AllowResize="true" >
<ContentCollection>
<dx:PopupControlContentControl runat="server">
<div class="flexs">
<dx:ASPxUploadControl ID="XXUpload" runat="server" UploadMode="Auto" ValidationSettings-AllowedFileExtensions=".xls" width="500px" >
</dx:ASPxUploadControl>
<dx:ASPxLabel ID="Label2" runat="server" Text=""></dx:ASPxLabel>
<dx:ASPxButton ID="DataUpload" runat="server" Text="UPLOAD" OnClick="DataUpload_Click ">
</dx:ASPxButton>
<dx:ASPxGridView ID="UpdateSplitGrid" ClientIDMode="Static" ClientInstanceName="UpdateSplitGrid" runat="server" Width="200%" DataSourceID="dtSource2" Theme="DevEx" >
.....
</dx:ASPxGridView>
</div>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
Vb.net code:
Function uploadExcel1(filePath As String) As String
Dim str As String = ""
Dim namestr1 As String = XXUpload.UploadedFiles.ToArray(0).FileName.ToString
If namestr1 <> "" Then
If Not XXUpload.UploadedFiles.ToArray(0).IsValid Then
str = "Fail to Upload " + namestr1
Else
XXUpload.UploadedFiles.ToArray(0).SaveAs(filePath)
str = " Successfully Uploaded!"
End If
Else
str = "Please select a File to upload!"
End If
Return str
End Function
Function getDTe(filename As String, ByVal sql As String) As DataTable
Dim dt As New DataTable()
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';"
Dim connection As New OleDbConnection(connectionString)
Dim adapter As New OleDbDataAdapter(sql, connection)
adapter.Fill(dt)
Return dt
End Function
Protected Sub DataUpload_Click(sender As Object, e As EventArgs)
Dim filepath As String = "C:\New folder\" + XXUpload.UploadedFiles.ToArray(0).FileName.ToString + ".xls"
Dim msg As String = uploadExcel1(filepath)
Label2.Text = msg
If msg.Contains("Successfully") Then
Dim sql As String = "select * from [Sheet1$]"
Dim dt As New DataTable
dt = getDTe(filepath, sql)
If dt.Rows.Count > 0 Then
Dim i As Integer = 0
Dim colname() As String = {"LotID", "Split_Cat", "Engr_Time", "PLANDESC", "STEPSEQ", "EQPTYPE", "PPID", "STEPDESC", "Split", "Recipe", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22"}
For Each dc As DataColumn In dt.Columns
If dc.ColumnName.ToString <> colname(i) Then
Label2.Text = " File is not in correct format - Details: " + dc.ColumnName.ToString
Return
End If
i = i + 1
Next
For Each dr In dt.Rows
Try
Dim LotID As String = dr("LotID").ToString
Dim Split_Cat As String = dr("Split_Cat").ToString
Dim Engr_Time As String = dr("Engr_Time").ToString
Dim PLANDESC As String = dr("PLANDESC").ToString
Dim STEPSEQ As String = dr("STEPSEQ").ToString
Dim EQPTYPE As String = dr("EQPTYPE").ToString
Dim PPID As String = dr("PPID").ToString
Dim STEPDESC As String = dr("STEPDESC").ToString
Dim Split As String = dr("Split").ToString
Dim Recipe As String = dr("Recipe").ToString
Dim a As String = dr("F11").ToString
Dim b As String = dr("F12").ToString
Dim c As String = dr("F13").ToString
.............
Dim insertsql2 As String = ""
insertsql2 += "insert into PTHOME.dbo.SplitTable (LotID,Split_Cat,Engr_Time,PLANDESC,STEPSEQ,EQPTYPE,PPID,STEPDESC,Split,Recipe,[1],[2],[3]) values "
insertsql2 += "('" + LotID + "','" + Split_Cat + "','" + Engr_Time + "','" + PLANDESC + "','" + STEPSEQ + "','" + EQPTYPE + "','" + PPID + "','" + STEPDESC + "','" + Split + "','" + Recipe + "', "
insertsql2 += " '" + a + "','" + b + "','" + c + "') "
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(insertsql2, conn)
conn.Open()
Dim res As Integer = cmd.ExecuteNonQuery
conn.Close()
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Else
Label2.Text = " NO Records Uploaded! "
End If
Catch ex As Exception
Label2.Text = " Failed to Upload, pls check your data or file format ! "
End Try
Next
End If
End If
End Sub
When i upload the xls file, the label displayed
"Please select a File to upload!", anything i missed out in the popup control? Please guide me on this, thanks in advance.
EDIT*
I have changed the upload control to this and it no longer showed the "Please select a File to upload!" now there is another error showed "File is not in correct format - Details: F11", the error seems to lie on the column [1]-[12], but the excel column is 1-12 and the column in database is [1]-[12].how can i achieve this? ( Solved by changing the number to F11 and so on.)
<dx:ASPxUploadControl runat="server" ClientInstanceName="XXUpload" ID="XXUpload" Width="600px" >
<ValidationSettings AllowedFileExtensions=".xls"></ValidationSettings>
</dx:ASPxUploadControl>
Edit 2*
The data has uploaded successfully to sql server and now another problem occurred, the data uploaded to sql server wont show in the UpdateSplitGrid gridview although i have declared this in my code.
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Your ASPxUploadControl, the XXUpload, doesn't have any function to execute when upload is complete. I suggest you use OnFileUploadComplete event with FileUploadMode="OnPageLoad".

select from database just can get first data [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Dim reserveTime As String
Dim Timer As String = ddlTime.SelectedValue
Dim dat As String
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Beauty shop\Beauty shop\Beauty.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
Dim reserveDate As String = Calendar1.SelectedDate
Dim bookingTime As String = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date='" & reserveDate & "'"
Dim sqlcommand2 As New OleDbCommand(bookingTime, conn)
Dim dr2 As OleDbDataReader
dr2 = sqlcommand2.ExecuteReader
If dr2.HasRows Then
dr2.Read()
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
dat = dr2.Item("Booking_Date")
reserveTime = dr2.Item("Booking_Time")
Next
End While
dr2.Close()
If Timer = reserveTime And dat = reserveDate Then
ShowTimeLbl.Text = "This time have been reserve"
Else
Dim sqlString As String
sqlString = "Insert INTO CustomerBooking(Customer_Name, Package_Name, Price, Booking_Date, Booking_Time, Card_Bank, Cardholder_Name, Card_Number,Expired_Month,Expired_Date) VALUES ('" & User_Name & "','" & Package_Name & "','" & Price_Package & "','" & Calendar_Book & "','" & Time_Book & "','" & Card_Name & "','" & Card_Holder & "','" & CreditCard_Number & "','" & Month_Card & "','" & Year_Card & "')"
Dim sqlcommand As New OleDbCommand(sqlString, conn)
sqlcommand.ExecuteNonQuery()
conn.Close()
Response.Redirect("ConfirmBook.aspx?Name=" + Master.NameMaster + "&UserName=" + User_Name + "&PackageName=" + Package_Name + "&PackagePrice=" + Price_Package + "&Calender=" + Calendar_Book + "&TimeBook=" + Time_Book + "&CardName=" + Card_Name + "&CardHolder=" + Card_Holder + "&CreditCardNumber=" + CreditCard_Number + "&MonthCard=" + Month_Card + "&YearCard=" + Year_Card)
End If
End If
when i choose time all date cannot run, what is my problem, i want to compare the date and the time, if time has been booking it will show full,but just can read first date , why cannot run second date?the date is same
You have kept an extra dr.Read before while loop.
If dr2.HasRows Then
***dr2.Read()***
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
Remove the extra read() statement and get the field count inside while loop. It should work fine.
If dr2.HasRows Then
While dr2.Read()
Dim count As Integer = dr2.FieldCount
For i As Integer = 0 To count - 1
UPDATE-
I am putting a pseudo code just to give you an idea. There is a lot of room for improvement. But since it is not a code review, I will keep quite on that matter.
query = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date= <inputDate> & and Booking_Time=<inputTime>"
dr2 = get datareader using <query>
If dr2.HasRows Then
'It means there are records in DB with input date and Time so show error
Else
'code to insert'
End If

Data from input box not inserting in to database

I made this form to insert information in database. I don't know where the error coming from. It's not inserting information from input fields to database.
Here's my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id, name, description, code, cat_industry, cat_theme, cat_occasion, cat_budget As String
id = product_id.Text
name = product_name.Text
description = product_description.Text
code = item_code.Text
cat_industry = industry.SelectedValue
cat_theme = theme.SelectedValue
cat_occasion = occasion.SelectedValue
cat_budget = budget.SelectedValue
Try
Dim str1 As String = "insert into product (ID, Product_Name, Product_Description, Item_Code, Industry, Theme, Occasion, Budget) values ('" + id + "', '" + name + "', '" + description + "', '" + code + "', '" + cat_industry + "', '" + cat_theme + "', '" + cat_occasion + "', '" + cat_budget + "')"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Your column names can't be referenced as Product Name and Product Description with a space - you will need to escape it as [Product Name], [Product Description] etc.
But please refrain from inserting data directly - instead you should be parameterizing your input variables. This has benefits from both a performance and security (Sql Injection) perspective.
Dim str1 As String = "insert into product (ID, [Product Name], [Product Description], Item_Code, etc) " _
" values (#id, #name, #description, #code, etc)"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.Parameters.AddWithValue("#id", id )
cmd.Parameters.AddWithValue("#name", name )
... etc
cmd.ExecuteNonQuery()

How to insert the values of 3 droplists into a single column of an MS Access database, using asp.net

In my project i display an 3 droplists (Daydrplist, MonthDropList, YearDropList). When the user selects the values and clicks the button the values should be inserted to the access database in the BirthDate column of the Teacher table.
How can I do that?
Protected Sub NextBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles NextBtn.Click
con = New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\user\Desktop\web programming\\IULWebInformationSystem1\IULWebInformationSystem1\App_Data\IUlDB.accdb;Persist Security Info=True"
con.Open()
sqlquery = "insert into Teacher values ('" & FirstNameTxtBox.Text & "','" & MiddelNameTxtBox.Text & "','" & LastNameTxtBox.Text & "','" & POBTxtBox.Text & "','" & NationalityDropList.SelectedValue & "','" & Gendrplist.SelectedValue & "')"
cmd = New OleDbCommand(sqlquery, con)
cmd.ExecuteNonQuery()
con.Close()
FirstNameTxtBox.Text = ""
MiddelNameTxtBox.Text = ""
LastNameTxtBox.Text = ""
POBTxtBox.Text = ""
NationalityDropList.SelectedValue = ""
Gendrplist.SelectedValue = ""
lblmsg2.Text = "Personal Information was Added Successfully"
lblmsg2.Visible = True
Response.Redirect("PersonalAddress.aspx")
End Sub

How to File Upload csv to SQL database on intranet VB.NET site

I am having problems uploading CSV files to my SQL Database. I am trying to achieve this through the File Upload technique on an intranet site. The intranet site is for me and another user to have the ability to file upload these CSVs (in case one of us is out).
I've used the following;
Dim errorList As String = String.Empty
Dim returnValue As Integer = 0
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
Dim ErrString As String
Dim countRecs As Integer = 0
Dim batchid As Integer = GetNextBatchNumber("PartsImport")
Using tf As New TextFieldParser(fileandpath)
tf.TextFieldType = FileIO.FieldType.Delimited
tf.SetDelimiters(",")
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (ID,PartName,PartID,Price,ShipAddress) " _
+ " values ('" + row(0) + "','" + row(1) + "','" _
+ row(2) + "','" + row(3) + "','" + row(4) + "')"
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close()
SQLCon.Dispose()
SQLCmd.Dispose()
When I click the form button to upload, it gives me a success message but when I look in the actual table, it is still blank.
Any ideas? Appreciate it
Thanks
Dave
private void UploaddataFromCsv()
{
SqlConnection con = new SqlConnection(#"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
string filepath = "C:\\params.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "[Base].[PartsImport]";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
Try catching a SqlException and seeing if there is a formatting issue with your request. If you have an identity column on the ID, you shouldn't set it explicitly from your CSV as that may cause a potential duplicate to be submitted to your database. Also, I suspect that you have some type mismatches in your types since you are putting quotes around what appear to be number columns. I would recommend you consider replacing the string concatenation in your query to using parameters to avoid issues with improper quote escaping (ie. what would happen if you have a PartName of "O'Reily's auto parts"?) Something like this may work. Note, I've been in the LINQ world for so long, I may have some syntax errors here.
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text 'Setup Command Type
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (PartName,PartID,Price,ShipAddress) " _
+ " values (#PartName, #PartID, #Price, #ShipAddress)'"
Dim partNameParam = New SqlParameter("#PartName", SqlDbType.VarChar)
Dim partIdParam = New SqlParameter("#PartID", SqlDbType.Int)
Dim partPriceParam = New SqlParameter("#Price", SqlDbType.Money)
Dim partAddressParam = New SqlParameter("#ShipAddress", SqlDbType.VarChar)
SQLCmd.Parameters.AddRange( {partNameParam, partIdPAram, partPriceParam, partAddressParam})
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString()
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
partNameParam.Value = row[1]
partIdParam.Value = row[2]
partPriceParam.Value = row[3]
partAddressParam.Value = row[4]
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close() 'TODO: Change this to a Using clause
SQLCon.Dispose()
SQLCmd.Dispose() 'TODO: Change this to a Using clause
With all that being said, if you have any significant number of items to insert, the bulk copy example is a better answer.

Resources