Get data from a Dataset by parameter in WHERE clause - asp.net

I'm following a tutorial where they explain how to add a Dataset to your ASP.NET web application and how to add a parameter to a SQL query. But it's not really working for me the way they are doing it in the tutorial.
I've added a Dataset to my App_Code folder. In the dataset i made a connection to a database in SQL Server. Now i can get data from my database by giving the dataset a SQL query. In the tutorial they do something like this:
SELECT TOP 20 [ProductID]
,[Name]
,[ProductNumber]
,[MakeFlag]
,[FinishedGoodsFlag]
,[Color]
,[SafetyStockLevel]
FROM [Production].[Product]
WHERE (Color = :Color)
The point in this example is the :Color part. That is how they let it know where to add the parameter. But when i use this query in my Dataset it gives me a warning:
Error in WHERE clause near ':'. Unable to parse query text.
After that he is able to actually add a parameter to the Dataset through the Properties window and test preview his data. That doesn't work for me since it already starts to complain when i add my query.
What can i do to solve this problem?

Parameters in Sql-Server have a # in front:
WHERE (Color = #Color)
Configuring Parameters and Parameter Data Types

Related

Error with SQLite query, What am I missing?

I've been attempting to increase my knowledge and trying out some challenges. I've been going at this for a solid two weeks now finished most of the challenge but this one part remains. The error is shown below, what am i not understanding?
Error in sqlite query: update users set last_browser= 'mozilla' + select sql from sqlite_master'', last_time= '13-04-2019' where id = '14'
edited for clarity:
I'm trying a CTF challenge and I'm completely new to this kind of thing so I'm learning as I go. There is a login page with test credentials we can use for obtaining many of the flags. I have obtained most of the flags and this is the last one that remains.
After I login on the webapp with the provided test credentials, the following messages appear: this link
The question for the flag is "What value is hidden in the database table secret?"
So from the previous image, I have attempted to use sql injection to obtain value. This is done by using burp suite and attempting to inject through the user-agent.
I have gone through trying to use many variants of the injection attempt shown above. Im struggling to find out where I am going wrong, especially since the second single-quote is added automatically in the query. I've gone through the sqlite documentation and examples of sql injection, but I cannot sem to understand what I am doing wrong or how to get that to work.
A subquery such as select sql from sqlite_master should be enclosed in brackets.
So you'd want
update user set last_browser= 'mozilla' + (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
Although I don't think that will achieve what you want, which isn't clear. A simple test results in :-
You may want a concatenation of the strings, so instead of + use ||. e.g.
update user set last_browser= 'mozilla' || (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
In which case you'd get something like :-
Thanks for everyone's input, I've worked this out.
The sql query was set up like this:
update users set last_browser= '$user-agent', last_time= '$current_date' where id = '$id_of_user'
edited user-agent with burp suite to be:
Mozilla', last_browser=(select sql from sqlite_master where type='table' limit 0,1), last_time='13-04-2019
Iterated with that found all tables and columns and flags. Rather time consuming but could not find a way to optimise.

Using "Count" in PreparedStatement ... gives same result [duplicate]

I already used the search here (and other forums as well) but haven't found an answer exacty to what I'm trying to do.
I know that it can easily be done in some other way, and this is just a small sandbox-framework I'm coding for a University course... in a real environment I'd just take Spring, Hibernate etc.
So what I did was coding myself a small generic Data Access Layer with POJOs, working with generic methods to retrieve, check or insert data to the database (Oracle). Most of this is done through PreparedStatements.
This is working as long as I don't have joins... is it possible to put in a Column as parameter?
Example:
Table A has Attribute X + others
Table B has Attribute Y + others
PreparedStatement with query SELECT * FROM A,B WHERE "A"."X" = ?
And then fill in "B"."Y" as the parameter...
The database doesn't throw me an error or exception, but the ResultSet returned after executing the statement is empty. Is it just not possible to do, or am I just missing some escaping?
I'm using PreparedStatement.setString(int index, String value) to fill in the parameter... in lack of ideas which other setX method I could use...
Again, in a real project I'd never code that myself, but rather use something like Spring or Hibernate and not re-invent the wheel, but I see it as an interesting exercise to code such a generic small data access layer myself.
No, JDBC does not allow this. Only column values can be set. If you want to make dynamic changes to the sql statement you will have to do it before you create the PreparedStatement.

ASP.NET Website display wrong data

I built a web application using ASP.NET, data stored at SQL Server 2008.
The application is running ok, but once a couple of day the application displays wrong data and i get error when i enter some pages. system return to normal work after 5 minutes by it self.
can someone give a clue what is the problem?
I'm getting error on lines which try to take data from retrieved DataTable:
like:
txtbx_contact_fullname.Text = dt_contact.Rows[0]["Contact_Fullname"].ToString();
or
lbl_Creation_datetime.Text = dt_YC_Last_Transaction.Rows[0]["Creation_datetime"].ToString();
usually these lines works perfect, and there is no reason that the datatable will return empty.
the error i get is:
Column 'xxxxx' does not belong to table.
The Query that retrieve the data is:
SELECT [Request ID],[Creation Date],[Request Status],[Contact Fullname],[Start Date],[Start Time],[End Date],[End Time],[Work Mode],[Comments],[HPM Points],[FA Points]
FROM dbo.vw_All_Requests
WHERE [Request Status] = #YellowCard_Status
ORDER BY [Creation Date] DESC
From some reason some columns do not get back..
txtbx_contact_fullname.Text = dt_contact.Rows[0]["Contact Fullname"].ToString();
lbl_Creation_datetime.Text = dt_YC_Last_Transaction.Rows[0]["Creation datetime"].ToString();
you column name in asp.net code has _ for example full_name but in sql query it does not have _, i don't know you've assigned names to your datatable or not but give attention to this issue ...
if you code is correct. you are calling Creation_datetime from .NET code, but in SQL you have no such column, what you do have is a Creation date only (from your SELECT query).
so, to fix your problem, all you need to do is change
dt_YC_Last_Transaction.Rows[0]["Creation_datetime"]
to
dt_YC_Last_Transaction.Rows[0]["Creation_date"]
after the issue is fixed, you should learn a better way to query the database using explicit names, for example, using objects instead calling the string value... You should learn a bit of Entity Framework and Linq, it will improve your code a lot.

MS Access CREATE PROCEDURE Or use Access Macro in .NET

I need to be able to run a query such as
SELECT * FROM atable WHERE MyFunc(afield) = "some text"
I've written MyFunc in a VB module but the query results in "Undefined function 'MyFunc' in expression." when executed from .NET
From what I've read so far, functions in Access VB modules aren't available in .NET due to security concerns. There isn't much information on the subject but this avenue seems like a daed end.
The other possibility is through the CREATE PROCEDURE statement which also has precious little documentation: http://msdn.microsoft.com/en-us/library/bb177892%28v=office.12%29.aspx
The following code does work and creates a query in Access:
CREATE PROCEDURE test AS SELECT * FROM atable
However I need more than just a simple select statement - I need several lines of VB code.
While experimenting with the CREATE PROCEDURE statement, I executed the following code:
CREATE PROCEDURE test AS
Which produced the error "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."
This seems to indicate that there's a SQL 'PROCEDURE' statement, so then I tried
CREATE PROCEDURE TEST AS PROCEDURE
Which resulted in "Syntax error in PROCEDURE clause."
I can't find any information on the SQL 'PROCEDURE' statement - maybe I'm just reading the error message incorrectly and there's no such beast. I've spent some time experimenting with the statement but I can't get any further.
In response to the suggestions to add a field to store the value, I'll expand on my requirements:
I have two scenarios where I need this functionality.
In the first scenario, I needed to enable the user to search on the soundex of a field and since there's no soundex SQL function in Access I added a field to store the soundex value for every field in every table where the user wants to be able to search for a record that "soundes like" an entered value. I update the soundex value whenever the parent field value changes. It's a fair bit of overhead but I considered it necessary in this instance.
For the second scenario, I want to normalize the spacing of a space-concatenation of field values and optionally strip out user-defined characters. I can come very close to acheiving the desired value with a combination of TRIM and REPLACE functions. The value would only differ if three or more spaces appeared between words in the value of one of the fields (an unlikely scenario). It's hard to justify the overhead of an extra field on every field in every table where this functionality is needed. Unless I get specific feedback from users about the issue of extra spaces, I'll stick with the TRIM & REPLACE value.
My application is database agnostic (or just not very religious... I support 7). I wrote a UDF for each of the other 6 databases that does the space normalization and character stripping much more efficiently than the built-in database functions. It really annoys me that I can write the UDF in Access as a VB macro and use that macro within Access but I can't use it from .NET.
I do need to be able to index on the value, so pulling the entire column(s) into .NET and then performing my calculation won't work.
I think you are running into the ceiling of what Access can do (and trying to go beyond). Access really doesn't have the power to do really complex TSQL statements like you are attempting. However, there are a couple ways to accomplish what you are looking for.
First, if the results of MyFunc don't change often, you could create a function in a module that loops through each record in atable and runs your MyFunc against it. You could either store that data in the table itself (in a new column) or you could build an in-memory dataset that you use for whatever purposes you want.
The second way of doing this is to do the manipulation in .NET since it seems you have the ability to do so. Do the SELECT statement and pull out the data you want from Access (without trying to run MyFunc against it). Then run whatever logic you want against the data and either use it from there or put it back into the Access database.
Why don't you want to create an additional field in your atable, which is atable.afieldX = MyFunc(atable.afield)? All what you need - to run UPDATE command once.
You should try to write a SQL Server function MyFunc. This way you will be able to run the same query in SQLserver and in Access.
A few usefull links for you so you can get started:
MSDN article about user defined functions: http://msdn.microsoft.com/en-us/magazine/cc164062.aspx
SQLServer user defined functions: http://www.sqlteam.com/article/intro-to-user-defined-functions-updated
SQLServer string functions: http://msdn.microsoft.com/en-us/library/ms181984.aspx
What version of JET (now called Ace) are you using?
I mean, it should come as no surprise that if you going to use some Access VBA code, then you need the VBA library and a copy of MS Access loaded and running.
However, in Access 2010, we now have table triggers and store procedures. These store procedures do NOT require VBA and in fact run at the engine level. I have a table trigger and soundex routine here that shows how this works:
http://www.kallal.ca/searchw/WebSoundex.htm
The above means if Access, or VB.net, or even FoxPro via odbc modifies a row, the table trigger code will fire and run and save the soundex value in a column for you. And this feature also works if you use the new web publishing feature in access 2010. So, while the above article is written from the point of view of using Access Web services (available in office 365 and SharePoint), the above soundex table trigger will also work in a stand a alone Access and JET (ACE) only application.

SQL Server Error: "Cannot use empty object or column names"

I get the following error:
Cannot use empty object or column names. Use a single space if necessary.
Msg 1038, Level 15, State 3, Line 1
and the query command looks like:
SELECT TOP 100 PERCENT
[].[cms_page].[pa_id], [].[cms_page].[pa_key],
[].[cms_page].[pa_title], [].[cms_page].[pa_keywords],
[].[cms_page].[pa_description], [].[cms_page].[pa_header],
[].[cms_page].[pa_created], [].[cms_page].[pa_modified],
[].[cms_page].[pa_language] FROM [cms_page]
WHERE
[cms_page].[pa_key] = #pa_key0
ORDER BY
[pa_id] ASC;
Strange indeed. Why does this happen? I'm using SubSonic 2.1.
Connectionstring:
<add name="OCDB" connectionString="Network Library=DBMSSOCN;Data Source=127.0.0.1,1433;Initial Catalog=test_db;User ID=test;Password=testpwd"/>
Edit: Well the solution was just to simply generate and rebuild the Data Access Layer and I was good to go.
You seem to be using a 3 part name with part of it empty, i.e. '[].'
It looks as though the query text is being constructed with an empty table schema.
Those empty [] square brackets should contain something like "dbo" to make the query syntactically valid. I don't know enough about SubSonic to give you a code sample though.
I'm not familiar with SubSonic, but have you tried a simpler query to test if you have your syntax correct? Does this query even work in SQL Server (Management Studio / Query Analyzer)?
Just looking at this from the perspective of SQL Server, you are using way too many brackets. If I was writing that query in SQL Server, it would look more like what I wrote below. I'm not sure about the variable #pa_key0, is this query part of a stored procedure or does SunSonic replace this variable when the query is ran?
SELECT
pa_id,
pa_key,
pa_title,
pa_keywords,
pa_description,
pa_header,
pa_created,
pa_modified,
pa_language
FROM
cms_page
WHERE
pa_key = #pa_key0
ORDER BY
pa_id ASC;
I think you need to set the schema for Subsonic to use. This thread seems to have some information:
Subsonic - How to use SQL Schema / Owner name as part of the namespace?

Resources