stateless API DB connection pattern - c#

I am writing a (C#) stateless Rest api that returns data from a MS SQL server. It replaces a curently existing JAVA API that uses a lot of hardcoded queries to access the data.
Inside the api I'm building I'll need to have the controllers be able to target multiple databases. There is no session management not are there any authentication issues
What is a good approach for handling data access?
one option is to create all the connection objects for each request. I worry that this would cause quite some overhead. Another option is to use a singleton for each database connection.
Any advice on this matter is welcome

Related

best practise for connecting to a database server in c#

I have been doing much research into this and was wondering what the best approach is, imagine the scenario where you have a WPF application that is being distributed to many users, this application has to connect to a database server. Connecting to a database is not a problem its how secure the connection is as external users will have access to the application.
within the app.config file connection strings can be pointed to the server, however releasing the password and server IP address is not a good idea. from research, other people recommended encrypting the data, but sure this is still got a degree of vulnerability.
the next approach is to use WCF, this i have limited knowledge on and not sure if this approach is correct.
Am I safe in encrypting the connection strings or is there more to it than that, I just want to be extra careful when dealing with sensitive data.
A common way is to add a server layer between your wpf app and the database. It can be a REST api or other web services as you like. In terms of technologies you can choose, wcf is one. But wcf is not easy to get started with if you do not have experience of dealing with services. I suggest to try Asp.Net's Web Api project to quickly establish a Rest Service (http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-1 ).
This server layer will protect your database information (connection string etc). Also, allowing your application directly querying the database will potentially prevent the database from evolving -- for example, the insert query may break on the client side when you add a constraint on a table. Having a server in between can solve this future headache as you can update the server side implementation and database simultaneously.
In case of data sensitive, I would like to prefer SOA architecture will most suitable to you. WCF will be good option but think about RestFulWCF or WebApi2.0 (popular for multi platform support).
Hope this will help :)

using C# GUI app to query a MySQL database with an online provider

Hosting services commonly provide support for webapps (say ASP.net, Rails or Django) and a few databases (e.g. SQLServer, MySQL).
I prefer C# WinForms for most of my own apps (speed of graphics updates eg.), but I'd like to have a webbased DB behind it so I can access it from multiple locations.
Is there a reason that I couldn't use such a web-provider just for my databases, i.e. not serve a dynamic webpage but just answer my sql queries?
Existing posts that appear to answer similar questions exist, but I would like to obtain more clarity.
E.g. does the webserver provide additional security that is otherwise hard to obtain?
Does the 'correct' answer include the keyword WCF? Do I need the hosting service to support WCF explicitly?
There is no technical limitation in accomplishing what you are asking, but most of the hosting providers (shared hosting mainly) restrict access to their database to be within their internal network. If you can find a hosting provider who provides you the option to connect from external network you are good to go.
One thing you want to keep in mind when you are distributing your winforms client is that the connection string can be extracted by the end user if he is a smart enough person. It would be prudent to encrypt the connection string in the configuration file and also use encryption for the connection it is making to the database (SslMode=Required in the connection string).
When you are using WCF, it helps you to implement an additional layer of abstraction and protection. You can use your own membership to authenticate the user who can have access to the WCF services and not worry about connecting from the client to the database directly.
All being considered, going with a WCF or any other web service layer instead of directly connecting to the database from the client would be better approach.

WCF - solution architecture

I am working on a project in which a WCF service will be consumed by iOS apps. The number of hits expected on the webserver at any given point in time is around 900-1000. Every request may take 1-2 seconds to complete. The same number of requests are expected on every second 24/7.
This is what my plan:
Write WCF RESTful service (the instance context mode will be percall).
Request/Response will be in Json.
There are some information that needs to be persisted in the server - this information is actually received from another remote system - which is shared among all the requests. Since using a database may not be a good idea (response time is very important - 2 seconds is the max the customer can wait), would it be good to keep it in server memory (say a static Dictionary - assume this dictionary will be a collection of 150000 objects - each object consists of 5-7 string types and their keys). I know, this is volatile!
Each request will spawn a new thread (by using Threading.Timers) to do some cleanup - this thread will do some database read/write as well.
Now, if there is a load balancer introduced sometime later, the in-memory stored objects cannot be shared between requests routed through another node - any ideas?
I hope you gurus could help me by throwing your comments/suggestions on the entire architecture, WCF throttling, object state persistence etc. Please provide some pointers on the required Hardware as well. We plan to use Windows 2008 Enterprise Edition server, IIS and SQL Server 2008 Std edition database.
Adding more t #3:
As I said, we get some information to the service from a remote system. On the web server where the the WCF is hosted, a client of the remote system will be installed and WCF references one of this client dlls to get the information, in the form of a hashtable(that method returns a hashtable - around 150000 objects will be there in this collection). Would you suggest writing this information to the database, and the iOS requests (on every second) which reach the service retrieves this information from the database directly? Would it perform better than consuming directly from this hashtable if this is made static?
Since you are using Windows Server 2008 I would definitely use the Windows Server App Fabric Cache to store your state:
http://msdn.microsoft.com/en-us/library/ff383813.aspx
It is free to use, well supported and integrated and is (more or less) API compatible with the Windows Azure App Fabric Cache if you every shift your service to Azure. In our company (disclaimer: not my team) we used to use MemCache but changed to the App Fabirc Cache and don't regret it.
Let me throw some comments/suggestions based on my experience in serving a similar amount or request under the WCF framework, 3.5 back in the days.
I don't agree to #3. Using a database here is the right thing to do. To address response time, implement caching and possibly cache dependency in order to keep the data synchronized across all instances (assuming that you are load balanced)(also see App Fabric suggested above/below). In real world scenarios, data changes, often, and you must minimize the impact.
We used Barracuda hardware and software to handle scalability as far as I can tell.
Consider indexing keys/values with Lucene if applicable. Lucene delivers extremely good performances when it comes to read/write. Do not use it to store your entire data, read on it. A life saver if used correctly. Note that it could be complicated to implement on a load balanced environment.
Basically, caching might be the only necessary change to your architecture.

What is suggested way of working with remote DB in WPF application

I have a task to create a desktop version of our web app that will be distributed to our customers. I decided to go with wpf. The web app is three tier app with dal, bbl and pl. I could reuse a lot of it in my wpf but question is: is it a good idea to allow remote connections directly to sql server (i could compile connection string directly into the app). Or should i go wcf way and access db through a web service (this will require wrapping business metods around with service methods. Additional coding...)?
Any input is highly appreciated.
I would HIGHLY suggest using a WCF service. That way you are in control of what is running queries against your database, and it helps with keeping code updated. A great example why remote connections are bad :
Remote Access World
You use a stored procedure GetAnObject
In the process of upgrading your software, you change GetAnObject to return something different
Now all old versions are broken =(
WCF World
You use a stored procedure GetAnObject
In the process of upgrading, you change what it returns
In your WCF you just have to write some code to convert your object into the old one and send to legacy client. New clients are using a different WCF method call.
Also, I personally am not a fan of opening up my SQL server to any joe blow on a pc who can guess the login.
If you publish a version with an error in it, you at least have a chance the error is in the WCF side and therefore don't have to hassle clients with a 'my bad' upgrade. They never have to know where was a problem.
In a perfect world your WCF service and Web app can share a codebase, so you have less to maintain.
My suggestion is to go via a service (WCF or any other). The extra layer of indirection is decoupling which helps a great deal in maintenance and scalability. For example, if you already had a service which your web application used, it would have been much easier for you to just focus on creating WPF UI.
It all depends on what you want. Are you planning to use the DB layer and business layer across applications? If your answer is yes maybe WCF is the way to go.
We have a bunch of apps where we connect to the DB from WPF app directly because we wanted to avoid the extra layer of indirection which WCF adds.

Dynamic choose connection entity framework rest

I have a very simple entity framework (.edmx) file, and a .svc rest service.
Everything works fine for CRUD operations.
I have many databases thats shares the exactly same schema.
My next step is to let the client pass inn a parameter that could be the connection string or some other value identifying the user so that the service serves data from the correct database.
Now, the only parameter is the uri for the ServiceRoot
I see in the datamodel that I can pass inn a connection string, but how can i do this from the client without making many service files.
I am assuming you are using WCF Data Services to expose the edmx file. I am no expert in this toolset but I suspect the only direct way is to create a service for each database.
This is a great question and it is a scenario that I hope will be addressed in the future WCF HTTP stack.
In the meanwhile, there is some positive news. I have experimented in the past with creating a large number of service hosts (around 1000) and my experimentation showed that it was quite efficient to start up and did not consume large amounts of RAM. The key is to create the service hosts in code rather than via the config files. Obviously, you don't want to be hand writing an XML config file with thousands of service entries in it!
It may not be the ideal solution but I believe it would work.
If you're using WCF Data Services you should be able to pass the information identifying the data source to use in the HTTP request. Either as a custom option in the URL or as a custom HTTP header (I would probably use the custom header as it's much easier to work with from the client).
Depending on the way you host the service you should be able to access the headers of the request on the server. You can use the ASP.NET way to do this (static variables), or you can hook into the processing pipeline of the WCF Data Services which should allow you to access those headers as well.

Categories