I am preparing to deploy a web service that uses SqlConnection primarily as its means to get to the database, and I am adding some new methods that use a DataContext instead of that, and the default constructor and DBML file would use a connection string refering to my development machine (I believe...)
The connection string that the SqlConnection objects use is hard coded into a separate class (don't ask). If I provide the DataContext with the same connection string as the SqlConnections will that work instead of modifying the DBML or Web.config?
The connection string that is used in these objects is:
Dim cn As New SqlClient.SqlConnection
cd.ConnectString = ApplicationInfo.ConnectString 'Connection string is stored here
So will this work too? Do I have to change something else?
Dim db As New FADataContext(ApplicationInfo.ConnectString)
Where ApplicationInfo.ConnectString is a hard coded string that has the properties of the connection. I don't have physical access to the production SQL server or Web server therefore can't use the DBML designer to edit the connection string. And they aren't stored in the .config files.
I'm pretty sure that would work. I know when you use Entity Framework you can send a connection string in the DataContext and it works fine. Although the connection string has more information in it then regualar connection strings, like the name of the csdl, msl, ssdl or whatever.
Related
My app makes use of OleDbConnection and OleDbCommand objects for executing queries. These are controls you can just drag and drop onto the designer. I can set the connection string on the OleDbConnection just fine from within the designer. The problem arises when I remove the connection string from the OleDbConnection and put it in my web/app .config. When I open/view the queries in the OleDbCommand objects, it throws this error:
"The ConnectionString property has not been initialized"
I have an OracleConnection object that doesn't throw this error but will pop up a box asking for connection string info. I don't want that either.
Before I moved the connection strings to my web.config, I was able to open the queries up in the designer (by clicking the ellipses next to the query), and even execute it if I wanted.
How can I get the designer to use the connection string inside my web.config so it stops throwing the above error when I try to open the queries from the designer?
I will note that the app works at run time because I'm setting the connection string from within the constructor of the code behind file using the ConfigurationManager.
Could you explain me how to construct correct ConnectionStrings? I mean that one you can find in web.config file in MVC project. I understand that if you want to add a new connection string you have to write <add ... /> XML tag with parameters such as name, connectionString (it is the most interesting parameter for me) and providerName (perhaps some else?). What each parameter does and means? How to construct connectionString parameter? Where is the db engine indicated?
The questions above are only examples. I care about collecting the most amount of information about constructing ConnectionStrings.
Starting from NET 2.0 you have at your disposal a class named SqlConnectionStringBuilder
Its purpose is to help building dynamically the connection string. But the various properties available explain in great detail the functionality underlying to each possible setting
The SqlConnectionStringBuilder class is derived by a base class named DbConnectionStringBuilder and this allows all the ADO.NET provider to implement their own version of this class. In the link provided there are the references relative to other ADO.NET providers
If you are trying to construct entity framework connection string just use as follows.It will help you..
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
UPDATED:
The easiest way to get the connection string is using the Server explorer window in Visual Studio (View-->Server Explorer menu) and connect to the server from that window. Then you can see the connection string in the properties of the connected server (F4 with your connection selected).
If you create the database in SQL Server Management Studio, that database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express installed on your machine.
I see a couple of DataContext connection string questions. I'm going to try to differentiate this one a bit:
How does one construct a generic connection string to a database, localhost | User-PC\User | Some database... (it is hosted/managed by Microsoft SQL 2008)
I notice that it is IDisposable. So if I have multiple users hitting my site, my code can only access the database one instance at a time, and has to wait until each instance is disposed, in order for the data to be consistent for each user?
Is it possible, by any chance, to somehow enable LINQ in F#-Interactive, and connect to the database from there? I cannot figure out how to enable/load the System.Data dll into fsi. Maybe that is unique to my installation, or it is a common thread? (ie, my installation also does not recognize windows.base.dll--I have to manually get it from programs\reference assemblies).
Anyhow, I've pretty much conclusively discovered that
let x = new System.Data.Linq.DataContext("localhost")
...does not work.
1) How does one construct a generic connection string to a database?
There is no generic way to construct a connection string. The best thing to do is to keep the connection string in some configuration file where you can change it depending on your configuration (the name of SQL Server machine, authentication options, whether it is a file-based database or normal). There is a web site with examples for most of the options.
2) I notice that it is IDisposable. So if I have multiple users hitting my site, my code can only access the database one instance at a time [...]?
No, this is not how DataContext works. The DataContext does not keep a live connection to the server that would block anybody else from using the SQL server. It keeps some state (i.e. cached entities that were already obtained) and it uses optimistic concurrency to make sure that the state is consistent (you can use transactions to prevent other connections, if that's what you want).
3) Is it possible, by any chance, to somehow enable LINQ in F#-Interactive [...]?
That shouldn't be a problem. You can reference assemblies using #r "foo.dll" in F# interactive. The typical approach for F# 2.0 is to generate the data context using C# tools and then just reference it (for F# 3.0, things are easier because you can just use type provider).
If you generate LINQ to SQL data context for Northwind in C#, the F# Interactive use would look like this:
#r #"<whatever_path>\Northwind.dll"
#r "System.Data.Linq.dll"
open Northwind
open Microsoft.FSharp.Linq
let connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=<path>\NORTHWND.MDF;" +
#"Integrated Security=True;User Instance=True"
let operation () =
// Using 'use' to make sure it gets disposed at the end
use db = new NorthwindDataContext(connStr)
// do something with the database
There actually is a somewhat generic way to construct a connection string:
open System.Data.Common
open System.Data.SqlClient
let providerName = "System.Data.SqlClient"
let factory = DbProviderFactories.GetFactory(providerName)
let cnBuilder = factory.CreateConnectionStringBuilder() :?> SqlConnectionStringBuilder
cnBuilder.DataSource <- "localhost"
cnBuilder.InitialCatalog <- "MyDatabase"
cnBuilder.IntegratedSecurity <- true
let connStr = cnBuilder.ConnectionString
My approach was to have 1 connection string and then use that for all of my DataContext connections. So this code builds the EntityConnectionString based on MyConnString:
protected override MyEntities CreateObjectContext()
{
string ConnString =ConfigurationManager.ConnectionStrings["MyConnString"];
string seConn = ConfigurationManager.ConnectionStrings["MyEntities"].ToString();
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(seConn);
ecsb.ProviderConnectionString = ConnString;
EntityConnection ec = new EntityConnection(ecsb.ToString());
ScheduleEntities ctx = new ScheduleEntities(ec);
return ctx;
}
Is sqlConnection ADO, if not, what's the name of the layer?
To invoke ADO, (to access non-MS db's), is OleDbConnection the prefered choice?
SqlConnection is part of the ".NET Data Provider for SQL Server", so it is ADO.NET, not to be confused with the old COM-based ADO.
Also, yes I believe OleDBConnection is preferred for Access. I do not believe there is an out-of-the box native data provider for MS Access.
1) The SqlConnection Class is part of the System.Data.SqlClient namespace, and is considered part of ADO.NET.
2) OleDbConnection is for connecting to OLE databases. If you're talking about building a platform-agnostic data access layer, you should use System.Data.Common.DbProviderFactories to create generic DbConnection, DbCommand, etc, objects as in the following code example:
Dim objFactory As DbProviderFactory = DbProviderFactories.GetFactory(ConfigurationManager.AppSettings("DbType"))
Dim objConnection As DbConnection = objFactory.CreateConnection
objConnection.ConnectionString = strConnectionString
In this example, you'd keep the name of the actual provider you're using in your Application Settings.
Note that the generic DB objects only support lowest-common-denominator methods so if you're looking for something platform-specific, you're out of luck. Also of course you will have to specify a valid DBtype to the provider factory, which means you'll have to use either one of the built in providers (ODBC, MS SQL, Oracle, OLEDB) or a third party one. I think you could get away with ODBC if you have a ODBC driver for your platform, but I don't know much about that one.
For information on the different connection objects included in ADO.NET: MSDN-Connecting to Data Sources
Yes it is part of ADO.NET. If you use SqlConnection, actually it is a part of ADO.NET to make a connection between your application and database.
I'm designing a web service in ASP.NET and VS2008, and am using typed datasets for retrieving table data. These work well and establish their own connections through their associated TableAdapter objects. Edit: I'm using VB, BTW!
I am now attempting to run a custom SQL string using a DataAdapter and a Command object, however I need to reference a Connection object in order for the Command to work. What is the best way to handle this? Should I:
a) Create a global connection object using Global.asax, retrieving the connection string from web.config? (I've been trying that one already, with not much success)
b) Create a class-level connection object using the InitialiseComponent method, also retrieving the ConnectionString from web.config?
c) Retrieve a Connection from one of the TableAdapters that I've already created in my typed DataSets?
d) Something else I haven't thought of yet?
BTW I've been finding it very difficult to extract a ConnectionString from web.config, so any help with that would be appreciated also!
I'm not entirely inexperienced with ASP.NET, but my last big project used VS2003, and I want to make sure that I'm using the current tools correctly.
To extract the connection string, use
WebConfigurationManager.ConnectionStrings["name"].ConnectionString
It's best to open and close the connections as close as possible to their use. ADO.NET will do connection pooling so that this won't be expensive:
var connectionString =
WebConfigurationManager.ConnectionStrings["name"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("query", conn))
{
conn.Open();
// Use the command
}
}
For Connection and data access problems I will advise you to go with some kind of Data Helpers like Microsoft Data Access Application Block
Here you can find small tutorial about how to use it.
For getting connectionstring from web.config use folowing methods
public static string GetConnectionString( string strConstringKey )
{
return ConfigurationManager.ConnectionStrings[strConstringKey];
}
public static bool GetConnectionString(string strConstringKey, ref string strConstring)
{
return (strConstring = ConfigurationManager.ConnectionStrings[strConstringKey] ) == null ? false : true ;
}