Good Day,
I have two connection strings defined in my web.config file.
<connectionStrings>
<add name="AppDb" connectionString="CONNECTION-STRING1"/>
<add name="LaptopDb" connectionString="CONNECTION-STRING2" />
</connectionStrings>
When I am working on my desktop, I want to use the connection string "AppDb". When I am working on my laptop, I want to use the connection string "LaptopDb". I don't want to comment out the line on the connection string everytime I work on a different machine.
I know that I can programatically do this. I'm just trying to figure out the best way.
Something like:
if (machineName == desktop)
use AppDb
else
use LaptopDb
but I don't like this approach. Is there something else I can test on?
Here's another couple of approaches you could consider:
You can use the configSource attribute to read the configuration for that element from another file, the contents of which can be different on each machine:
http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx
Or you can use different build configurations and use XDT to transform the web.config file.
Really not too hard to do -- the trick is to use the System.Environment.MachineName to drive which string to pick and to get your connection string from a static property:
public static string ConnectionStringName
{
get
{
var customConnection = ConfigurationManager.ConnectionStrings[Environment.MachineName] != null;
var connectionStringName = customConnection ? Environment.MachineName : "DefaultDb";
return connectionStringName;
}
}
Related
I want to change Virtual Path(The path is out of project means local system or Server.) of the file Which is save on the folder in asp.net.
Code is
DataTable dtFiles =
GetFilesInDirectory(HttpContext.Current.Server.MapPath(UPLOADFOLDER));
gv.DataSource = dtFiles;
gv.DataBind();
if (dtFiles != null && dtFiles.Rows.Count > 0)
{
double totalSize = Convert.ToDouble(dtFiles.Compute("SUM(Size)", ""));
if (totalSize > 0) lblTotalSize.Text = CalculateFileSize(totalSize);
}
private static string UPLOADFOLDER = "D:/Uploads";
And the error show "D:/Uploads is not a valid virtual path.".
If you want to get the files in a directory and you know the full path, then you don't need to use Server.MapPath(). Just use the path.
Incidentally, the path delimiter is incorrect in your code. The string "D:/Uploads" should be #"D:\Uploads" (note the leading # sign to denote a string that should be treated literally and not escaped).
Of course. You're telling your server to map path that is completely off the IIS. How is it supposed to do? If you're using a web application, try to avoid such ideas completely. Even though it is possible, it isn't a good idea because of security issues you can run into.
Configuration File
<add key="ObjConn" value="Provider=SQLOLEDB;Persist Security Info=True;User
ID=OMembers;PWD=OMembers;Initial Catalog=Omnex2007;Data Source=192.168.100.131"/>
C# Code
strconnection = System.Configuration.ConfigurationManager.AppSettings("ObjConn");
sqlcon = new SqlConnection(strconnection);
you need to use
ConfigurationManager.AppSettings["ObjConn"]
instead of
ConfigurationManager.AppSettings("ObjConn")
Preferred approach is use below settings in config file
<connectionStrings>
<add name="ObjConn" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
and use ConfigurationManager.ConnectionStrings["ObjConn"] in your code to retrieve it
try
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
sqlcon = new SqlConnection(strconnection);
This is one of the language syntax differences between C# and VB. Array accessors in VB use parentheses () while in c# they use square brackets [].
In VB, Something(1) could be calling a function named "Something" and passing a 1 as a parameter, OR it could be that Something is an array or a list, and you're accessing the item at index 1.
in C#, Something(1) is ALWAYS a call to a function named Something, while Something[1] would indicate that Something is an Array or a List, and you're accessing an item in a list.
In C# you should use like
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
change and try again.
Generally, the accessing of Config entry values which you have tried in your coding will be used in VB.net coding, but in C# you should use [] with a key name(string format) inside the square brackets, to get the Config entry values.
... and not by reading it from the config file! Nor inferring it from anyplace other than be reading exactly what the Membership Provider is itself using. Call me paranoid.
The first data access in my application is an access to the membership provider. The vast majority of connectivity issues have been where the application is deployed to staging or production with a connection string from development, so I'd like to change this:
MembershipUser me = Membership.GetUser();
to this:
MembershipUser me;
try
{
me = Membership.GetUser();
}
catch ( SqlException E )
{
Response.Write( "SQL Error " + E.Message + ".<br />" );
Response.Write( "Connection String: " + Membership.Provider.WHAT? + "<br />" );
}
Seems so obvious, but every reference I find instructs me to use the ConfigurationManager, which is what I specifically don't want to do. Although I concede that such may be my only option, and a satisfactory one at that.
I'm perfectly willing to accept the possibility that my question is on par with this:
int i;
try
{
i = 42;
}
catch ( Exception e )
{
Response.Write( "Error assigning literal to integer." );
}
If this is the case, please comment accordingly.
I don't believe there is a direct property that you can use that will give you the connection information. One thing you could do though is subclass your chosen membership provider and implement your own properties to give you the info.
It's generally considered a bad idea to surface connection strings in the UI (i.e. poor security) which is why you won't find readily available properties to pass on the value from classes that have read it from the config file.
You may want to consider addressing the root cause of the problem which is related to deployment. This problem is easily solved by using different configuration files for development, staging and production. Visual Studio has built-in support for automatically managing the deployment of the appropriate config file. Full details here:
http://blogs.msdn.com/b/webdevtools/archive/2009/05/04/web-deployment-web-config-transformation.aspx
Hi Here is a way to get connection string from or by the specified Provider Name (ex MySQL provider).
using MySql.Data.MySqlClient;
using MySql.Data;
using MySql.Web.Security;
using System.Collections.Specialized;
using System.Reflection;
void SomeFunction()
{
Type t = Membership.Provider.GetType();
FieldInfo fi = null;
while (fi == null && t != null)
{
fi = t.GetField("connectionString", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
t = t.BaseType;
}
MySql.Web.Security.MySQLMembershipProvider a =(MySql.Web.Security.MySQLMembershipProvider)Membership.Provider;
string Connection_String_Value= fi.GetValue(a).ToString();
}
By replace 'connectionString' with other Non-Public field name You
can Access its Value too.
By replacing Provider(default) with
Membership.Providers["Name_Of_Your_Provider"] you can get its
connection string too.
So I'm venturing out into the world of Linq and WCF web services and I can't seem to make the magic happen. I have a VERY basic WCF web service going and I can get my old SqlConnection calls to work and return a DataSet. But I can't/don't know how to get the Linq to SQL queries to work. I'm guessing it might be a permissions problem since I need to connect to the SQL Database with a specific set of credentials but I don't know how I can test if that is the issue. I've tried using both of these connection strings and neither seem to give me a different result.
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;User ID=domain\userName; Password=blahblah; Trusted_Connection=true"
providerName="System.Data.SqlClient" />
Here is the function in my service that does the query and I have the interface add the [OperationContract]
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = from c in db.Cities
where c.CITY_ID == 30429
select c.DESCRIPTION;
return city.ToString();
}
The GeoData.dbml only has one simple table in it with a list of city id's and city names. I have also changed the "Serialization Mode" on the DataContext to "Unidirectional" which from what I've read needs to be done for WCF.
When I run the service I get this as the return: SELECT [t0].[DESCRIPTION] FROM [dbo].[Cities] AS [t0] WHERE [t0].[CITY_ID] = #p0
Dang, so as I'm writing this I realize that maybe my query is all messed up?
Try this:
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = db.Cities.SingleOrDefault(c => c.CITY_ID == 30429);
return city.DESCRIPTION;
}
The problem with your query is that it's not returning a string in the var, it's returning an IQueryable. So when you ToString() the IQueryable, it must be returning a string representation of the SQL query represented by the IQueryable.
am using MVC and Subsonic 3.0.0.3 but i cant seem to pin down a specific point for multiple database connection.
normally in normal .net i would have my 2 strings in the web.config file
and have a database class for my project, within this db class i would do something like this:
try
{
conn.ConnectionString = server1;
conn.Open();
}
catch (MySqlException)
{
conn.ConnectionString = server2;
conn.Open();
}
I am trying to pin down the one place in subsonic's created files where something like this would be best to place and maybe an up to date example on how to achieve it. I have googled etc but the examples shown are for an older subsonic.
many thanks
If you look in Context.tt at line 35 you'll see the following code:
public <#=DatabaseName#>DB()
{
DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
Init();
}
This is where the provider is getting setup for you so if you add a BackupConnectionStringName variable in Settings.ttinclude after the ConnectionStringName at line 20 then you should be able to check your connection is working and user your fallback if not. For example:
public <#=DatabaseName#>DB()
{
DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
Init();
try
{
DataProvider.CreateConnection();
}
catch(SqlException)
{
DataProvider = ProviderFactory.GetProvider("<#=BackupConnectionStringName#>");
Init();
}
}
NB You may need to do some clean up to make sure a connection is not left open by CreateConnection.