Is it possible to add MySQL connection to another Class (as public) in C# and call the connection in other classes instant of typing all connection code lines every time and for each part of the program ?
Is it secure and correct to do something like that ?
For EX, in PHP we can use include, is any other way in C# to do the same ?
I know we can use Public classes in C# and call them in other part of program, like using function in PHP, so I would like to know if it's secure to use same method in C# for MySQL connection !
And finally, if someone can explain me how to make it happen (have MySQL connection in separated class) or send me a link where it explain that !
Well, as I learned, it's not a good idea to use MYSQL connection info into the app and so I just created a PHP file on my server and I use webclient post to send and receive data to and from the PHP file and I have my database connection into my PHP file too.
What you are looking for is called data Access layer. I suggest you to look at entity Framework also.
Related
I have a C# ASP.Net MVC web application. I am trying to successfully connect to an Oracle database.
I am getting a "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" error.
I do not have access to the server the database is on. But I do have access to Oracle SQL Developer, which I have installed on my machine.
In my C# code I am setting the connection string like this:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd,1521;User ID=userid;Password=password;";
abcd should be the service name. and 1521 is the port number.
I understand that my connection string might not be the cause of the error, but I want to rule it out. Also, I know the more proper way of doing things is probably to set the connection string in web.config and retrieve it as needed, but I am doing it this way just for ease of testing until I know I am able to connect to the database successfully.
What is weird to me, is that I was able to connect to the database using Oracle SQL Developer using the same IP address, port number, service name, username, and password I am using in my connection string.
Primarily, I would like help knowing if my connection string looks valid. If you have additional thoughts about what the issue could be, that would also be appreciated.
using this command in Oracle SQL Developer:
select sys_context('userenv','service_name') from dual;
I am able to determine that the service name I am using in my connection string is one that exists, although I guess this does not guarantee that the service is up.
I am not a DBA by any means. In fact, I am still new to .Net and web development in general, but I have been assigned to troubleshoot this issue. Any help is appreciated.
I don't recall seeing the following format
DataSource=XXX.XX.XXX.XXX/abcd,1521
as valid (which doesn't mean its not, I've just not seen it).
The more common ones I've seen are:
DataSource=XXX
where XXX is a reference to your tnsnames.ora file
DataSource=//nnn.nnn.nnn.nnn/service_name
DataSource=//nnn.nnn.nnn.nnn:port/service_name
So maybe try those variants and see how you go. There's also more definitive list of alternatives at https://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
I ended up figuring this out. My connection string format I don't t think was correct. I changed it to be:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd;User ID=userid;Password=password;";
Basically, I just took off the port number. In my case, the default port was what I needed anyway. Not sure what I would have done had I needed to specify the port number.
As new to Oracle I struggled a few days finding solution to this
this article helped me alot
As of Oracle 21 c
This is my Connection string for C#
Password=dev;Persist Security Info=True;User ID=Dev;Data Source=localhost:1521/XEPDB1
Keep in mind Dev is Username which is also the Schema name for Oracle
I'm a beginner so I'll try to explain what I'm trying to do so please bear with me:
I'm developing a db application on C# and I'm using MySQL (Workbench) to manage my database so when I establish the connection in the C# project I use the following connection string:
string MyConnectionString = "Server=localhost;Database=catalogue;Uid=root;Pwd=1234;";
But I'd like to send the project to a friend to check it out so what would be the easiest way to send him the DB as well? Is there a way to send it as a single file (something like an Access db) and modify the connection string so that the project works without him adding the db to the localhost.
Thank you!
I have one solution with one project in it. This project is an asp.net mvc web application with xsockets.net websocket server (everything merged inside single project).
Everything was working for a few months, until today. Today I decided to update entity framework and xsockets.net. There were few errors on the way, but I solved almost all of them... almost.
Well, the part of my project that runs websocket server is not using correct connection string. I mean, I can login to my web application, and move around it (so asp.net mvc is using correct connection string), but my websocket server (which is using the same database) cannot gather any data from database, since it's throwing incorrect connection string exception.
And since everything is in the single project, with single web.config file, I don't know what to do next. I don't believe that this is websocket related error, maybe entity framework update has changed something? Anyways, is there any way to explicitly use connection string inside of a class? What else I can do to fix that?
When Entity Framework connects to create the entity objects it also establishes the connection string to that database. This usually isn't a problem since that project is referenced by another program that is overriding the server connection string with their own app config (or web config).
Typically in code when connecting to an instance of Sql Server, you write your code:
using ( MyServer context = new MyServer(myconfig.ConnectionStrings["MyServerName"]))
{
}
If you exclude providing he connection string when creating the instance of your context, you risk catching the default value created when you updated entity framework. So this probably answers both your questions: the why is it changed your connection string. The explicit use is the code example above.
I am New to the more enhanced features of the C# and .NET coding practices
I have been trying to Find A solution to using a particular method in C# for Winforms, Windows Services And ASP.NET web Applications where you program your connection to SQL and Convert the C# Code file to a dll to be used in your project.
The idea is to Create the Connection and Convert it to a dll so that every time you start a function and need to make a database connection you will just write it where you say
Function ABC
{
//VB Version would be like this as i have seen this
Dim DCDLL as New Dataconn
//Where 'DCDLL' is the DLL file which is being declared as a new dataconnection
//C# Version would be Alon these Lines
SQLConnection DataConn = New SQLConnection(DCDLL)
}
I have only seen the VB Code version of the Call so I am not keen on the C# Method that this would be done
Meanwhile The DLL Holds all the other code like
string ConnectionString =
"Data Source=Datasource; UID=User; PWD=Pass; Persist Security
Info=True; Initial Catalog= Catalog";
Dataconn = new SqlConnection(ConnectionString);
Dataconn.Open();
the purpose of the DLL would be to handle the connection to the database, Open it catch errors if dataconnection is not successfull and close the connection if needed so that you dont have to programatically do this every time. Also it is only responsible for the connection therefore you can use a function to call the connection execute the procedure and whatever else is required.
The idea of using a DLL is just to make the Connection settings to the Database a little more secure, the Connection obviously wont become super secure but it adds more security than having the Code in you code pages etc.
i have spoken to and seen people use this type of method but my research on how to achieve this via google and other sources does not seem to understand what i am searching for.
I am trying to understand that when i code this file how it must be done as to ensure that it handles the database connection correctly without issues and doesnt break.
If anyone can Give me Examples in C# of how to do this it would be appreciated or if you know of any pages that have explained how to achieve this i would be most grateful for your assistance
You should put your connection strings in app.config / web.config, and use c# to get the values...
Get ConnectionString from app.config in c#
You can also encrypt the connection string...
http://msdn.microsoft.com/en-us/library/89211k9b(v=vs.80).aspx
I am designing a desktop application in C#, which needs to be connected to my online mysql database. I tried to give access in control panel a "%" which means from any IP, but it is not working. May be the hosting provider (bigrock) not allowing that.
Alternatively, I am trying to write some code in online on PHP which will get the "sql" as parameter and returns the output as JSON format using json_encode.
Is there any alternate methods which is better approach.
What error do you get when you try to connect? Timeout = firewalled; Permission denied = permissions not right etc.
One solution is to create a proxy with pre-coded queries (let's call then "stored procedures") - you can then say "Run query 5, parameters A, B and C". As this would be server-server (not public) you just need to add some basic authentication system (e.g. shared rotating key, checksum using parameters etc), but also ensure the queries are not dangerous if any parameters are thrown at it.
Disclaimer: It's a solution, but I'm not actually recommending that I'd do it unless you're very sure it's safe!
Do you have Cpanel ? If yes, then try adding your host in remote MySQL.
Here the link http://www.liquidweb.com/kb/enable-remote-mysql-connections-in-cpanel/ if you are unsure on how to do that.
I'd advise that you do not create a wildcard user that can connect to the database from anywhere using embedded MySQL credentials in your application. This is a bad idea.
It would be extremely easy to determine the credentials used by your application and then a malicious user could directly connect to your DB server and begin issuing queries to your database.
They will be able to issue SELECT statements for any information in your tables, even info they shouldn't see. It then becomes much easier to exploit any known or unknown vulnerabilities in MySQL much easier since now they have console access and can send data directly to the server. If the account has the DELETE privilege, they can erase all the data in your table(s).
Also, having a PHP script that issues queries provided by the application/end-user is not ideal because one can still freely issue queries. While that option is better than giving blanket access to a remote user, it is still a bad idea.
The way to go would be to identify all of the information that the C# application needs to access, and how, and write a simple web service/API that will receive parameters and issue its own queries and return the results using XML, JSON, or even SOAP. Try to abstract the database access as much as possible from the outside world for the best security.
Hope that helps.
I would do the following:
Create a user with the host of your public ip (www.whatismyip.com).
If that doesn't work, create a user with your host as your public ARPA/PTR record:
>nslookup
> set q=ptr
> 8.8.8.8
Non-authoritative answer:
8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com
8.in-addr.arpa nameserver = ns1.Level3.net
8.in-addr.arpa nameserver = ns2.Level3.net
The host would then be set to google-public-dns-a.google.com.
The second worked, and I am not sure why for me on a project I worked on in the past, where you would have thought the IP address to be sufficient.
I am not sure if you have root access or access to my.cfg. If you can edit it, make sure the line "skip-networking" is commented or removed and it contains line "bind-address = *". Restart mysql after editing config.
For security reasons you shouldn't access the database directly over the (public) network.
One way is to write a php script on the database server and access it via HTTP/POST.
You should authenticate the client via username and a hashed password. The data you are sending should be encrypted (eg with the users clear text password). Don't send complete queries, only what you want to do and the parameters. As example, you want the orders for the customer, you can send a post request with the following parameters
user=abc,password=9151440965cf9c5e07f81eee6241c042a7b78e9bb2dd4f928a8f6da5e369cdffdd2b70c70663ee30d02115731d35f1ece5aad9b362aaa9850efa99e3d197212a,data=EncryptedData
You can notice, that the password is an SHA512 Hash.
The data can be json or anything else:
{
"Command": "GetOrder",
"Limit": "10"
}
In your php code you do the following steps:
1. Authenticate the user, if the password is not correct, respond with error code etc
2. Decrypt the data
3. Execute a query
4. Return the result as encrypted data
If you don't want to store the clear text password in your database, you could store in your database the hashed value and use a double hashed value for authentication and single hashed value for encryption.
If you wan't to execute the queries with parameters from the request you should use prepared statements to prevent sql injection.
More information about en/decrypting in php see: http://php.net/manual/de/ref.mcrypt.php
Like some answers suggested, I think you are firewalled by bigrock.
Now if you want to use AJAX/PHP, you need three things:
- your C# class to send requests and receive the result
- your HTML/JS (or jQuery) file to receive the request and hand it over to your PHP. Then send you the result.
- your PHP file to query your DB.
The AJAX seems superfluous to me, you could just send your query passing it through POST or a GET parameter (i.e. example.com/query.php?req='SELECT * FROM clients')
The code would be as follow:
C# using this class made by Ali Ahsan Rana:
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.example.com/query.php","POST","req=");
//use System.Web.Script.Serialization and myRequest.GetResponse();
Some tutorial on System.Web.Script.Serialization.
On the PHP side:
<?php
$request=$_POST['req'];
$dsn = 'mysql:dbname=mydb;host=example.com';
$user = 'ajay';
$password = '0000';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$response = $dbh->query($request);
while ($rep = $response->fetch())
{
$response_array[] = $rep;
}
$response->closeCursor();
$return = json_encode($rep);
return($return);
?>
That's a quick draft but should work AFAIK.