making a client server application of sales inventory system including sql database in c# - sql-server

i am a beginer and i am making a client server application in c# using sql database.
i am using just two computers, at one computer i want to store my database as well as the application will also run on the same computer it one computer is the server and the client both and the another computer will be a simple client that will access the database.
can any one help me how shoud i write the code for both systems to connect the database.
thank you.

To connect to SQL Server from C#.NET, you need to create a connection string such as below:
private SqlConnection connection;
private string connectionString =
#"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid", connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.

Related

How to access LocalDB without SqlServer from a winforms app c#?

Scenario:
I have programmatically created a Database on Master using an appropriate connection string and added tables to it. But when I tried to access it to create a stored procedure I cannot as it says, it does not have access to perform any action on DB.
I used this query with C# and tried to create the stored procedure.
//Connection String ("Server=localhost;Integrated security=SSPI;database=master") => For Createing Database
//Connection String ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\MyAppDB.mdf;Integrated Security=True") => For trying to create stored procedure on already created Local DB
string AccountEmail = "CREATE PROCEDURE [MyAppDB].[dbo].[usp_AccountEmail]( #Email varchar(max)) AS SELECT Username FROM [dbo].[User] WHERE Email = #Email";
SqlCommand mySP = new SqlCommand(AccountEmail, sqlcon);
using [MyAppDB].[dbo].[usp_AccountEmail] resulted in Exception of specifying the database name. But when I tried the same like [dbo].[usp_AccountEmail] it executed and created a stored procedure on master but that's not what I want, I want it to be created on localDB.
The Problem:
I want to add a stored procedure to the already created database and I want to use the DB without installing any SQL Packages by the client. Just clean install of my app and run which connects to the local DB which is created programmatically by my app. I am struggling with attaching the DB with the installer and if I even do the connection string from the app cannot get the proper path of the attached DB which the client chooses (not definite).
Common Question:
is there any common approach to attach local DB with the set of files to the installer so that the client doesn't need to install any other packages?
The Goal:
All I want is to create an installer that has DB and AppData which does not require any additional packages to be installed and the app uses the DB to store and retrieve the data plus the database already has tables and stored procedures.
Please Help me with this Guys. Thanks in advance.

How do I generically reference a local table in a SQL Server database from an assembly installed in that database?

Let's say I have an assembly with a method does_stuff() that I've installed in an SQL server database. I want this method/storedproc to refer to a specific known table in the database. How do I get does_stuff to access the contents of the table without ever knowing where itself is hosted?
Let's say does_stuff is supposed to access table info_config.
If it was hosted in database ALPHA, it would access ALPHA.info_config
If it was hosted in database BETA, it would access BETA.info_config
I know how to open DB connections etc with ADO.NET, but those require specific server and database strings. I need flexibility so that the assembly does the same thing no matter where it is hosted.
Google search is giving me nothing.
Thanks in advance
All you have to do is use a context connection.
At the moment it may not seem obvious, but CLR code always executes in some context. There is always something (somebody) that executed the code directly or in some parent scope (stored procedure calls CLR function, CLR trigger fires on insert etc). When program execution reaches context connection, it just takes connection parameters (server, database, SET options etc) of that scope.
I want this method/storedproc to refer to a specific known table in the database.
After context connection is opened, you are querying your database as usual.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM MyTable");
SqlContext.Pipe.ExecuteAndSend(cmd);
}

Script to replicate SQL Server data dynamicaly

I have an access 2010 application with a SQL Server database.
But I need to do an offline version. So I thought I would create a local SQL Server database on their computers then they can run a script to update their data before they go on the road.
NOTE: There won't be any sync. The data in offline mode is only for read-only and any changes will be lost.
I tried with Management Studio like this:
But I realized that the data is hard coded instead of doing inserts from selects.
Is there any easy way to create the script?
What I have so far is my pass through query in access to create the backup of my online database.
Then I have my pass through query to restore the backup to the local server.
The only problem is how can I build the connection string for the second query. It's currently set to this one
ODBC;DRIVER=SQL Server;SERVER=010-068\SQLEXPRESS;UID=marcAndreL;Trusted_Connection=Yes;DATABASE=SMD
but because it's a different database for everyone, it won't work.
How can we build a custom connection string?
I am using SQL Server Express 2012 and Windows Authentication, so using the answer provided here, I find this works for me:
Sub TestCon()
Dim cn As New ADODB.Connection
cn.Open ServerConLocal
End Sub
Function ServerConLocal()
''OleDB Connection
ServerConLocal = "Provider=sqloledb;Data Source=localhost\SQLEXPRESS;" _
& "Initial Catalog=Test;Integrated Security=SSPI;"
End Function
For an ODBC connection string in a Pass-through query, this works for me:
ODBC;Driver={SQL Server Native Client 11.0};Server=localhost\SQLEXPRESS;Database=test;
Trusted_Connection=yes;
Take a look at download-only articles for merge replication. MSDN.

Help with MS Access and SQL Server 2008

I need somebody to point me to the right direction, I have a MS Access DB that is updated by HP devices, and I have to sync it with the SQL Server 2008.
I have a few Ideas, and I would like to know what do you think about this:
Is there anything like triggers on access? if so can I comunicate with a SQL Server?
Is there any way to use VBA so access tell my VBA macro or whatever to make an update on SQL Server?
Is there a simple way to connect from VB 6 to SQL Server 2008?
Using a script that run at background and check DB at X minutes or seconds.
Any other ideas or suggestions are very welcome.
Thanks and like always sorry for the english.
Just to add a few points to adopilot’s answer
1) Access 2010 does have triggers and stored procedures but they are more about native access/jet tables as opposed to linked SQL tables I believe.
2 & 3) If you want to connect VB6 or VBA to an SQL server then the technology to do that is called ADO for example here is some code to open a connection and run a SQL statement
Dim dbCon as NEW ADODB.Connection
dbCon.ConnectionString = strSQL_con_string
dbCon.Provider = "sqloledb"
dbCon.Open
dbCon.Execute “UPDATE tblFoo SET bar=5 WHERE Foo=1”
dbCon.Close
4) You can either do this client side with a timer/wait event in VB6/Access or do it server side with a SQL job, not sure which is best for your situation given the limited information provided
You can refer to either the SQL Server database or the MS Access database inline in your SQL:
UPDATE SQLTable (ID, Stuff)
SELECT ID, Stuff
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'c:\External\MyAccess.mdb';'admin';'', Table1)
-- From databasejournal
You can execute this query using ADO with a connection to SQL Server
-- Connection strings
You can also do the same from the Access end with ODBC
Dim cn As New ADODB.Connection
scn = "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" _
& DBFullName
cn.Open scn
s = "INSERT INTO [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server\Instance;Trusted_Connection=Yes;" _
& "DATABASE=test].Table2 (ID, Stuff) SELECT ID, Stuff FROM Table1"
cn.Execute s
You can run ADO with VBScript, or other suitable script and use Windows Task Scheduler to kick the script off at suitable intervals. This is not without pain.
You can try to link MS Access database to SQL server,
Now you can querying data from SQL server which is in MS Access.
I do not know about trigers on MS ACCESS but you can implement some loops in
MS SQL to periodicity count or select data for cheking new one.
To make linked server in SQL MGM Studio on Object Explorer -> Server Object -> Linked server -> right click -> New linked server
After then in new query simple call any table like
Select * from [linked server].dbo.mytable
In MS SQL there is WAITFOR command which You can implement

Can SqlServer be configured to not execute stored procs submitted as strings?

Scenario A:
SqlConnection con = new SqlConnection(myConnString);
SqlDataAdapter adp = new SqlDataAdapter("EXEC spGetUserInfo 42", con);
DataSet ds;
adp.Fill(ds);
Scenario B:
SqlConnection con = new SqlConnection(myConnString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "spGetUserInfo";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserID", 42));
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds;
adp.Fill(ds);
The question
In a discussion of how to fortify SqlServer against sql injections attacks separately from modifying the underlying application code calling the database, the question was raised whether SqlServer could be configured to simply not execute stored procs written in the manner of Scenario A, only allowing execution requests written in the manner of Scenario B. The theory being that Scenario A would be vulnerable to injection if the underlying app didn't perform input validation, allowing something like "EXEC spGetUserInfo 42; drop database foo; --" to possibly be executed, whereas Scenario B would simply fail to execute when SqlServer fails to convert "42; drop database foo; --" to an integer.
Is it possible to configure SqlServer to not execute stored procs called in the manner of Scenario A?
Not so far as I know, and I have looked pretty hard for a way to do it.
The closest thing that I can think of would be to somehow do something with the network so that only RPC connections to the SQL Server were allowed as the ".StoredProcedure" invocations normally come through RPC, but dynamic SQL requests cannot. However, I do not know enough about network management and server management to know if that is doable.
The other (and more standard) approach is to simply give users/apps only CONNECT access to your database, but not access to ANY of the database's objects. Then create stored procedures in their own SCHEMA and grant their owner/schema normal access to the database objects (tables, views, any other stored procedures, etc.). Finally then, grant the users EXECUTE access to the stored procedures in that Schema. This still would not prevent every possible dynamic SQL scenario, but it does take the danger out of them (and the point out of most of them).
Odds are the SQL Server database engine will never prevent that from happening. The reason for this is that as far as the SQL Server knows when those commands come into the SQL Server the commands are basically the same. The driver on the client machine is what does the formatting.
The only way to protect the database engine from SQL Injection is to handle it at the application layer.
Edited: I stand corrected, I went back and read the TDS standard here:
http://www.sybase.com/content/1040983/Sybase-tds38-102306.pdf
The TDS_LANGUAGE command does support native parameters over the wire, so that is in fact how SQL Server receives parameterized queries.
As to whether there's a way to force use of parameters and not accept arguments in the CommandText, I don't know of a way to do so.

Resources