In order to insert data into an SQL Server database on an Android application do I simply need to execute a query ? I have the following code :
public int SaveUser(User user)
{
int r;
lock (locker)
{
connection = new SqlConnection("Data Source=" + path + ";Initial Catalog=DB;User ID=sa;Password=***********th");
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO tblUsers (Username, UserEmail, FirstName, LastName, FacebookID) VALUES (#Username, #UserEmail, #FirstName, #LastName, #FacebookID)";
command.Parameters.AddWithValue("#UserEmail", user.Email);
command.Parameters.AddWithValue("#Username", user.UserName);
command.Parameters.AddWithValue("#FirstName", user.FName);
command.Parameters.AddWithValue("#LastName", user.LName);
command.Parameters.AddWithValue("#FacebookID", user.FacebookID);
r = command.ExecuteNonQuery();
}
connection.Close();
return r;
}
}
And I get the following information from the facebook-sdk login, so I simply need to execute that query in order to insert the data to the database? Is it right to use the sa account? Is inserting data into a database on an Android application done the same way it's done on a Windows application ? Until now I used the Microsoft Access and it was horribly simple and easy, but now as I moved on to SQL Server 2008 I'm kinda clueless.
Ok this is not really a proper answer, but I did not want to keep making comments.
It seems to me that what you really want is a DB on a server and not in your android app, because if users are added in massive amounts then those users cannot be coming from the android OS itself, they must be coming from an external source, ie. the internet.
So if they are coming from the internet you need a central storage location, which is your server. An ASP.NET server hosting a SQL Server instance.
You will need a domain name, and a hosting solution. Use either MVC controllers or WebAPI to set up your website and/or services that interact with your SQL Server instance. I would recommend you use Entity Framework as well it would make your life a lot easier.
You have many hosts, AZURE is one, but its expensive. But the least it will cost you is something like £8 a month to host databases.
You would design your MVC website+services, or WebAPI (just services) using Visual Studio and use the settings the server host gives you to upload it.
Once the services are up then its a simple matter of making HTTP get/post calls to your server to get and set data in your database, and your android APP will act like a client.
I did this whole thing a week ago for a very simple scenario and it works well.
You would have to follow best practices on how to secure your web service, using some sort of authentication mechanism so only authorised users can access your data.
I hope the above gives you a general idea of how it can be accomplished. Its very high level and you will have to google each stage, but its pretty simple if you know some basics.
That's all I can say...
Related
I have built a C# application for my client and I am hosting the database using Microsoft Azure. I found that in order for the client to access the database I need to add their client IP into the firewall configurations. Is there any way that this could be done automatically once they launch the application or if there is another more efficient authentication method which could be used since the application will be download from a website and used by anyone so I would need a method to grant access to anyone who downloads my application. I am fairly new to Microsoft Azure so forgive me if I come off as stupid I just need some advice. Thanks in advance.
Programmatically adding each ip address:
using tsql:
If you want to add ip address to database firewall programatically, you can run the below stored proecedure in the your Azure database.
sp_set_database_firewall_Rule at MSDN
-- Create database-level firewall setting for only IP 0.0.0.4
EXECUTE sp_set_database_firewall_rule N'Example DB Setting 1', '0.0.0.4', '0.0.0.4';
Using Commandline:
You can use SQLCMD.exe to execute stored procedure sp_set_daabase_firewall_rule
Using ADO.NET:Reference Blog Post
String clientIPAddress = Request.UserHostAddress;
using(SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlAzureMaster"].ConnectionString)) {
sqlConnection.Open();
using(SqlCommand sqlCommand = new SqlCommand("sp_set_firewall_rule", sqlConnection)) {
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlCommand.Parameters.Add("#name", SqlDbType.NVarChar).Value = clientIPAddress;
sqlCommand.Parameters.Add("#start_ip_address", SqlDbType.VarChar).Value = clientIPAddress;
sqlCommand.Parameters.Add("#end_ip_address", SqlDbType.VarChar).Value = clientIPAddress;
sqlCommand.ExecuteNonQuery();
}
}
2.Refreshing the cache post the firewall rules change
Once, you programmatically add the firewall rules, you have to update the authentication cache which is holding logins, firewall rules for the database.
You need to call below command. DBCC FLUSTHAUTHCACHE on msdn
DBCC FLUSHAUTHCACHE
Note: Adding range of ip address for a office network:
If your client will be working from an office network, you can get the range of ip addresses for that office network and add them. It will avoid you to add the ip address every time to the database. Database supports 128 IP configurations at a time. Make sure that you are not going beyond 128 limit.
There's no way can add the client IP into Azure SQL database firewall automatically.
But you can set the firewall range to allow the all database user connect Azure SQL database from any client IP: set the firewall range from:
0.0.0.0---255.255.255.255
But as #Caurav Mantri mentioned, you must need think about the database security issue to protect the SQL database.
Please reference:
ransparent data encryption for SQL Database and Azure Synapse
Always Encrypted: Protect sensitive data and store encryption keys
in Azure Key Vault
Hope this helps.
While i've been debugging my code, I've been writing the output to the console so that I can monitor the errors and sql output. Naturally to protect against sql injection I have parameterised the queries where needed. After reading some articles online regarding the methods by which some injection attacking programs work, I now question whether the below practice is a good idea anymore.
Consider the following method.
public void MyQuery(int item_id)
{
string sql = "SELECT * FROM table WHERE item_id = #id";
SqlCommand sqlQuery = new SqlCommand(sql,conn);
sqlQuery.Parameters.Add("#id", SqlDbType.Int).Value = item_id;
try
{
conn.Open();
sqlQuery.ExecuteNonQuery();
conn.Close();
}
catch (SqlException ex)
{
Console.WriteLine(sql);
Console.WriteLine(ex.Message);
}
}
on my dev machine the console output is fine - no risk here. But if i were to leave the code as it is now when the application was live, would that potentially open up other avenues to exploit?
Im aware that if i were to have done MessageBox.Show(ex.Message); that would certainly be bad due to it being in your face.
You're deploying a WinForms application that connects to a SQL Server with credentials that apparently allow the application to write to that SQL Server.
Leaking SQL errors to the console is the least of your worries.
A malicious user can simply use the credentials used by your application to execute arbitrary SQL on that server.
Anything you deploy on a client machine must be considered insecure. Leaking queries is not the problem (the user could decompile your application or check its resources and inspect the SQL strings), the problem is that the client has a direct database connection.
If you want to prevent the client to know where the database is, what its credentials are and what queries your application executes, you must remove all this code from your application, and let the database stuff happen on a different machine altogether. You can then talk to this machine through a web service, for example.
Then the web service handles authentication, and refuses to execute any action for a user that isn't authenticated.
I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.
I'm currently developing an application based on ASP.NET MVC3, SQL Server 2008 and EF with database first.
My application requires every user to have it's own SQL Server database. These databases all have an identical structure.
My customers are identified with a customercode, e.g. fgt. This code is provided in the url.
I need to know how can I retrieve the customercode from the url and set the connection string accordingly.
Thanks for the help
My idea is to connect to the database once the customercode is retrieved from the URL and then prompt to user to enter his username and password for access data.
But yes, is a good idea to create a database to store the connection string of each customer.
Can anyone write the code that I need for do this please?. I am new to asp. I come from php.
(I'm just learning English. Sorry about the bad grammar)
Try something like this to get started:
string customerCode = Request.QueryString["cust"].ToString();
string myNewConnString = ConfigurationManager
.ConnectionStrings["MyDatabase"]
.ConnectionString
.Replace("[placeholder]", customerCode);
Where your connection string in your .config is something like this. Note that I've assumed you'll place a token to be replaced ([placeholder]).
<add name="MyDatabase"
connectionString="Data Source=192.168.0.1;Initial Catalog=[placeholder];User ID=foo;Password=bar"
providerName="System.Data.SqlClient" />
Suggest that you whitelist your customers and their connection strings.
setup a web service on your side.
your deployed application calls your web service using the customer code.
web service validates the customer code, and returns a valid conn string.
customer's app keeps the conn string in memory (session, cache, whathaveyou).
This would allow you to ensure the conn string is always valid for a given customer code. You'd have fine grain control on access to the database for any reason (non-payment, etc). Your service would have a few hits thanks to any caching that you build in.
maybe sqlshard could help you in using multiple databases?
http://enzosqlshard.codeplex.com/
Sounds like pretty insecure solution. What if customer put another customer code in URL? Where is validated if customer can access that code if you don't have any central database with customer's permissions?
You need authentication and some central store (additional database) where you will validate that user accessing the application has access permissions to provided URL. It will also validate if such database even exists. Next you need just SqlConnectionStringBuilder and use the customer code as a name of database (or part of the name). For security reason each database should have a separate SQL account with permissions to read only from that database. This db account can also be stored with that central storage with encrypted passwords.
There can be additional complexities if you also expect dynamical adding or removing customer codes = databases. That would require high privileged account to manage logins, accounts, databases, etc.
Because you are asking how to get part of Uri it looks like you have almost no experience with ASP.NET MVC and perhaps with everything related. You should definitely ask any more skilled colleague or boss to review your architecture because at this point it looks like you are going to have serious problems and you can develop very insecure application which can significantly harm reputation of your company and your customer.
We are trying to build a Help Desk ticketing system just for intranet. Deciding upon the ASP .NET (C#) with Visual Studio 2008 Express (think we have a full version floating around if we need it). Nothing fancy, couple of pages grabbing NTLM information, system information and storing it along with their problem in a database. Goal is to make it simple, but instead of using our SQL Server 2000 back end, the admin wants me to use MS Access. I have the GridView and connections running smooth. Can pull select queries until my heart is content. However, tying in a couple variables with a text box on a submit button into say an INSERT statement.. well I don't even know where to begin with MS Access. Every internet example is in VB .NET plus seems to be hand coding what Visual Studio has already done for me in a few clicks.
Is MS Access going to be too hard for all we want to do? If not, where do we begin to simply submit this data into the tables?
Edit: After a bunch of playing around we have the OleDB working. It's not pretty, yes SQL Server would be awesome but, sometimes you just have to play ball.
Edit: Anyone looking for an actual coded answer, here you are. There has got to be others out there in the same boat.
string userIP = Request.UserHostAddress.ToString();
string userDNS = Request.UserHostName.ToString();
string duser = Request.ServerVariables["LOGON_USER"]; //NTLM Domain\Username
string computer = System.Environment.MachineName.ToString(); //Computer Name
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\helpdesk.MDB;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO ticketing ([user], [comp], [issue]) VALUES (#duser, #computer, #col3)";
cmd.Parameters.Add("#duser", OleDbType.VarChar).Value = duser;
cmd.Parameters.Add("#computer", OleDbType.VarChar).Value = computer;
cmd.Parameters.Add("#col3", OleDbType.LongVarChar).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
conn.Close();
The admin is nuts. Access is an in-process database, and as such is not well suited for web sites where users will be creating or updating records.
But as far as creating INSERT queries go, Access is no harder than anything else. If you can't create INSERT queries for Access you'll probably have trouble with SQL Server as well.
I also suggest using SQL Server, but considering your problem:
What is your problem writing an INSERT query for Access ?
You should make use of the classes that you'll find in the System.Data.OleDb namespace:
OleDbConnection
OleDbCommand
Quick'n dirty code (not compiled whatsoever):
OleDbConnection conn = new OleDbConnection (connectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (#p_col1, #p_col2)";
command.Parameters.Add ("#p_col1", OleDbType.String).Value = textBox1.Text;
...
command.ExecuteNonQUery();
There are some caveats with the OleDb classes however (like adding the Parameters to the collection in the order that they occur in your SQL statement, for instance).
Don't bother with Access. Use SQL Server Express. There's also an admin tool for it that looks like the full blown SQL Server management tool.
Access has its place, and can usually do more than what most people give it credit for, but yes you want to use SQL Server in ones of its many forms (eg. SQL Server Express) or another proper "server" database for a web app like this.