Configuration Manager returns default connection string - visual-studio

I've added the line
static private readonly string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString;
to my Console App project, and it returns a connection string despite the fact that I haven't yet set one up, and there is no config file anywhere in the solution folder.
It appears to be an ASP.NET database connection string:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Where is VS getting this string from?

I think this has been answered in full here:
Autogenerated Default Connection
Essentially it's a default from Machine.Config.

Related

Xamarin.forms how to auto save user name like browser

I am developing a mobile application using Xamarin.Forms
I had the following Home page contains login info:
How can we have the application to automatically save the user name, so that they do not have to type it in each time (as in a browser)?
You can use Properties dictionary in Xamarin.Forms Application class. And let the Xamarin.Forms framework handle persisting user name between app restarts and pausing/resuming your app.
Save user name by writing it to Properties dictionary
var properties = Xamarin.Forms.App.Current.Properties;
if(!properties.ContainsKey("username")
{
properties.Add("username", username);
}
else
{
properties["username"] = username;
}
Then, when your login screen is about to appear (for example in OnAppearing method) check Properties for user name:
var properties = Xamarin.Forms.App.Current.Properties;
if(properties.ContainsKey("username")
{
var savedUsername = (string)properties["username"];
}
If it's not there, then it means that this is first time when user log in into your application.
A very similar question was posed just a few days ago - my answer on that question also applies to your question: The best way to save Configuration data in Xamarin.Forms based app?
Essentially, you want to store the information using the native settings functionality. I would advise against using Application.Properties for now. It is currently not reliable on Android, and in the past has had other problems. The nuget package referenced in my linked answer is a better approach and will save you some headache in the future.
The right way to be done is through the App settings plugin
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Settings
What i did in my application is.
1) Installed Plugin.Settings from nuget
2)Added to Helpers->Settings.cs (autogenerated file by plugin) the following
public static class Settings
{
private static ISettings AppSettings
{
get { return CrossSettings.Current; }
}
private const string UserNameKey = "username_key";
private static readonly string UserNameDefault = "demo";
public static string UserName
{
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
}
3)In order to keep the username in the Application Context set
Settings.UserName = ViewModel.Username;
4)When you login screen starts
string username = Settings.UserName;
The answer is simple: persistance. Servers do this by setting cookies containing the data (or reference to it) that they want you to see when rendering the form field.
In order to do this in an app (with Xamarin for instance), you need to store the user's data into a file or database somewhere. Since you're using Xamarin you can probably use some sort of ConfigurationManager to keep track of this.
Obviously you could just create a config file in the local storage you have for your app (I don't think you need permissions to create files in that space).
When you have the info stored somewhere, just retrieve it and set the input's value to it.

Telerik report not working

An error has occurred while processing Report 'ReportStandart': Unable to establish a connection to the database. Please, verify that your connection string is valid. In case you use a named connection string from the application configuration file, make sure the name is correct and the connection string settings are present in the configuration file of your application. ------------- InnerException ------------- !
Go to the folder where your report project is.
Open the folder and look for the file "Telerik.ReportDesigner.exe.config"
Open the file in Visual Studio and copy the connection string
Past the above connection string to your web.config
You can find the above here towards the end of the video (3':15'')
In this sample, we have got sqlDataSource by filling connection string:
MyReport report = new MyReport();
string selectCommand = #"SELECT * FROM Sales.Store";
string connectionString = "Data Source=(local)\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True";
Telerik.Reporting.SqlDataSource sqlDataSource = new Telerik.Reporting.SqlDataSource(connectionString, selectCommand);
report.DataSource = sqlDataSource;
In my case, my start-up project has connection string in its config file so I cannot use the connection string again in another project because of this error:
an error has occurred while processing table 'crosstab 1' ...
format of the initialization string does not conform to specification
starting at index 0
This error is because of having 1 more connection string.
Maybe this discussion on the Telerik site entitled Set CrossTab DataSource in code-behind will help.

Umbraco - First run - connection string failed

I just downloaded Umraco (via Web Platform Installer).
It takes me to this web page:
How can I just select 'integrated security'?
That connection string is set to a blank database that exists. I have added 'IIS AppPool\DefaultAppPool' and 'IIS APPPOOL\UmbracoTest' as database owner. The next screen is like this Database configuration is invalid for connection string Data Source=.;Integrated Security=True;Initial Catalog=UmbracoTest:
That connection string is fine, I've used '.' datasource elsewhere with no problems (SQL Express).
Is there any way to get useful error messages?
How can I get this working?
Thanks.
I just ran into the same issue during an Umbraco 6.1.5 installation. My issue was the providerName being empty as suggested, so when I added:
providerName="System.Data.SqlClient"
I was able to install and upgrade my Umbraco 6.1.3 database. My full connection string is:
<add name="umbracoDbDSN" connectionString="server=72.18.**.***,1533;database=mydatabase;user id=emma;password=******" providerName="System.Data.SqlClient" />
The connection string is wrong, trust me :)
Instead of DataSource=. try DataSource=.\sqlexpress
Also ensure that the initial catalog=UmbracoTest is actually the correct name of the database.
Finally, since you are using an Umbraco 6.x version, the log files will be at ~App_Data/Logs but in this case they will just tell you much the same as the install screen, that an SqlException has occurred.
Edit:
Looking at the Umbraco source, the error you see is raised by the following code:
if (_configured == false ||
(string.IsNullOrEmpty(_connectionString) ||
string.IsNullOrEmpty(ProviderName)))
{
return new Result
{
Message =
"Database configuration is invalid. Please check
that the entered database exists and that the provided
username and password has write access to the
database.",
Success = false,
Percentage = "10"
};
}
So my assumption is that you are missing the Provider from your connection string. In your web.config file your connection should look like this:
I had the same issue. I fixed it by adding the IIS_IUSRS user to the Umbraco site directory with "Modify" rights as the setup process is trying to write to the web.config with your connection string. Hope this helps.

How to use new database instance of each MSTest unit test run

I'm using MSTest under Visual Studio 2010 to test an ASP.NET MVC 3 project. I have a SQL Express 2005 DB that I'd like it to use and I want a fresh instance of the DB every time, copied from a template I've included in the project. Pretty standard requirements, I would have though, but I can't get this to work.
I've created a .testsettings file which enables deployment and my connection string looks like this:
<add name="MyDb" connectionString="Data Source=.\SQLEXPRESS2005;Database=MyDbTest;AttachDBFilename=|DataDirectory|MyDbTest.mdf;User Instance=true;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
The test runs OK the first time, but after that it fails with errors like this:
Test method ... threw exception: System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.EntityException: The underlying provider failed on Open.
---> System.Data.SqlClient.SqlException: Database '...\bin\Debug\MyDbTest.mdf' already exists. Choose a different database name. Cannot attach the file '...\Out\MyDbTest.mdf' as database 'MyDbTest'.
The accepted answer in this MSDN thead says to remove the "Database=" connection string parameter. However, if I do that it fails with this error:
Test method ... threw exception:
System.InvalidOperationException: Unable to complete operation. The supplied SqlConnection does not specify an initial catalog.
How do I get this to work?
So far I've come up with a hack to change the DB name at runtime, at test assembly initialization time. This requires a further hack - using Reflection to enable modifying the configuration at runtime (thanks to David Gardiner).
[TestClass]
public static class TestHelper
{
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
RandomizeDbName();
}
private static void RandomizeDbName()
{
// Get the DB connection string setting
var connStringSetting = ConfigurationManager.ConnectionStrings["TheDbSetting"];
// Hack it using Reflection to make it writeable
var readOnlyField = typeof(ConfigurationElement).GetField("_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
readOnlyField.SetValue(connStringSetting, false);
// Randomize the DB name, so that SQL Express doesn't complain that it's already in use
connStringSetting.ConnectionString = connStringSetting.ConnectionString.Replace(
"Database=MyTestDb", "Database=MyTestDb_" + new Random().Next());
}
}
Edit: It's actually even a bit worse than this: I'm having to call TestHelper.RandomizeDbName() at the start of every test that requires a fresh DB, otherwise it gets data left over from previous tests.

Getting "Object is read only" error when setting ClientCredentials in WCF

I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code:
InstanceContext context = new InstanceContext(this);
m_client = new ServerClient(context);
m_client.ClientCredentials.UserName.UserName = "Sample";
As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet.
I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName.
Any ideas?
I noticed that after creating an instance of the proxy class for the service, I can set the Username and Password once without errors and do a successful call to my webservice. When I then try to set the Username and Password again on the existing instance (unnecessary of course) I get the 'Object is Read-Only' error you mentioned. Setting the values once per instance lifetime worked for me.
It appears that you can only access these properties pretty early in the instanciation cycle. If I override the constructor in the proxy class (ServerClient), I'm able to set these properties:
base.ClientCredentials.UserName.UserName = "Sample";
I'm beginning to appreciate the people who suggest not using the automatically built proxies provided by VS.
here is the solution:
using SysSvcmod = System.ServiceModel.Description;
SysSvcmod.ClientCredentials clientCredentials = new SysSvcmod.ClientCredentials();
clientCredentials.UserName.UserName = "user_name";
clientCredentials.UserName.Password = "pass_word";
m_client.ChannelFactory.Endpoint.Behaviors.RemoveAt(1);
m_client.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);
I have similar code that's passing UserName fine:
FooServiceClient client = new FooServiceClient("BasicHttpBinding_IFooService");
client.ClientCredentials.UserName.UserName = "user";
client.ClientCredentials.UserName.Password = "password";
Try creating the proxy with binding name in app.config.
The correct syntax is:
// Remove the ClientCredentials behavior.
client.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();
// Add a custom client credentials instance to the behaviors collection.
client.ChannelFactory.Endpoint.Behaviors.Add(new MyClientCredentials());
http://msdn.microsoft.com/en-us/library/ms730868.aspx
It worked for me.
I was facing same problem, my code started working when I changed my code i.e. assigning values to Client credential immediately after initializing Client object.
here is the solution ,
ProductClient Manager = new ProductClient();
Manager.ClientCredentials.UserName.UserName = txtUserName.Text;
Manager.ClientCredentials.UserName.Password = txtPassword.Text;
This will not happen if the service reference is added through -> Add service reference ->Advanced->Add Web Reference-> Url/wsdl (local disk file).
I was facing this issue where I was trying to create a generic method to create a clients for different end points.
Here how I achieved this.
public static T CreateClient<T>(string url) where T : class
{
EndpointAddress endPoint = new EndpointAddress(url);
CustomBinding binding = CreateCustomBinding();
T client = (T)Activator.CreateInstance(typeof(T), new object[] { binding, endPoint });
SetClientCredentials(client);
return client;
}
public static void SetClientCredentials(dynamic obj)
{
obj.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();
obj.ChannelFactory.Endpoint.Behaviors.Add(new CustomCredentials());
obj.ClientCredentials.UserName.UserName = "UserId";
obj.ClientCredentials.UserName.Password = "Password";
}
I think your problem might be related to the use of the InstanceContext. I thought that was only needed for duplex communication channels from the server side.
I admit I'm not sure about this, but I think in this case you are telling the client to use an existing instance context so it thinks there is already a running service and will not allow changes.
What is driving the use of InstanceContext?
If using a duplex client, when you instantiate it the DuplexChannelFactory within the DuplexClientBase that your client is derived from is initialized with existing credentials so it can open the callback channel, which is why the credentials would be read only.
I second Mike's question and also ask why are you using NetTcpBinding if you are not going to use its inherent transport level security? Perhaps an HTTP based binding would be a better fit? That would allow you to use certificate based security which I believe can be modified after instantiation (http://msdn.microsoft.com/en-us/library/ms576164.aspx).
A shot in the dark but does netTcpBinding allow username and password validation? Try using application layer (SOAP) security using a http binding
or you could just simply check the Credentials
if (client.ClientCredentials.ClientCertificate.Certificate == null || string.IsNullOrEmpty(client.ClientCredentials.ClientCertificate.Certificate.Thumbprint))
{
client.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.LocalMachine,
StoreName.My,
X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("CertificateThumbprint"));
}
In .NET 4.6 I couldn't remove the credentials using Fabienne's answer. Kept getting Compiler Error CS0308 in the Remove method. What worked for me was this:
Type endpointBehaviorType = serviceClient.ClientCredentials.GetType();
serviceClient.Endpoint.EndpointBehaviors.Remove(endpointBehaviorType);
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
serviceClient.Endpoint.EndpointBehaviors.Add(clientCredentials);

Resources