ASP.NET: I am having troubles trying to run a sql script - sql

I have installed Microsoft SQL Server 2014 Express, and I am am learning how to use ASP.NET with Visual Studio Express 2015 for Web to retrieve data from a veterinarian database called vetDatabase_Wizard.
As a beginning, I am retrieving a protocolID from an entered ID and storing the information in a class called clinicalCase. I am 100% new to SQL.
Here is my SQLQuery1.sql script (attempt):
Select * from tblCases
CREATE PROCEDURE spGetCaseByID
#ID int
BEGIN
SELECT caseID, protocolID
FROM tblCases
WHERE caseID = #ID
END
Here is my getCaseByID function calling my SQL script:
[WebMethod]
public clinicalCase getCaseByID(int ID)
{
// Retrieve connection string
string cs = ConfigurationManager.ConnectionStrings["vetDatabase_Wizard"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetCaseByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#ID", ID);
cmd.Parameters.Add(parameter);
clinicalCase cases = new clinicalCase();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
cases.ID = Convert.ToInt32(reader["ID"]);
cases.protocolID = Convert.ToInt32(reader["protocolID"]);
}
return cases;
}
}
When I run the function and try it, I get the following error at
SqlDataReader reader = cmd.ExecuteReader();
Could not find the stored procedure "spGetCaseByID".
I suspect it's my SQL syntax or the fact that I added a connection string in my web.config file because I didn't have one:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="vetDatabase_Wizard"
connectionString="Data Source=JOHNATHANBO431E\SQLEXPRESS2014;Initial Catalog=vetDatabase_Wizard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>
I got the name and connectionString from the properties panel of the database.
I would greatly appreciate the community's feedback because I must be missing something obvious! I would like to thank you very much for your time! :)
EDIT: I realized that I need to first execute my SQL script in SQL Server Management Studio before using it in Visual Studio.
However, I get the following error:
SQL80001: Incorrect syntax: 'CREATE PROCEDURE' must be the only statement in the batch. vetApp
Hence, my SQL script is wrong and would appreciate debugging help.

Your code is trying to run a SQL Server stored procedure called spGetCaseByID.
This stored procedure does not exist in your database.

you are trying to run multiple commands in SQL . In order to create stored procedure it should be the first line of code or place go in between the multiple sql command
Select * from tblCases
GO
CREATE PROCEDURE spGetCaseByID
#ID int
**AS**
BEGIN
SELECT caseID, protocolID
FROM tblCases
WHERE caseID = #ID
END
This will help

Related

Accessing EF6 in code throws System.NotSupportedException in EntityFramework.dll

based on .NET 4.0 and EF 6.1, I've created a project names Database with an Entity Model to access a SQL Server instance via Designer in Visual Studio 2013.
Additionally, there is an Console Application (also .NET 4.0) trying to consume the entities of the Database-project.
The credentials for the underlying database are stored in the Console Application's App.config within the key <connectionStrings>.
When creating a DbContext in the following way, I can perfectly access the entities:
var db = new MyEntities();
var o1 = db.Buildings.First();
MyEntities is the class that the Entity Framework creates automatically, inheriting from DbContext.
For some compatibility reasons to our guidelines, I'm trying to split up the connectionString into own keys (database, instance, user, password) within Ap.config.
For this, I'm using EntityConnectionStringBuilder to build up the EntityConnection with ProviderConnectionString, Metadata and Provider. It look's like this:
Dim sqlBuilder = New SqlConnectionStringBuilder()
sqlBuilder.MultipleActiveResultSets = True
sqlBuilder.DataSource = "database instance"
sqlBuilder.InitialCatalog = "database"
sqlBuilder.UserID = "user"
sqlBuilder.Password = "password"
Dim providerConnectionString = sqlBuilder.ToString()
Dim metaData = #"res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl"
Dim entityConnectionBuilder As New EntityConnectionStringBuilder() With { _
.Metadata = metaData, _
.ProviderConnectionString = providerConnectionString, _
.Provider = "System.Data.SqlClient"}
Dim s = entityConnectionBuilder.ToString()
entityConnection = New EntityConnection(s)
In my Console Application, I call:
var db1 = new MyEntities(entityConnection);
var o2 = db1.Buildings.First();
When executing the last line, the following exception will be thrown:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Unable to determine the DbProviderFactory type for connection of type 'System.Data.EntityClient.EntityConnection'. Make sure that the ADO.NET provider is installed or registered in the application config.
App.config of Console Application contains the following:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Any ideas, why this exception occurs?

Web.config jsonSerialization maxJsonLength ignored

I have an MVC3 application running under .NET 4.0 and when I use JavascriptSerializer.Deserialize I'm getting an error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Reading Can I set an unlimited length for maxJsonLength in web.config I put the jsonSerialization maxJsonLength key in my web.config but it gets ignored. Though I can set the JavaScriptSerializer.MaxJsonLength property in code and it works fine.
I would like to have the value in the Web.config rather than code. Here is how I am using JavaScriptSerializer.
Dim client As New WebClient
...
Dim result = _client.DownloadString("Test")
Dim serializer = New JavaScriptSerializer
Return serializer.Deserialize(Of Foo)(result)
Here is my Web.config
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/Http404"/>
<error statusCode="403" redirect="/Http403"/>
<error statusCode="550" redirect="/Http550"/>
</customErrors>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.webServer>
....
</system.webServer>
</configuration>
According to the link you provided (the 2nd most voted answer), your web.config setting will be ignored because you're using an internal instance of the JavaScriptSerializer.
If you need the value to be stored in the web.config, you could add a key in the <appSettings> section called maxJsonLength with a value of 50000000 and then in your code, you could use it like:
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = ConfigurationManager.AppSettings['maxJsonLength'];

How to declare ConfigurationManager.ConnectionStrings?

hello i'm using visual studio 2008, vb.net and oracle as my db.
this is what i save in my apps.config
<appSettings/>
<add key="SMSDW_connection" value="server=abc;database=efg;User ID=**;Password=**;"/>
and this is my code for calling the apps.config file :
Dim connectionString = System.Configuration.ConfigurationManager.AppSettings("SMSDW_connection")
Dim sqlConnection As OracleClient.OracleConnection = New OracleClient.OracleConnection(connectionString)
but still i got an error which is :
The ConnectionString property has not been initialized.
i have add reference System.Configuration and Imports System.Configuration
The <appSettings> node has the closing tag "/" so the <add is outside of it.
it should read:
<appSettings>
<add ...
</appSettings>

Move simple membership profider functionality to class library project

I'm trying to move my DbSet's to a class library project that is going to be used for database operations.
I've been following this tutorial to a Code First / SimpleMembershipProfider project. I've already got the database filled with new tables etc, via the class lib project.
But i am missing the webpages_ tables you can see on this image.
This is my datacontext class:
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public DbSet<Orders> Orders { get; set; }
public DbSet<Appointment> Appointment { get; set; }
public DbSet<UserProfile> UserProfile { get; set; }
}
And for every DbSet i created a cs file. I copied the connectionString from the web.config and placed it in the app.config in the class lib project. This is how the app.config file looks like:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I'm not sure what to do with the Filters folder (which has the class InitializeSimpleMembershipAttribute) in my webproject.
Can someone tell me how to get the webpages_ created in the database? And how to move websecurity etc to the class lib project?
Thanks in advance!
If you trying to take control of Asp.net Simple Membership Table and or Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model your Project Entity framework, there is a number of steps you need to take. I would explain them step by step but it would take too long so i will just provide you with references.
Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
Building Applications with ASP.NET MVC 4. You can use trial version on pluralsight
If you have any specific questions, i would be happy to answer them.

How to add Application name to <appSettings/>?

This is my app.config file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Application Name" value="/MyApplication" />
</appSettings>
<connectionStrings>
<add name="frmStartup.My.MySettings.HDIMembershipProviderConnectionString"
connectionString="Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<membership defaultProvider="HDIMembershipProvider">
<providers>
<clear/>
<add name="HDIMembershipProvider" type="MyApplication.HDIMembershipProvider, MyApplication"/>
</providers>
</membership>
</system.web>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
I am trying to use HDI membership provider and this is my Users table structure:
And in my recent question asked here Oded helped me out trying to figure the problem with my Insert statement and I re-modified it and I have an ApplicationName column in my database structure I need to specify it.(As it should not be null value)
Now I need to add my application name by default to enter to database as we do it for web.config.
This is what I mean.
I need to add that MyApplication to my app.config file.
So How do I do that?
This is how I'm trying to enter user details to database but it is not enetering a single value
Try
Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
Using cn As New SqlConnection(connectionString)
cn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"
Dim param1 As New SqlParameter()
param1.ParameterName = "#Username"
param1.Value = txtUsername.Text.Trim()
cmd.Parameters.Add(param1)
Dim param2 As New SqlParameter()
param2.ParameterName = "#Password"
param2.Value = txtPassword.Text.Trim()
cmd.Parameters.Add(param2)
Dim param3 As New SqlParameter()
param3.ParameterName = "#Email"
param3.Value = txtEmail.Text.Trim()
cmd.Parameters.Add(param3)
Dim param4 As New SqlParameter()
param4.ParameterName = "#PasswordQuestion"
param4.Value = txtSecurityQuestion.Text.Trim()
cmd.Parameters.Add(param4)
Dim param5 As New SqlParameter()
param5.ParameterName = "#PasswordAnswer"
param5.Value = txtSecurityAnswer.Text.Trim()
cmd.Parameters.Add(param5)
cmd.Connection = cn
cmd.ExecuteNonQuery()
cn.Close()
End Using
Successlbl.show
Successlbl.show.Text = "Regisration Success."
Catch
Errolbl.Show()
Errolbl.Text = "Your account was not created.Please try again."
End Try
Can anyone point me out where I'm making mistake.
And this is the final result I'm getting while entering to database:
To be more short and clear I need to enter the above shown User details to my database using the HDI membership provider.
There is a better way by using the following steps:
1) Add a reference to System.Configuration to your application.
2) Add the following block to your app.config file, within the configuration section:
<appSettings>
<add key="ApplicationName" value="/MyApplication" />
</appSettings>
3) Retrieve the value and use it where needed with the following code (example from your answer shown):
param6.Value = System.Configuration.ConfigurationManager.AppSettings("ApplicationName")
Add a AppSettings section to your web.config
<appSettings>
<add key="ApplicationName" value="/website1" />
</appSettings>
I have figured out the problem Myself after a lot of hair pulling and found the solution that I have changed my code in this way:
cmd.CommandText = "INSERT INTO Users ( Username,ApplicationName,Password,
Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#ApplicationName,#Password,
#Email,#PasswordQuestion,#PasswordAnswer)"
And add another Param this way:
Dim param6 As New SqlParameter()
param6.ParameterName = "#ApplicationName"
param6.Value = txtApplicationName.Text.Trim()
cmd.Parameters.Add(param6)
I know this not the best way If anyone found any other best solution let me know.