I have one solution, which has multiple projects in it, in which some
projects are developed using web form, MVC.
I need to share the session data between these projects. For this, i have
used SQLServer Mode in session state. I am able to store the session data
into database, but i am not able to retrieve the sessions data. So any
help will be appriciated.
Thanks in advance.
This is what i have tried to fetch data from ASPState database
public ActionResult Home()
{
ViewBag.Result =Session["username"].ToString();
SqlCommand cmd = new SqlCommand("select SessionId from
ASPStateTempSessions", con);
byte[] bytdata = new byte[50];
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
var list = new List<LoginUser>();
if(dr.HasRows)
{
while(dr.Read())
{
//obj=dr["SessionId"];
string obj = dr["SessionId"].ToString();
bytdata = System.Text.Encoding.UTF8.GetBytes(obj);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytdata);
BinaryFormatter bin = new BinaryFormatter();
//bin.Serialize(ms, bytdata);
//list = (List<LoginUser>)bin.Deserialize(ms);
string session = Convert.ToString(bin.Deserialize(ms));
}
}
ViewBag.Data = list;
return View();
}
This is what i have configured ion Web.config
<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="SessionSqlCon" cookieless="false" timeout="10" />
</providers>
</sessionState>
Related
Controller
if (User.Identity.IsAuthenticated)
{
var users = adminDatabase.AspNetUsers.Where(u => u.UserName ==User.Identity.Name).FirstOrDefault();
Session["CurrentUser"] = users;
}
Connection
<add name = "DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=administration;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
The problem that showed me is on controller user identity.
I have no idea what's going on!
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
I am trying to connect to a SQL Server database using the configuration manager.
The config file code:
<connectionStrings>
<add name="DBCS"
connectionString="data source =.\\SQLEXPRESS; database = Sample2; integrated security = SSPI;"
providerName ="System.Data.SqlClient" />
</connectionStrings>
The C# code below:
string SC = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//string SC = ("data source =.\\SQLEXPRESS; database = Sample2; Integrated Security = SSPI;");
SqlConnection con = new SqlConnection(SC);
SqlCommand cmd = new SqlCommand("Select * from tblemployee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
When I try to run the application I get an error at
con.Open();
Error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Please help.
You need only one \ before SQLExpress in your connection string:
<add name="DBCS"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS; database = Sample2;Integrated Security=SSPI"/>
Check the documentation for further details
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?
I have created a new MVC 4 project, Build and Run -> All Successful
Try to login -> New Database is created in SQL Express (Database name: xyz) => All good so far...
Now, I want to add a new table called "ABCD" in SQL Express (to above xyz Database). How can I access this table in Visual Studio solution? There is no Entity Framework model to go and update it manually?
However, I have added a class called ABCD in the Models folder
Created a new controller for ABCD with a new Data Context Class but when I ran the solution, it is created a new Database instead of using the default database mentioned in Web.config file
Can someone please let me know how can I fix this issue with detailed steps?
Here is my DataContext class:
using System.Data.Entity;
namespace _1024.Models
{
public class _1024Context : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, add the following
// code to the Application_Start method in your Global.asax file.
// Note: this will destroy and re-create your database with every model change.
//
// System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<_1024.Models._1024Context>());
public _1024Context() : base("name=_1024Context")
{
}
public DbSet<ABCD> ABCDs { get; set; }
}
}
Here is the Web.config File:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-_1024-20130606134952;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
<add name="_1024Context" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=_1024Context-20130606135301; Integrated Security=True; MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You should not use new connection string if you want to use existing database. In your connection strings you have two different initial catalog that means two different database.
Try to write like this without the "name=" first. This works for me.
public _1024Context() : base("_1024Context")