Writing queries in code behind vs. SqlDataSource - asp.net

I always have this notion that writing SQL queries in the code behind is not good compared to writing it using a SqlDataSource
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
myGridView.DataSource = ds;
myGridView.DataBind();
vs.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnection %>"
SelectCommand="SELECT * FROM Categories" />
I feel using SqlDataSource is secure, easy to maintain.
Is my concern true? Please justify.

I wouldn't write SQL queries in code behind full stop. How about a data access layer?
What happens if you want to change your backing store? You're going to have to re-write all your code-behind.
What happens where you need to use the data in more than one place? You duplicate code.
You need think seriously about how you're architecting your solution before writing SQL queries in your code behind. Think about separation and maintainability long before you question the 'security' of SqlDataSource objects. Seriously.

SQL queries in the code-behind and SQL queries in a SqlDataSource are pretty much equivalent.
they're both about the same security-wise; as for easier to maintain, SqlDataSource may be a bit easier in most cases.
A data-access layer is preferred, but SqlDataSource is sometimes a good-enough expediency. I wouldn't hit you with a rolled-up newspaper for using one if you didn't already have a data-access layer and it was for something simple/a one-off.

Neither of your methods are more or less secure than the other. Since your aspx pages are compiled just as your code behind pages are, you don't run the risk of accidentally exposing your SQL statements or database structure simply by using SqlDataSources. However, security isn't your main problem here -- it's maintainability.
Lots of people complained when Microsoft released SqlDataSources as part of .NET 2.0: we believe it encourages and reinforces bad habits.
For any type of project that's larger than a single intranet page, you should look into its well-behaved big brother, the ObjectDataSource. In using an ODS, you're almost constrained into developing a separate model for your data, away from your view.

In my experience, SQLDataSource is good for a quick one-off page to display data and perhaps edit it. But once you get into any kind of complicated scenario (and I always have), it breaks down pretty quickly. Maintainability is a nightmare using both SQLDataSource and straight SQL in the code behind. I've been burned by SQLDataSource many times.
I would at the very least write a Data Access Layer as a separate assembly that you can call into. This will give you a pluggable way to change it out if you need to. Even better would be a data access solution such as NHibernate or LinqToSql, which handles the plumbing for you and prevents you from having to write the whole thing yourself.

SQL in aspx or aspx.cs are both really novice, bad approaches. Look up n-tier / n-layer design, seperation of concerns and any book on software design.

DataSource controls are great for most things. They support paging in grids and serverside caching and may save trips to the database. However one downfall is that if you are doing anything complicated with db transactions, you wont be able to use a transaction across more than one sqldatasource, at least not easily.
because of pooling, two datasources could have different connections and there is no easy way to assign the transaction object before the commands execute.

I've used SQLDataSources to fill a grid, needing an uncomplicated query. Using a stored procedure instead of putting the query right in the SQLDataSource solves the reusability problem. The examples from Telerik controls make use of data sources extensively, but that may be due to the a need for simplicity and not real-world constraints. Another use I have encountered was on a page placed on every site at a client not particularly concerned with security that enabled the staff to execute sql on the fly. It contained a simple SQL query - opening the page was an easy way to check if the database was accessible.

Related

Security There is a Hyperlink in my GridView

There is a page in my company that contains only a GridView with some data
Today i saw this text in one of the cells (i changed a little to show to you)
[div style="display:none"]discount online BLABLABLA[a href="http://www.[randonURL].net/page/[randompage].aspx"]click[/a] new prescription coupon[/div]
I searched this text and somehow, someone inserted this in my database
How he made that?...what i can do about it?
It sounds like a classic case of SQL injection. There are a number of things you can do to prevent it. Here are a few. I would suggest reading up on it though.
On your database methods always use parameterized SQL, stored procedures or an ORM. Never use dynamic SQL. In the rare case you have to, there are ways of protecting that too. But that is a fairly long discussion.
Always encode user input. For JavaScript use the encodeURI() method. On the server side use the HtmlDecode() method.
Never show error details in the public domain. This gives hackers clues they can use.

ASP.NET MVC and Linq, when to use?

I just started working on an asp.net / C#.net application that is going to call a number of different procedures. The -only- thing these procedures do is create database table views, and the only thing I want to do is to store the information in variables. Then pick out which columns I want to convert to JSON, and then make a JSON string. I've actually written code for that in C#.net already, which is smaller, but since I switched to asp.net mvc I'm a little unsure if I should keep it or go with the whole Linq thing.
I checked out the Linq --> SQL drag & drop functionality, and that instantly created about 200 lines of code with set & get methods and everything.
So my question is, is it still worth using Linq even for just extracting data? Eventually this data will be fed to a javascript timeline, which is where I was told MVC would be highly useful with regards to Ajax functionality.
Since you are only using LINQ-to-SQL for data retrieval, I can't think of a single reason NOT to fully utilize it. I've been working on an MVC 1.0 project since last April. During that time, I've had to quickly become familiar with a number of technologies, LINQ-to-SQL being one of them. Get comfortable with it, and also look at the repository pattern...you will be very content and things will go relatively smoothly.
Now, when you get to INSERTs and UPDATEs, things are going to get a little more sticky. LINQ-to-SQL is still up to the job, but you'll need to understand how things work internally a little better. I highly recommend "Pro LINQ (Language Integrated Query) in C# 2008" by Joseph C. Rattz, Jr. The sections covering LINQ-to-SQL easily take up over a third of the book with detailed examples.
As far as the JSON objects go, LINQ-to-SQL's biggest contribution is that it allowed me not to have to worry about creating specialized views or stored procedures just to handle those one-off-types of data retrievals. My current project has a database of 65 tables...NO stored procedures. I can do filters, unions, multi-level joins...and it's all maintained in the application. Sweet...
Yes, it's totally worth it!
LINQ2SQL provides you a great subsurface to retrieve and save data to.
However, you'll need to implement your own Repository Pattern as you dig deeper into ASP.NET MVC.
And during the implementation of the Repository and the required (and even custom / webapp-state based) Queries, you'll be very glad to have all the power available at your fingertips that LINQ provides.
LINQ only adds to the available toolkit you can lean on when creating code. Even if you are using LINQ in a trivial way now, implement it, get familiar with it, and take advantage of the power it gives you both on this project and future projects.
Linq2Sql is quiet good for creating select queries. As it is appearing that you need to create JSON objects from database views it will be quiet useful

Suggestions on which ASP.NET control to use?

I've received a project for internal use. My application has to store about 100 rows of meta data of a game and each row has about 15 fields maximum. Fields can be game name, game category, maker, source code path, etc. I will most likely have to join about 5-10 tables for each row of record. Only a few people are using it and will receive very little hits. Speed performance is not a much of an issue. The rows of data I have to present must be sortable and searchable
My current solution is to use ASP.NET's GridView control with ASP.NET's AJAX UpdatePanel to give it that ajax feel. I'm thinking of using LINQ-to-SQL as my data access layer. I'm thinking of building my own custom search engine but if there's an existing control that has this feature already, i would prefer to use that; anyone know of such control exist? Anyways what do you guys think?
Update #1:
I'm looking into creating a DynamicData website. Any have thoughts on that?
Use ext.js!
Look at the Grid Samples, its a very shallow learning curve and provides you with amazing results in little to no time.
http://extjs.com/products/extjs/
Basically, you expose your data via a web service (asmx or WCF, your choice), throw the Ext.Js grid onto your html/aspx page and point it at your webservice. Configure the control for things like sorting/searching/expanding/grouping/paging etc (use the api reference http://extjs.com/deploy/dev/docs/).
ASP.NET Dynamic Data looks really cool, particularly for sites where you've got:
lots of data
not a lot of worries about performance
no / little desire to skin / design the site
no / little desire to extend existing / write new functionality.
So I'd say that's a good match for your project.
Gridview is your best bet. It's so powerful if you know how to use it correctly. It does automatic sorting and if you can code pretty well you can get the data to be filterable(if that's a word). It also makes the Connection to the database for you....so in my opinion, you can't beat the gridview when it comes to reports like that.

How to write a database class that supports parameterized queries

I'm a former classic ASP programmer and sometimes PHP programmer writing my first ASP.NET application. I'm loving the much-improved ADO.NET functions, but I'm feeling the need to write a database class. Partly I want to consolidate the code that actually interacts with the database, and partly I want to reduce what feels like repetition.
A simple database class is not hard to do, but I'm using parameterized queries as one of my security measures. I'm struggling with how to incorporate this into a class. I wrote a function to return the datatype of a column in the database by passing in the table and column name, but I can't think of a robust way to obtain the table and column name from the SQL query.
My design for the class was to have a Query() function for selecting, and an Execute() function for insert/update/delete. (Not opposed to having more public functions, but didn't want to get ahead of myself.) Both functions take a SQL string and a SortedList for the parameters. It might be possible to get the column name by finding the parameter name in the SQL string and looking in front of the equal sign. Likewise, it should be fairly simple to get the table name when the query is insert, update, or delete, because you only work with one table at a time. The big concern is selecting, because there could be one or more joins, inner selects, etc.
Am I headed in the wrong direction? Anything I'm not thinking of that could make my life easier or more difficult? Anybody written a class for this in any language that could offer some advice?
Don't reinvent the wheel. Look into nHibernate or LINQToSQL (or LINQToEntities) for your ORM needs.
Would second the call to find a tried and tested wheel that works for you, especially if this is your first foray into aspnet... there will be plenty else to keep you busy.
Would add a suggestion for SubSonic, which is perhaps a little lighter than nHibernate, but it really depends on the nature of your project, they are both great tools, and both have saved me months of work over the last few years.
I think since this is your first experience in ASP.NET you would be well advised to look into Linq to SQL. Do some tutorials so you get a feel for how it works before you try to code any Linq queries.
The only reasons I can think of to NOT use Linq to SQL in your case would be if you are not using SQL Server (or need to support other DBs either now or in future), or you cannot use .NET 3.5 runtime for some reason.
Good luck
It sounds to me like your "simple database class" is hiding too many details from the classes that need to use it.
I've written classes that contain a SqlCeEngine and expose methods like "LookupDescription(String Code)" ... I think that kind of design is something you should be looking into. And, consider looking into LINQ. It has a lot to offer.

asp.net gridview vs writing innerhtml

Are there any performance benefits to me not using the gridview in asp.net for simple tables querying from a stored procedure and instead writing the html in server code myself. I'm sure my code would certainly be more concise in output.
I am going to propose an alternate solution. If you don't need any of the features of a GridView, why not use a repeater.
A repeater keeps it simple for implementation, but also allows you to have full control over the generated source. Without the issue of string concatentation preformance.
I've found marginal performance improvements with repeaters over GridViews.
No, there are no performance benefits with using a GridView. In general, the GridView is going to decrease a little bit of performance due to the fact that items are written into the ViewState,and additional HTML is generated. The benefits you DO get from the GridView include command events and arguments that can be easily consumed or created, a DataKey "property bag" that allows you to track critical fields in a large result set, as well as many other things. I will add this caveat that I've used GridViews on even very simple result set returns and have not seen any significant performance problems.
If you are simply doing some output from a table query, and not worrying about doing too much interaction with the data from the results itself, "rolling your own" would provide a great solution.
Well, of course it depends on your implementation. You could almost certainly build something that runs faster than the stock gridview.
The problem is, how would you know? The default system for string concatenation in .Net is by it's nature very slow, so it would be easy to accidentally build something that is much slower than the stock gridview. You could of course test things out, but the development time investment is likely to outweigh an server performance gains.
There's an additional possibility here that exists between using a GridView and using a StringBuilder to generate HTML. I'm talking about using the ASP Table class. I have seen impressive speed benefits on using them over a standard GridView when all I'm doing is spitting out data. As an added bonus, I can add a button (or linkbutton) to my output and wire it up with an event handler and still get the functionality of a GridView in that regard.
You'd use it thus:
Dim tab As New Table
For Each row In DataTable.Rows
Dim tabRow as New TableRow
For Each col In row.Columns
dim tabCol as New TableColumn
tabCol .Text = row(col)
tabRow.Controls.Add(tabCol )
Next
tab.Rows.Add(tabRow)
Next
Page.Controls.Add(tab)

Resources