SQL Server ASP.net Insert Into Vb.net Code Not Working

Enflow
Enflow used Ask the Experts™
on
Installed SQL Server EXPRESS 2014 to my local desktop -
Name: MY64BIT-PC\SQLEXPRESS

Created SQL Server AUTH hybrid login

Created a User Name and Password for connection string and gave them every permission i could find for both Server and Database I created

Created New DBase
Name: HousingAuthority

Created a table
Name: dbo.tblApplication

See uploaded image file with these names...

with 4 fields ID, FirstName_1, LastName_1, datetime field

See web page code below... that runs on visual studio local host server (needs better web config error handling too)

Insert Into code fired from button not working and web page not showing error...

<%@ Page Language="VB" AutoEventWireup="false" Debug="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data"%>\
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.data.OleDb" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub

    Private Sub SubmitEM_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim con As New SqlConnection : Dim cmd As New SqlCommand
        Try
            con.ConnectionString = "Data Source=MY64BIT-PC\SQLEXPRESS;Initial Catalog=HousingAuthority;Persist Security Info=True;User ID=ABC;Password=XYZ"
            con.Open()
            cmd.Connection = con
            cmd.CommandText = "INSERT INTO dbo.tblApplication ([FirstName_1], [LastName_1]) VALUES ('Test_FN','Test_LN')"
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            'abc
        Finally
            con.Close()
        End Try
    End Sub
</script>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body> 
  <form id="form1" runat="server">  
    <div><asp:Button ID="Button1" runat="server" Text="Submit Application" onclick="SubmitEM_Click" usesubmitbehavior="false" /></div>       
  </form>
</body>
</html>

Open in new window

1-Names.jpg
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You are suppressing exception in your code:
Try            
...
Catch ex As Exception          
  'abc        
Finally            
con.Close()      
  End Try

Replace 'abc with error message output for ex
I didn't have any luck with your connection string. Comment out your try catch finally if you need to debug this page.

This should work
<%@ Page Language="VB" AutoEventWireup="false" Debug="true" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub

    Private Sub SubmitEM_Click(ByVal sender As Object, ByVal e As EventArgs)
     Dim con As New SqlConnection : Dim cmd As New SqlCommand
        Try
            con.ConnectionString = "Server=MY64BIT-PC\SQLEXPRESS;Database=HousingAuthority;UID=ABC;PWD=XYZ;Persist Security Info=False;"
            con.Open()
            cmd.Connection = con
            cmd.CommandText = "INSERT INTO dbo.tblApplication ([FirstName_1], [LastName_1]) VALUES ('Test_FN','Test_LN')"
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            'abc
        Finally
            con.Close()
        End Try
    End Sub
</script>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body> 
  <form id="form1" runat="server">  
    <div><asp:Button ID="Button1" runat="server" Text="Submit Application" onclick="SubmitEM_Click" usesubmitbehavior="false" /></div>       
  </form>
</body>
</html>

Open in new window


If you mention username and password in your connection string and set Persist Security Info as false then the credentials cannot be extracted.
If you mention username and password in your connection string and set Persist Security Info as true then the credentials can be extracted in thread.

Author

Commented:
@OMC2000 & @Hilltop...

Okay I commented out the the Try/Catch/Finally and got an error message.. This is much more helpful...

Server Error in '/' Application.
The INSERT permission was denied on the object 'tblApplication', database 'HousingAuthority', schema 'dbo'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: The INSERT permission was denied on the object 'tblApplication', database 'HousingAuthority', schema 'dbo'.

Source Error: 


Line 17:         cmd.Connection = con
Line 18:         cmd.CommandText = "INSERT INTO tblApplication ([FirstName_1], [LastName_1]) VALUES ('Test_FN','Test_LN')"
Line 19:         cmd.ExecuteNonQuery()
Line 20:         'Catch ex As Exception
Line 21:         'abc

Source File: C:\Users\My64Bit\Documents\WebSites\Enflow\CC\P1\TEST.aspx    Line: 19 

Stack Trace: 


[SqlException (0x80131904): The INSERT permission was denied on the object 'tblApplication', database 'HousingAuthority', schema 'dbo'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1960634
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4890859
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2412
   System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +192
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +317
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
   ASP.cc_p1_test_aspx.SubmitEM_Click(Object sender, EventArgs e) in C:\Users\My64Bit\Documents\WebSites\Enflow\CC\P1\TEST.aspx:19
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

Version Information: Microsoft .NET Framework Version:2.0.50727.8762; ASP.NET Version:2.0.50727.8762

Open in new window

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Check user permissions for database again, probably you directly denied write permission when selected all permissions

Author

Commented:
@OMC2000

Wait ! - I think i do have db_DenyDataWriter checked for dbo Schema -- Please stand by

YES... On my User i had checked db_Writer and but ALSO db_DenyWriter or something like that spelling... Unchecked that and finally was able to insert data...

Many thanks... CJ

Author

Commented:
Thanks to OMC2000 for simple fix to a very tiresome problem... with the double check on the security settings...

Thanks to Hilltop for the Persist False suggestion on login creds.. and the comment out Try/Catch/Finally to get ASP.net err...

CJ
Happy to help Enflow.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial