C# - Is It Safe Using Dynamic SQL With Parameters
Jan 12, 2011
For example, this is the code that I am using:
String commandString = "UPDATE Members SET UserName = @newName , AdminLevel = @userLevel WHERE UserID = @userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(commandString, conn);
cmd.Parameters.Add("@newName", newName);
cmd.Parameters.Add("@userLevel", userLevel);
cmd.Parameters.Add("@userid", userid);
conn.Open();
cmd.ExecuteReader();
Reader.Close();
}
View 3 Replies
Similar Messages:
Feb 1, 2010
I have been in the process of updating my code with security methods, and I've been learning this from [URL](or "Security Guidelines: ASP.NET 2.0"). In the middle of the page under "When Constructing SQL Queries, Use Type Safe SQL Parameters" it says "Use type safe parameters when constructing SQL queries to avoid possible SQL injection attacks that can occur with unfiltered input".
Now, what was to use code like:
"DataSet userDataset = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(LoginStoredProcedure", connection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);........"
But, I was already using code like:
"var dataSource = (SqlDataSource)form1.FindControl("sqlDataSource5") ;
dataSource.UpdateParameters.Add("someVal", val);"
So now, to use type safe parameters, I decided to include it like:
"var dataSource = (SqlDataSource)form1.FindControl("sqlDataSource5") ;
dataSource.UpdateParameters.Add("@someVal", DbType.Int16, val);
dataSource.UpdateParameters["@someVal"].Size = 1;"
So, that would be how I would modify my current code base to use type safe parameters in sql updating/inserting.
Getting to my actual question, as it was said "Use type safe parameters when constructing SQL queries to avoid possible SQL injection attacks that can occur with unfiltered input". First off, that this should apply to unfiltered input. Also, in their example they only did this for an ID.
So, what I'd like to know, when it comes to "unfiltered input", does this mean as long as the input is unfiltered I must use type safe parameters, or even filtered input shall have this (just to be sure), like, input that has been ran through a regularexpression check? Shall I do this for all values I insert/update into the database, or just IDs and important things?
The way I see it right now is that it would be a good precaution to just do type safe checks on everything (literally) that updates/inserts into the database just to be extra safe. But, I really am unsure if this is really the best idea, because if I did, would this possibly cause overprocessing of information? Can this cause too much strain on server resources?
View 1 Replies
Mar 15, 2011
I been reading a bit about SQL injection and I want to be sure my code is lets say "safe" from it, I was planning on using RegExp validators to check the user input but another post in here suggested only using parametrized querys, well Im using them but I want to be sure my code is safe, is it?
[code]....
View 3 Replies
Feb 1, 2010
I have been in the process of updating my code with security methods, and I've been learning this from [URL] (or "Security Guidelines: ASP.NET 2.0"). In the middle of the page under "When Constructing SQL Queries, Use Type Safe SQL Parameters" it says "Use type safe parameters when constructing SQL queries to avoid possible SQL injection attacks that can occur with unfiltered input". Now, what they suggested was to use code like:
"DataSet userDataset = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(LoginStoredProcedure", connection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);........"
But, I was already using code like:
"var dataSource = (SqlDataSource)form1.FindControl("sqlDataSource5") ;
dataSource.UpdateParameters.Add("someVal", val);"
So now, to use type safe parameters, I decided to include it like:
"var dataSource = (SqlDataSource)form1.FindControl("sqlDataSource5") ;
dataSource.UpdateParameters.Add("@someVal", DbType.Int16, val);
dataSource.UpdateParameters["@someVal"].Size = 1;"
So, that would be how I would modify my current code base to use type safe parameters in sql updating/inserting.
Getting to my actual question, as it was said "Use type safe parameters when constructing SQL queries to avoid possible SQL injection attacks that can occur with unfiltered input". First off, this suggests that this should apply to unfiltered input. Also, in their example they only did this for an ID.
So, what I'd like to know, when it comes to "unfiltered input", does this mean as long as the input is unfiltered I must use type safe parameters, or even filtered input shall have this (just to be sure), like, input that has been ran through a regularexpression check? Shall I do this for all values I insert/update into the database, or just IDs and important things?
The way I see it right now is that it would be a good precaution to just do type safe checks on everything (literally) that updates/inserts into the database just to be extra safe. But, I really am unsure if this is really the best idea, because if I did, would this possibly cause overprocessing of information? Can this cause too much strain on server resources? If my fears serve true, what would be a good suggestion of how I could implement this properly without having to worry about what I said?
View 1 Replies
May 12, 2010
I am using jquery ajax method on my aspx page,which will invoke the webmethod in the code behind.Currently the webmethod takes a couple of parameters like firstname,lastname,address etc which I am passing from jquery ajax method using
data:JSON.stringify({fname:firstname,lname:lastname,city:city})
now my requirement has been changed such that,the number and type of parameters that are going to be passed is not fixed for ex.parameter combination can be something like fname,city or fname,city or city,lname or fname,lname,city or something else.So the webmethod should be such that it should accept any number parameters.I thought of using arrays to do so, as described here.
But I do not understand how can I identify which and how many parameters have been passedto the webmethod to insert/update the data to the DB.
View 4 Replies
Jan 19, 2011
I need to update a table with values from a listbox. I am trying to create as many parameters as there are items in the list, my code below, but how do i name them differently? so that they dont' overwrite each other?
For Each item As ListItem In ris
Dim pID As New SqlParameter("@userid", SqlDbType.Int)
pID.Value = objFormat.CheckSQL(item.Value)
myCommand.Parameters.Add(pID)
Next
and on the SQL side, is it possible to write an update statement, that will take a dynamic number of parameters?
so for example, i need to update multiple users with the same value in the "active" field...
View 3 Replies
Mar 24, 2011
Using routing in web forms in ASP.NET 4.0. Looking to use dynamic parameters in the RoutingExpressionBuilder class something like:
NavigateUrl="<%$ RouteUrl:searchterm={dynamicParameterFromObject} %>">
Would like to know the proper syntax is available.
View 1 Replies
Mar 6, 2013
I have a dynamic created drop down list - and I set the event of it to be like this:
ddlAnswer.ID = "ddlistAnswer" + QuestionID;
ddlAnswer.SelectedIndexChanged += new EventHandler(ddlAnswer_SelectedIndexChanged);
Please note that drop down list is dynamic, and in selectedIndexChanged, I would like to pass the "QuestionID" to that selectedindexchanged to work on my logic. Is there a way to pass it to that method as command argument or something?
Code:
protected void ddlAnswer_SelectedIndexChanged(object sender, EventArgs e)
{
//wanting that question id here
}
View 1 Replies
Jul 22, 2010
In my "selecting" statement I need to add two dynamic parameters when using the LinqDataSource's WhereParameters collection:
e.WhereParameters.Add(param, True)
However, the system adds these parameters as AND, but I want to perform an OR where either parameter 1 OR parameter 2 is true.
View 2 Replies
Sep 28, 2010
I know parameters to attribute declarations have to be a constant expression and resolved at compile time. However, can I play with the concept of 'compile time'? ASP.net has the concept of App_Code folder. It looks from it's description like you can drop .cs files into it, even while the app is running, and it will be brought in and compiled. Is it possible to use this mechanism to dynamically create an Enum or const array that can be used in an attribute declaration?
[SomeAttribute(ValidTypes.SomeType)]
public class Foo
{
}
Basically, I want to dynamically grow the valid types in ValidTypes without having to recompile all components that reference it. And I need to keep it in sync with a list of values in a database table. So, my question is, can I drop a .cs file with the definition for an Enum or const string array into App_Code and have it automagically show up? Or better yet, is the mechanism .Net uses to do this available to be called elsewhere so I don't have to do it in an ASP.Net app?
View 1 Replies
May 20, 2010
I've a requirement that I need to read an excel sheet programmatically using asp.net/C# and write the data obtained into a mysql table.The excel sheet contains something around 50 columns and 2000 records.I am able to read the data from the excel sheet and store it in a dataset.I am using the following code to write the data into mysql table.
for (int i = 1; i <= myDataSet1.Tables[0].Rows.Count - 1; i++)
{
MySqlCommand cmd = new MySqlCommand();
for (int j = 0; j <= myDataSet1.Tables[0].Columns.Count - 1; j++)
{
paramset[j] = myDataSet1.Tables[0].Rows[i][j].ToString();
cmd.Parameters.AddWithValue("val" + j, paramset[j]);
}
cmd.CommandText = "Insert into faqimport
cmd.Connection=con;
cmd.CommandType = CommandType.Text;
int x=cmd.ExecuteNonQuery;
}
When I try to run the above code I am getting 'Unknown column 'val0' in 'field list'' error.I understand that i am manually creating the parameters val0,val1,val2.....instead I am creating them dynamically using the integer 'j'.But I do not want to create around 50 parameters to insert data into the database table.
Also is there a way i can get the column datatypes from the excel sheet in order to create a new table in mysql with the columns in the excel sheet?
View 1 Replies
Feb 14, 2011
I want to create a function which would have two parameters
public **XYZ** GetOputput(string strToConvert, **ABC**)
What I want from this function, that I will send a string to this function and the datatype in which I want to convert this string [Ex: Int32,Int64, datetime etc..] and the return will be the same as the datatype I have sent as the input parameter.
I want to have something like this in my function:
[code]....
View 5 Replies
May 28, 2010
I'm new to web dev and c# so please bare with me. I am trying to create a dynamic gridview in a web form for users to to answer questions with (code below).
The dificulty im having is that i am nesting a dropdwonlist in the gridview and want to be able to dynamically set the list values based on parameters (of the row they are on). These values are in the main dataset for the gridview as each row represents a questionid and question text and then a ddl for the criteria...
I just don't know how to set the values for the dropdown all the code so far is below... just need to be able to populate the dropdowns with the relevant values.
I have created a stored proc to return the different criteria based on the questionid and questionGroupid which is the dataset that populates the other fields in the gridview: dbo.usp_QuestionCriteria @QuestionGroupId, @QuestionId
I have added this as a tableadapter called criteriaTableAdapter in a xsd file as well using the wizard... not sure if this is the right option though or just use the same method as i have for the other stored procedure as in the code below:
[CODE
]using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
con.Open();
SqlCommand com = new SqlCommand("usp_QuestionGroupDS", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ada = new SqlDataAdapter(com);
DataSet ds = new DataSet();
ada.Fill(ds);
for (int i = 0; i < ds.Tables.Count; i++)
{
if (ds.Tables[i].Rows.Count > 0)
{
GridView gvDynamicQuestion = new GridView();
gvDynamicQuestion.Width = Unit.Pixel(700);
gvDynamicQuestion.BorderWidth = Unit.Pixel(0);
gvDynamicQuestion.Caption = "<div id="nifty" class="QuestionGroup"> <b class="rtop"><b class="r1"></b><b class="r2"></b><b class="r3"></b><b class="r4"></b></b>" + ds.Tables[i].Rows[0]["Category"].ToString() + " Questions<b class="rbottom"><b
class="r4"></b><b class="r3"></b><b class="r2"></b><b class="r1"></b></b></div>";
gvDynamicQuestion.AutoGenerateColumns = false;
gvDynamicQuestion.ShowFooter = true;
TemplateField tf = null;
tf = new TemplateField();
tf.HeaderTemplate = new DynamicGridViewTextTemplate("QuestionId", DataControlRowType.Header);
tf.ItemTemplate = new DynamicGridViewTextTemplate("QuestionId", DataControlRowType.DataRow);
tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);
gvDynamicQuestion.Columns.Add(tf);
tf = new TemplateField();
tf.HeaderTemplate = new DynamicGridViewTextTemplate("Question", DataControlRowType.Header);
tf.ItemTemplate = new DynamicGridViewTextTemplate("Question", DataControlRowType.DataRow);
gvDynamicQuestion.Columns.Add(tf);
tf = new TemplateField();
tf.HeaderText = "Criteria";
tf.HeaderTemplate = new DynamicGridViewTextTemplate("Criteria", DataControlRowType.Header);
tf.ItemTemplate = new DynamicGridViewDDLTemplate();
gvDynamicQuestion.Columns.Add(tf);
////tf = new TemplateField();
////tf.HeaderText = "Criteria";
////tf.ItemTemplate = new DynamicGridViewDDLTemplate();
////gvDynamicQuestion.Columns.Add(tf);
gvDynamicQuestion.DataSource = ds.Tables[i];
gvDynamicQuestion.DataBind();
phDynamicGridHolder.Controls.Add(gvDynamicQuestion);
}
}
}
protected void DynamicGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
//
}
}
}
public class DynamicGridViewTextTemplate : ITemplate
{
string _ColName;
DataControlRowType _rowType;
int _Count;
public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
{
_ColName = ColName;
_rowType = RowType;
}
public DynamicGridViewTextTemplate(DataControlRowType RowType, int QuestionCount)
{
_rowType = RowType;
_Count = QuestionCount;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = "<b>" + _ColName + "</b>";
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.lbl_DataBind);
container.Controls.Add(lbl);
break;
case DataControlRowType.Footer:
Literal flc = new Literal();
flc.Text = "<b>Total No of Questions:" + _Count + "</b>";
container.Controls.Add(flc);
break;
default:
break;
}
}
private void lbl_DataBind(Object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridViewRow row = (GridViewRow)lbl.NamingContainer;
lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();
}
}
public class DynamicGridViewDDLTemplate : ITemplate
{
// Implementation of ITemplate
public void InstantiateIn(System.Web.UI.Control container)
{
// Create a DDL
DropDownList ddl = new DropDownList();
//Attach method to delegate
ddl.DataBinding += new System.EventHandler(this.ddl_DataBind);
container.Controls.Add(ddl);
}
//Method that responds to the DataBinding event
private void ddl_DataBind(object sender, System.EventArgs e)
{
//DropDownList ddl = (DropDownList)sender;
//DataGridItem container = (DataGridItem)ddl.NamingContainer;
//ddl.Data.Checked = [Data binding expression];
}
}
[/CODE]
View 7 Replies
Sep 21, 2010
There is not a clear category on the site where to post this, so giving it a shot here.
Has anyone used VS 2008? I current user Turtoise for some projects, and Source Gear Valut for others.
The company where I work is thinking about moving to VSS because of the MSDN subscription.
My experience with VSS prior to VSS 2005 was that it conied the name "Visual Source Unsafe" and I know first hand that it trashed my work more that once and I stopped using it. Source Gear Valut on the other hand is rock solid.
So is VSS 2008 Really "safe" was VSS 2005 "safe" ?
View 3 Replies
Aug 22, 2010
1. I have a GridView on my page and it uses sqldatasource with parameterized query. What I want to do is, on page load (where nothing has been selected so no parameter supplied), I want it to query everything (something like SELECT * FROM [this_table]) but since my SelectCommand is something like
SELECT * FROM [this_table] WHERE [this_column] = @someParameters AND [that_column] = @someParameters.
Can I play around with default value to achieve something like that but how ? Now, when the page loads, it doesn't show anything (No Gridview).
2. On my page, I made something like (username, gender, address, and more) and one single search button. That means, no single control enable auto postback. What I am trying to accomplish is building dynamic query
(if username specifed -> SELECT * FROM [this_table] WHERE [username] LIKE @username).
If both username and gender are specified (SELECT * FROM [this_table] WHERE [username] LIKE @username AND [gender] = @gender) and you know the rest. How can I do this using GridView and SqlDataSource ? To my knowledge, I can only specify one SELECT statement in a sqldatasource.
View 11 Replies
Feb 28, 2011
I wonder if its safe to use the CTP5 in production yet. My main use would be for 2 small projects. I Know they pre released it but any thoughts on this if it would hold up for production are welcome.
View 1 Replies
Nov 12, 2010
I've a blog-driven ASP.NET website. Under the post, there is a Comment block to let readers post comments.I've used some TextBoxes and TextArea for that.To Prevent XSS:I've filtered the input by using: Server.HtmlEncode() Method (I don't care about text formatting).To Prevent SQL-Injection:I'm using Linq To SQL (that should be like parametrized queries I think!).
ArticlesDataClasses dc = new ArticlesDataClasses();
ArticleComment newComm = new ArticleComment()
{
ArticleID = int.Parse(Request.QueryString["ArticleID"]),
CommentAuthor = Server.HtmlEncode(txtName.Text),
CommentText = Server.HtmlEncode(txtComment.InnerHtml).Replace("
", "<br />"),
CommentAuthorEmail = Server.HtmlEncode(txtMail.Text),
CommentTime = DateTime.Now,
Enabled = false
};
View 1 Replies
Apr 23, 2010
When storing a value in a cookie using C#, what is the best way to encode (or escape) the value so that it can be retrieved and decoded/unescaped reliably?
I'm not talking about encryption.
View 1 Replies
Feb 21, 2011
I want to store certain html tags in my database to the layout of content, for example <h3> and <p> tags. The problem is with ValidateInput set to True, you get "Potential Danger error" when you try sending content with html tags.
With it set to False, you open yourself to all sorts of potential dangers. So Here is what I'm wanting to achieve:
I hope you like the image ! lol I spent 10 minutes in Photoshop to create it.
So eventhing that goes in, I want as encoded, but when I get content back, I want to decode only the <h3> and <p> tags. ! What do you think of my solution ? Bad, Good ?
View 16 Replies
Oct 21, 2010
I'm trying to make an existing ASP.NET web forms app more unit testable by using some of the ASP.NET MVC objects, specifically HttpContextWrapper. I've seen examples of its usage and they always create a new object. I disassembled the source with Reflector and see all it does is store the passed HttpContext. But I was curious as to whether or not it's safe to always create a new instance of HttpContextWrapper or follow the singleton pattern somehow? Below is the class I'm using in my app
public static class AppHttpContext {
public static HttpContextBase Current { get { return Getter(); } }
public static void SetContext(Func<HttpContextBase> getter) {
Getter = getter;
}
private static Func<HttpContextBase> Getter = () => new HttpContextWrapper(HttpContext.Current);
}
And I use it similar to HttpContext.Current
AppHttpContext.Current.Session["blah"] = "something";
View 1 Replies
Feb 10, 2011
I'm considering making use of an HttpModule for localization purposes (based on the example in this article) - but I'm curious, is this safe?
Here's the code, for reference:
public class CookieLocalizationModule : IHttpModule
{
public void Dispose()
{
}
[code]....
I was under the impression that multiple threads could potentially service a web request. Is it safe to set the Current/Current UI Cultures in an HttpModule like this and have it respected for the life of the web request regardless of how many threads are involved in servicing it?
View 1 Replies
Jan 23, 2011
Is there any way to make asp.net objectdatasources to be type safe. Meaning I get a compile time error if parameters or datatypes change during refactoring?Does anyone know any other method? Or can recommend any other way to do it? I find manual binding tedious. What is other people doing?
View 1 Replies
Feb 16, 2011
[Code]....
When I want to get the output values its okay but I also want returning a table as a result data.But Datareader has no rows.is it possible if I want a returning query result and multiple output values togather ?I wrote a test above.I can get output values as sqlparameters. But Datareader attached to a Gridview is empty.can you detect whats wrong here and it doesnt return a query result.So stored procedure is not standart or ı am doing something wrong.this doesnt raise any exception.but not returning any data.
[code]....
View 8 Replies
Jun 7, 2010
I want to define a route that have 2 optional parameters in the middle of the URL the start an end parameters are digits
[Code].....
View 1 Replies
Mar 30, 2011
I am toying with the idea of enabling CLR on my SQL server, using EXEC sp_configure 'clr enabled', 1
However, I am sharing my database server with several other developers and their projects. I've heard vaguely that their might be security issues with enabling this.
Does anyone know what these issues might be? Is CLR safe to use on SQL Server?
View 1 Replies