Build SqlCredential in C# Web Service - c#

I'm creating a Web Service using C#. I've a SQL Database in a host, so I'm building a SqlConnection instance in order to be able to execute queries.
But to use SqlConnection you need a SqlCredential, which needs of SecureString in order to be initialized (or to assign a password anyway).
The problem is, that SecureString can be easily obtained from a password textbox, but it's not so easy when you want to build it without it (since it's a webservice, so it doesn't have any GUI).
The only available method I've found is SecureString.AppendChar(), so I would have to build the SecureString by using a loop over my original password string, in order to add its chars to it, which seems quite weird for me.
Does exist any other approach to do it?
Thanks in advance!

Most of the time, people will simply create a Sql Connection with the connection string set in the Web.config.
You can pass the connection string into the constructor of your SqlConnection, like so:
(in the Web.Config)
<connectionStrings>
<add name="nameOfConnectionString" connectionString="Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Then you'd access it like this:
var connectionString = Configuration.ConfigurationManager.ConnectionStrings["nameOfConnectionString"].ConnectionString;
var sqlConnection = new SqlConnection(connectionString);
For more information on the varying types of connections and formats, you can google the info, but SQL Server connection strings usually lists the layouts.

Related

How to add connection string to once for whole solution to use?

Recently I am working on an .Net project. We used EF to handle SQL, when we make an installer of the program, we realize that app.config is visible which mean that the connection string is not safe.
I am looking for a way to add connection string (or maybe secret code and username) to the EF so that the connection string is not visible.
Something like change old code from this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities
'TODO
End Using
to this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities(ConnectionString)
'TODO
End Using
But since we used connect code to SQL all over the place, changing every single line of code is not possible. There is a way I only need to add connection string once?
You’d be better off encrypting the connection string section in the app.config. You wouldn’t need to make any changes.
Storing any sort of configuration in an assembly can be read using a hex editor.
It’s been answered on here before.
Encrypting Connection String in web.config
You’d be better off using a trusted connection if you’re using SQL Server. The user running the app would need to have permissions and no username and password is required.
Save connection string is settings of project properties.
Go in project properties.
Select settings.
Add new setting as connection string and save connection string.
Then you can use it for whole project.

What is the format of a SQLConnection connection string?

What is the format of a SqlConnection connection string that is passed in the constructor method? I have run a search engine search online and all I could find so far is examples like:
"Data Source=(local);Initial Catalog=AdventureWorks; Integrated Security=SSPI;"
"User Id=sa;Server=localhost;Initial Catalog=Test;"
The examples raises questions. Since the SQL Server Management Studio (SSMS) program offers a different set of fields during start up in order to connect to a database, I have to ask how does "Server type, "Server name", "Authentication", "User name" and "Password". Also, is "Catalog" another name for a database table?
You should be more specific about what your goal is. This will provide you with better answers.
Catalog is a different name for database, you're connecting to a SQL server and use catalog to specify the database which you want to access.
Server type is either SQL or Windows Authentication
If you're trying to generate a ConnectionString in a string format but don't know how to format the string. The best way is to use the SqlConnectionStringBuilder . After you've set all the variables in the builder use the toString() method to convert it to a string. That way you don't have to worry about how to format your connectionstring.
If you have the string already, or don't need to generate it on the fly you can put it in your web/app.config and use it directly.
A very basic connectionstring that uses SQL authentication looks like this:
"data source=[sqlserver];initial catalog=[database];user id=[username];password=[password];"
I always look at this website for connection string patterns and examples:
https://www.connectionstrings.com/sql-server/

Is it possible to have two ConnectionStrings with the same name?

Can it is possible to have same name with two Connection String in an application with two datasource like or condition.
<add name="DefaultConnection" connectionString="Data Source=serverName|serverIpAddress;Initial Catalog=DatabaseName;User=name;Password=Password;"
providerName="System.Data.SqlClient" />
Can any body help me to doing this.
It is not possible because ConnectionStrings are maintained in KeyValuePair and with name being the key.
Please let us know why you need such scenario, then we might be able to help you.
If your two databases are configured with SQL Server Mirroring, then you can actually specify a backup server inside the connection string. You can do this with Failover Partner:
Data Source=Primary_Server;Failover Partner=Secondary_Server; ... other stuff...
Then you just have to edit your existing configuration string with both server addresses and the framework will automatically connect to your secondary server if the primary is unavailable.
There's some idiosyncrasies around the usage of Failover Partner though (from what I've read, I haven't used it myself), so I'd recommend reading up on it in depth before implementing it.
If your databases aren't mirrored, you're going to have to implement the failover yourself, probably by abstracting the acquisition of the database connection.
Specify two distinct connection strings in your config (primary and secondary), and then implement some sort of Connection String service that returns the appropriate connection string based on your criteria (i.e. test primary, if fails, return secondary, else return primary, or whatever you want).
Keep in mind that there is a possibility that your server could go offline AFTER testing the string but BEFORE using it, but this is a pretty big edge case. Just keep it in mind if you need to maintain functionality in that situation.
No you can not have two connection string with same name.
So if you can what is result this code:
var connectionString=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Connection string store in KeyValuePair object.
The application can optionally specify the connection name in an
application configuration file that provides the required
keyword/value connection string values. In this case, you cannot
supply them directly in the connection string. The Name keyword is not
allowed in a configuration file.
When the Name keyword is not included in the connection string, a
non-empty values for Provider keyword is required.
This keyword is mutually exclusive with all the other connection
string keywords.

Sharing SQL Server Between Multiple System

I have three computer in a office and I have installed my C#-2005 Project on all three
computers. But Problem is that Boss wants Sql-server-2000 on One PC out of three and other
would share the same.
I don’t know how to share Sql-server-2000 between three PC?. How to do?.
Confusion:-
Thanks for your co-operation but here I have a confusion on majority people said to check
TCP/IP address and consider the Connection string as per main server from client PC.
Suppose I have financial project and there would be thousand of connection string in a
project. As per above I have to change thousand of connection string as per main pc.
Now think it is a one customer's need If I have ten cutomer having same offer than think How much time I have to waste on it?. I have to modify thousand of connection string ten time more?.
If it is true than it will take lots of time on installation to each customer.
I don’t know if it is only way?.
The Connection string I have utilized on my each winform is as below:
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Here suggested about Config File and same I don't know if some body give me idea about how to consider it with my C#2005 project than it will save my lots time.
When you connect to the database in your code, you'll a database connection string of some sort somewhere in there. Figure out the connection string for the Database server and set your code to point to that database server's connection info; I'd bet you currently you have it pointed at localhost
If you're using SQL Server you may need to enable remote connections on the database server.
added: you may need to modify firewall settings as well to allow SQL Server traffic (thanks Jared)
.
Edit: For putting the configuration string into a central location.
Your posted code
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Change to
Assuming your application has a App.Config file then you'd add an entry in there like
<add key="DBConnectionString" value="server=.;initial catalog=maa;uid=mah;pwd=mah"/>
And change your C# code to be like
string connstr = ConfigurationManager.AppSettings["DBConnectionString"];
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Putting the ConfigManager call into a class might be a good idea if you have a lot of settings to retrieve and/or believe the configuration storage methodology might change down the road. Going with the above example is WAY better than having the string literal scattered throughout your code.
Enable theTCP/IP connection in SQL Server. So that you can connect remotely from any pc within the network
check here
If your problem is that you embedded your connection string in the code, then you are going to have to do some refactoring. These would be the general steps, you will have to tailor them a bit to your situation.
Add your connection string to the app.config file.
Create a static/shared method that will read the connection string from the
config file.
Do a find and replace in your solution to replace all
of the hard coded connection strings in your code with the (class
and) name of the method that gets the connection string.
This is probably going to be easier than rewriting all of your data calls to use something like enterprise library or EF.
You will need to do as the others suggested, such as changing the connection string and enabling TCP/IP within SQL Server, but you will also likely need to configure your firewall to allow requests to SQL Server (default port of 1433) through.

Problem in Connection strings

I changed my project connection string through Code, as a result, Connection strings in all Config files changed. but problem is here that in datasets, some tables have different connection strings:
app.config connection string: "Datasource=USERPC; initial Catalog=MYDataBase; integrated security=False; User ID=sa; Password=user"
tablAdapter Connection string: "Datasource=USERPC; initial Catalog=MYDataBase; integrated security=False; User ID=sa"
what is my problem and How can i do solve it?
Go to Project Properties -> Settings Tab set there Connection String Value to application level instead of app.config. If you are using typed dataset the connectionstring defined by them itself so better do not alter them. For using conenctionstring in you code. Go directed as above. Then create a property or function that will access the value using Settings CLass.
In vb we use My.Settings.Default.ConnStringName
Are you sure, that your connection strings won't work. Cause all what is missing is the password and if i remember correctly if you fill in a password and read the connection string afterwards back you won't see the password anymore. But that's not a bug, it's a security feature.
To override this behavior you should take a look into the Remarks section of the SqlConnection

Categories

Resources