Passing a vb variable to an SQL statement in ASP.NET - asp.net

I've tried hard to make sure I couldn't find the answer to this anywhere, so apologies if it's a repeat.
I want to use a WHERE clause to filter data output from an SQL Server statement to items which are less than two weeks old. I've successfully managed to write the .vb code to get the date from two weeks ago, however I'm having trouble trying to insert this date into the statement from my .aspx page.
The code to calculate the date two weeks ago is as follows:
Protected dateBuffer As String = lastFortnight().ToString("dd/MM/yyyy")
Function lastFortnight() As DateTime
Dim retVal As DateTime = DateTime.Now.AddDays(-14)
Return retVal
End Function
This returns a date of 06/01/2014 (as of today) if called on my .aspx page using <%=dateBuffer %>
However if I try and insert it into my SQL statement to filter the outputs like so:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Database SQL 20130905ConnectionString %>"
ProviderName="<%$ ConnectionStrings:Database SQL 20130905ConnectionString.ProviderName %>"
SelectCommand="SELECT [ReqNumber], [ApprovedDate], [Approved] FROM [RequisitionDetails] WHERE ([RequestDate] >= ?)">
<SelectParameters>
<asp:Parameter DefaultValue='<%=dateBuffer %>' Name="RequestDate" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
I consistently get the error
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
I've spent most of my day searching for how to fix this, and I'm still no closer than I was 4 hours ago. If I'm making any stupid mistakes please let me know... I'm a complete newbie when it comes to any of this stuff, It's the first time I've ever worked with .aspx, .vb and SQL server.

SQL's date format differs from the .NET DateTime data type, which is why you're getting the formatting error. There are ways to convert, such as using the SqlDateTime struct - How can I convert a .Net Datetime to a T-SQL Datetime
In your case though, might it not be simpler to pass the number of days to your SQL statement (or stored proc), and use a DateDiff/DateAdd combination in SQL ?

Related

SqlDataSource throwing "Specified cast is not valid" error on data pulled from Oracle

This SqlDataSource, which is pulling from an Oracle db, throws "Specified cast is not valid" ONLY when I include c.item_cost in the SQL. If I remove this column, no error. It does not matter if I actually reference the field in code.
<asp:SqlDataSource ID="mySqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" ProviderName="Oracle.ManagedDataAccess.Client"
SelectCommand="select msi.segment1 partnumber,
msi.description,
msi.primary_uom_code uom,
c.item_cost
from apps.cst_item_costs c, apps.mtl_system_items_b msi, APPS.ORG_ORGANIZATION_DEFINITIONS org
and msi.organization_id=org.ORGANIZATION_ID
and c.organization_id=org.ORGANIZATION_ID
and c.cost_type_id=1
and ((msi.inventory_item_id=c.inventory_item_id)
and (msi.organization_id=c.organization_id))
order by msi.segment1">
Also, if I add SQL to trim the number of rows down to a small number, the error is NOT thrown. I'm guessing it's some piece of data in the column causing the issue.
Is the SqlDataSource making some assumptions on datatypes?
Even if I can pinpoint the data, which appears to all be valid decimals, how can this error be avoided?
Please let me know if more information is needed. I am currently trying to pinpoint the data that causes this but everything appears to be a valid decimal though some have more digits. The SQL does successfully run with a db tool such as TOAD.
Update: The value in the c.item_cost is 15.032221226116 which is far more decimal digits than other data.
This is a problem involving conversion of Oracle data types to .Net types. Entity Framework 3 and 4 had a similar problem. If you specified an Oracle type as Number(10) it was interpreted as a .Net Float.
I suspect this is a similar issue with .Net casting the Oracle number into a float instead of a decimal. This answer has more details.
I recommend trying ROUND(c.item_cost,12) or even CAST(c.item_cost as DECIMAL(3,12)) as item_cost

DropDown -- Truncate DateTime to Date in Oracle SQL or ASP.NET?

Currently, I'm populating a DropDown with the following SQL:
SELECT REPORT_DATE FROM MY_TABLE
Although the values stored in the table are in the following format, dd-mon-yyyy (my preferred format), the text that fills my DropDown differs in that it also displays time, like dd-mon-yyyy hh:mm:ss AM.
What is the best way to resolve this? I know of TRUNC and TO_DATE functions in Oracle SQL. But I think I could also loop through the DropDown after its populated and truncate the string there. I have tried the following code, but it returns a runtime error:
For Each i As ListItem In DropDown1.Items
'Strip time here
i.Text.ToString("dd-MMM-yyyy")
Next
Essentially, I just want to loop my DropDown and change ONLY the text to match `dd-MMM-yyyy'. How can I accomplish this? Should I use SQL or VB.NET? Is there a best practice?
Thank you!
you can do this sql side with
SELECT to_char(REPORT_DATE, 'dd-mon-yyyy') report_date FROM MY_TABLE order by report_date;
p.s.
"values stored in the table are in the following format, dd-mon-yyyy". dates are not stored like that, they are stored as an 7 byte numeric internally, how you see them on select is entirely dependant on your NLS_DATE_FORMAT setting.
If the data is of type DateTime, you can simply specify the DataTextFormatString property on the dropdown as so:
<asp:dropdownlist DataTextFormatString ="{0:MM-dd-yyyy}" ... />
It should be to the UI layer to display the date in the format you want. You should try to avoid putting the logic to transform the date to the format you want on the SQL statement, if possible.
Use this string to get data from Oracle
SELECT TO_CHAR(REPORT_DATE,'DD-MON-YYYY') FROM MY_TABLE
Try
i.Text = Convert.ToDateTime(i.Text).ToString("dd-MMM-yyyy")
You cannot use .ToString("dd-MMM-yyyy") for date formatting on string. You need to convert it to DateTime
You can also try <asp:DropDownList DataTextFormatString="{0:dd-MMM-yyyy}" />
It's better to format the date in the DropDownList instead of letting sql doing it.
Just add DataTextFormatString="{0:dd/MM/yyyy}" to your DropDownList tag :
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="adddate"
DataTextFormatString="{0:dd/MM/yyyy}" DataValueField="adddate">
</asp:DropDownList>

Different date format in development server and production server in asp.net

I have a gridview with 3 columns, in database the date field of the origin table isn't stored as a date format (the table is in oracle), is stored in string format, so I have my datasource in asp like this
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:OracleXexdb %>"
ProviderName="<%$ ConnectionStrings:OracleXexdb.ProviderName %>"
SelectCommand="select to_date(date, 'mm/dd/yyyy') as date, user, description from mytable where user is not null"
filterexpression = "user LIKE '%{0}%'"
>
</asp:SqlDataSource>
As you can see in the SelectCommand, I convert the date field with the format dd/mm/yyyy (in the database the date format is mm/dd/yyyy); when I run my webpage in the asp.net development server everything is fine, I mean I see the date field with the format dd/mm/yyyy but when I put the webpage on the server I see the mm/dd/yyyy format.
Is there anything I can do? thanks in advance
The most likely reason for the difference when deploying the application is that the culture that will be picked up will be different.
Setting the culture explicitly to the needed one in the Web.config file system.web globalization configuration or on the current thread should resolve the problem.
For example: See Example in Comment Below
The date format can also be specified explicitly on the DatePicker by using the Format method.

Update Syntax for Oracle 10g using ASP.NET

I have a GridView with an Update button. I want to update a field in the database but I think the '#' in the code below is causing the problem in my ASP .NET page. What can be done within the grid or in the update (UpdateCommand) statement? Note, I get an Ora 00936 error.
<asp:SqlDataSource ID="dsBooks" runat="server"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT OBJECTID, TRACT, GIS_ACRES, COMMENTS, PDF_STORAGE FROM CampusDev.CU_POLY ORDER BY OBJECTID"
UpdateCommand="UPDATE CampusDev.CU_POLY SET COMMENTS='just atest' WHERE OBJECTID=#OBJECTID"
The ":OBJECTID" in Oracle parlance is a Bind Variable.
I'm ignorant of asp.net semantics, but you will want to use bind variables here. This link should provide a more complete explanation, but basically it's this:
cmd.Parameters.Add(new OracleParameter(“OBJECTID″, #OBJECTID));
UpdateCommand="UPDATE CampusDev.CU_POLY
SET COMMENTS='just atest' WHERE OBJECTID=:OBJECTID"
Then execute your command.
Always use bind variables where possible in production code - it allows Oracle to avoid hard parsing of the SQL statement.
Also, the name of the Bind Variable is unimportant to Oracle. The order in which it appears is the important aspect. You could just as easily say
WHERE OBJECTID=:1
with the same effect.
Oracle usually has : instead of #:
WHERE OBJECTID = :OBJECTID
Or perhaps objectid is a reserved word, which you can escape with " in Oracle:
WHERE "OBJECTID" = :OBJECTID
Or perhaps you'd have to specify a parameter to ASP.NET:
<asp:SqlDataSource ...>
<UpdateParameters>
<asp:Parameter Type="Int32" Name="ObjectId" />
</UpdateParameters>
</asp:SqlDataSource>

Can't filter Oracle SELECT in ASPX

Part of an ASP.Net 2 datasource:
SelectCommand="SELECT BU.P_GEAC_CORP_CD AS Corp_Code,
BU.Business_unit as Abbreviation,
CC.DEPTID AS Cost_Center,
CC.DESCR AS Description
FROM fstst.PS_P_CATR_BUDPT_VW CC,
fstst.ps_p_bus_unit_cnv BU
WHERE BU.Business_unit = CC.Business_unit">
This feeds a GridView which works. The display shows that
CC.DESCR AS Description
is text (non-numeric).
I want to use a textbox as a "contains" filter, i.e., if I put "Recovery" in the box,
I want the datasource to add
AND CC.DESCR Like '%Recovery%'
to the SQL. If I hard-code that line, it works.
But if I add
<SelectParameters>
<asp:ControlParameter ControlID="Dept_Name"
Name="DName"
PropertyName="Text"
Type="string" />
</SelectParameters>
without changing the SQL, I get no rows returned. Then if I put
AND CC.DESCR Like '%' + :DName + '%'
into the SQL, I get no results when the textbox is blank, and ORA-01722: invalid number as soon as I put characters in it.
Thanks for the attempt, "birdlips."
Unfortunately, the Oracle server had only minimal logging turned on.
On top of that, while I was visiting the DBA, stackoverflow somehow ended up on our company's list of forbidden sites. So I could not share the answer.
This must be a little known fact about Oracle, as our two DBAs didn't catch it either: Oracle thinks plus is for numbers no matter what the context.
It worked as soon as I changed + to ||
you need to use single quotes around the text when using a like statement with a string.
It needs to look like
AND CC_DESCR LIKE '%VALUE%'

Resources