Apex Dynamic SOQL date binding + days - soql

I am able to evaluate today's date using:
String timeframe = DateTime.newInstance(Date.today(), Time.newInstance(0, 0, 0, 0)).format('yyyy-dd-MM');
But I need to add days to this. So I want:
String timeframe = DateTime.newInstance(Date.today()**.addDays(10)**, Time.newInstance(0, 0, 0, 0)).format('yyyy-dd-MM');
query += ' and (created_date__c <= ' + timeframe + ')';
But am receiving this error: line 1:392 no viable alternative at character '2'
I also tried:
DateTime refDate1 = DateTime.newInstance(System.today().year(), System.today().month(), System.today().day(), 0, 0, 0);
DateTime refDate2 = refDate1.addDays(-10);
query += ' and created_date__c <= '+ refDate1.date() + ' and created_date__c >= ' + refDate2.date();
Which throws: line 1:405 no viable alternative at character ' '
Please help!

I resolved this using code I'd already tried, which makes me think there was something wrong with my soql string to begin with.
String timeframe = DateTime.newInstance(System.today().addDays(-10),
Time.newInstance(0, 0, 0,0)).format('yyyy-dd-MM');
whereClause += ' and (';
whereClause += 'created_date__c >= ' + timeframe;
whereClause += ' OR sourced_date__c >= ' + timeframe;
whereClause += ' OR last_phone_bank_call_date__c >=' + timeframe;
whereClause += ')';

Related

MS Access - Combine varchar column with int column - ASP.net VB.net

I'm using an oledb connection string to connect my asp.net code to an access db
I can't seem to convert combine the 3 fields - ProductID(NUMBER)
ProductCode(TEXT), ProdDescription(TEXT)
Dim strQuery As String = "SELECT ProductID, (CAST(ProductID AS TEXT) + ' - '
+ ProductCode + ' - ' + ProdDescription) AS [Prod]
FROM [FG - End Product Codes]
ORDER BY ProductCode;"
I've also tried
(CAST(ProductID AS VARCHAR(10)) + ' - ' + ProductCode + ' - ' + ProdDescription) AS [Prod]
And
(CONVERT(ProductID, TEXT)) + ' - ' + ProductCode + ' - ' + ProdDescription) AS [Prod]
AND
(CAST(ProductID) AS VARCHAR(10)) + ' - ' + ProductCode + ' - ' + ProdDescription) AS [Prod]
AND
(CAST([ProductID] AS TEXT) + ' - ' + [ProductCode] + ' - ' + [ProdDescription]) AS [Prod]
Error msg: System.Data.OleDb.OleDbException:
'IErrorInfo.GetDescription failed with E_FAIL(0x80004005).'
error code : -2147467259
I seen the same error in another question but theirs seem to have some reserve keyword problem, If mine is the same, what is My reserved Keyword and where is it in my code?
thanks in advance
That's because you try to use T-SQL against Access which uses Access SQL. So, try this:
Dim strQuery As String = "SELECT ProductID, ProductID & ' - ' &
ProductCode & ' - ' & ProdDescription AS [Prod]
FROM [FG - End Product Codes]
ORDER BY ProductCode;"

Reading from a text file and then Write to the text file in same classic ASP script

<%
dim narrationCounter,logDateString,logDate, logTime,folderName,folderPath,logFolder2,month,day,year,txtFilePath
logDateString = Request.Form("logDateString")
logDate = Date()
folderName = "NarrationClickLog" & "_" & logDate
month = DatePart("m",Now())
day = DatePart("d", Now())
year = DatePart("yyyy",Now())
folderPath = "D:\iisroot\casecomments\CaseNarrationClickLog" + "_" & month & "_" & day & "_" & year
txtFilePath = folderPath + "\CaseNarrationClickLog.txt"
visitorIP=Request.ServerVariables("REMOTE_ADDR")
visitorUserName = Request.ServerVariables("REMOTE_USER")
visitorHost = Request.ServerVariables("remote_host")
set oFs = server.createobject("Scripting.FileSystemObject")
If Not oFs.FolderExists(folderPath) Then
set logFolder=oFs.CreateFolder(folderPath)
End If
' Extract last updated narration button click value from text file
if oFs.FileExists(txtFilePath) then
if oFs.GetFile(txtFilePath).size <> 0 then 'Get narrationCounterVal from log file
' open the file and Read it
set oTextFile = oFs.OpenTextFile(txtFilePath, 1 , true) 'forreading
ReadMe = oTextFile.ReadAll
Tab = split(ReadMe,vbcrlf)
i = ubound(Tab) - 2
paragraph=paragraph & Tab(i) & ""
Response.Write("Paragraph is : " + paragraph)
paragraphReverse = StrReverse(paragraph)
Response.Write( paragraphReverse )
' get the narration counter
narrationCounterPos = Split(paragraphReverse)
'Default delimiter is the space character..in this case Split at the Space before colon SO first element in array is narration counter number
narrationCounterVal = StrReverse(narrationCounterPos(0))
'Response.Write("Latest Narration Counter from text file is :- " + narrationCounterVal)
narrationCounter = narrationCounterVal + 1
oTextFile.Close
set oTextFile = nothing
WriteToLogFile(narrationCounter)
else ' Set narration Counter Value = 1 , A NEW FIRST Record entry.
narrationCounter = 1
WriteToLogFile(narrationCounter)
end if
Response.Write("Latest Narration Counter value :- " + narrationCounterVal)
Response.Write("file exists")
else
Response.Write("File does not exist")
end if
function WriteToLogFile(narrationCounter)
set oTextFileWrite = oFs.OpenTextFile(txtFilePath, 8, True) ' "D:\IISROOT\CaseComments\CaseNarrationClickLog.txt"
oTextFileWrite.WriteLine " User IP Address: " + visitorIP + " User Name: " + visitorUserName + " Clicks on DATE : " + logDateString + " are : " + narrationCounter
Response.Write("Text file path : -" + txtFilePath & " visitor IP : " & visitorIP & " User name: " & visitorUserName & " visitor host: " & visitorHost)
oTextFileWrite.Close
set oTextFileWrite = nothing
end function
oTextFile.Close
set oTextFile = nothing
oTextFileWrite.Close
set oTextFileWrite = nothing
set oFS = nothing
%>
This code must do the following:
Checks if folder exists, if not, create
Check if text file exists, If Yes then Read contents from text file in the above way, extract the narrationCounterVal variable value and then WRITE to the text file using the WritetoLogFile(narrationCounter) function
Problem: Just stuck. The folder and file get created BUT nothing gets written to it. I am also making sure that I close the oTextFile object used for opening file in Read mode before I call the Writetologfile function.

SQL Server Data type change from Numeric(7,3) to Varchar(20)

I have a field (dose_str) that needs to be changed from Numeric(7,3) to Varchar(20). I would like to know if there will be a need to change the query below (especially this portion SELECT (convert(varchar,cast(Prot_det.dose_str as float)) ) in the code of my application.
myCommand.CommandText = "
SELECT (convert(varchar,cast(Prot_det.dose_str as float)) + ' '
+ dose_unit + ' ' + dose_form_comment + ' ' + dose_mult) as Dose_str
from
Prot_det,
dosage_form
where
Protocol_num = '" & lblProtocol.Text & "' and
nsc_num = " & lstNSC.SelectedValue & " and
prot_det.dose_form = dosage_form.dose_form"
After changing the datatype of the column, you will be able to change this:
(convert(varchar,cast(Prot_det.dose_str as float))
to this:
(Prot_det.dose_str)
And I would recommend that you do.

How to read text files that have line feed and carriage return intermixed using X++?

I am trying to read a text file using Dynamics AX. However, the following code replaces any spaces in the lines with commas:
// Open file for read access
myFile = new TextIo(fileName , 'R');
myFile.inFieldDelimiter('\n');
fileRecord = myFile.read();
while (fileRecord)
{
line = con2str(fileRecord);
info(line);
…
I have tried various combinations of the above code, including specifying a blank '' field delimiter, but with the same behaviour.
The following code works, but seems like there should be a better way to do this:
// Open file for read access
myFile = new TextIo(fileName , 'R');
myFile.inRecordDelimiter('\n');
myFile.inFieldDelimiter('_stringnotinfile_');
fileRecord = myFile.read();
while (fileRecord)
{
line = con2str(fileRecord);
info(line);
The format of the file is field format. For example:
DATAFIELD1 DATAFIELD2 DATAFIELD3
DATAFIELD1 DATAFIELD3
DATAFIELD1 DATAFIELD2 DATAFIELD3
So what I end up with unless I use the workaround above is something like:
line=DATAFIELD1,DATAFIELD2,DATAFIELD3
The underlying problem here is that I have mixed input formats. Some of the files just have line feeds {LF} and others have {CR}{LF}. Using my workaround above seems to work for both. Is there a way to deal with both, or to strip \r from the file?
Con2Str:
Con2Str will retrieve a list of values from a container and by default uses comma (,) to separate the values.
client server public static str Con2Str(container c, [str sep])
If no value for the sep parameter is specified, the comma character will be inserted between elements in the returned string.
Possible options:
If you would like the space to be the default separator, you can pass space as the second parameter to the method Con2Str.
One other option is that you can also loop through the container fileRecord to fetch the individual elements.
Code snippet 1:
Below code snippet loads the file contents into textbuffer and replace the carriage returns (\r) with new line (\n) character. The condition if (strlen(line) > 1) will help to skip empty strings due to the possible occurrence of consecutive newline characters.
TextBuffer textBuffer;
str textString;
str clearText;
int newLinePos;
str line;
str field1;
str field2;
str field3;
counter row;
;
textBuffer = new TextBuffer();
textBuffer.fromFile(#"C:\temp\Input.txt");
textString = textBuffer.getText();
clearText = strreplace(textString, '\r', '\n');
row = 0;
while (strlen(clearText) > 0 )
{
row++;
newLinePos = strfind(clearText, '\n', 1, strlen(clearText));
line = (newLinePos == 0 ? clearText : substr(clearText, 1, newLinePos));
if (strlen(line) > 1)
{
field1 = substr(line, 1, 14);
field2 = substr(line, 15, 12);
field3 = substr(line, 27, 10);
info('Row ' + int2str(row) + ', Column 1: ' + field1);
info('Row ' + int2str(row) + ', Column 2: ' + field2);
info('Row ' + int2str(row) + ', Column 3: ' + field3);
}
clearText = (newLinePos == 0 ? '' : substr(clearText, newLinePos + 1, strlen(clearText) - newLinePos));
}
Code snippet 2:
You could use File macro instead of hard coding the values \r\n and R that denotes the read mode.
TextIo inputFile;
container fileRecord;
str line;
str field1;
str field2;
str field3;
counter row;
;
inputFile = new TextIo(#"c:\temp\Input.txt", 'R');
inputFile.inFieldDelimiter("\r\n");
row = 0;
while (inputFile.status() == IO_Status::Ok)
{
row++;
fileRecord = inputFile.read();
line = con2str(fileRecord);
if (line != '')
{
field1 = substr(line, 1, 14);
field2 = substr(line, 15, 12);
field3 = substr(line, 27, 10);
info('Row ' + int2str(row) + ', Column 1: ' + field1);
info('Row ' + int2str(row) + ', Column 2: ' + field2);
info('Row ' + int2str(row) + ', Column 3: ' + field3);
}
}
Never tried to use the default RecordDelimiter as FieldDelimiter and not setting another RecordDelimiter explicitly. Normally rows (Records) are delimited by \n and fields are delimited by comma, tab, semicolon or some other symbol. You might also be hitting some weird behaviour when TextIO is assuming correct UTF-format. You didn't supply an example of some rows from you datafile, so guessing is hard.
Read more about TextIO here: http://msdn.microsoft.com/en-us/library/aa603840.aspx
EDIT:
With the additional example of file content, it seems to me the file is a fixed width file, where each column has its own fixed width. I would rather recommend using subStr if that is the case. Read about substr here: http://msdn.microsoft.com/en-us/library/aa677836.aspx
use StrAlpha to restrict blank values after you convert Con2Str

Select a Variable TimeSpan with an Arbitrary End point

I've been working on a Stored Procedure that checks the time, then retrieves records going back over the last full 24 hour period between 8am and the previous 8am. So, for instance, assume that it's currently 10am. The stored procedure looks at the current time, notes that it is past 8am, and sets the query to run backwards 24 hours, from 8am today to 8a yesterday. If it were, say, 7am, the query would be set to check from 8am yesterday to 8am the day before. This was actually relatively simple to do. The SP is meant to be used to retrieve records for a report tracking jobs completed in the given time span.
However, they've come back at me and asked me to change the stored procedure such that the hour the report ends at, and the span of time checked, is configurable from the front-end of the site. I have this working for TimeSpans greater or equal to 24 hours, but am having trouble with spans under that. Here's what I have so far for my logic in the Stored Procedure -
-- Retrieves data on jobs that completed/completed with errors during a given time span.
DECLARE #Hour NVARCHAR(2)
DECLARE #TimeFrame NVARCHAR(2)
DECLARE #TimeSpan INTEGER
SET #TimeSpan = 24
SET #TimeFrame = 'AM'
SET #Hour = '08'
DECLARE #dateStart DateTime
DECLARE #dateEnd DateTime
IF #TimeSpan < 24 -- Our TimeSpan is under one full day.
BEGIN
IF GETDATE() > DATEADD(hh, 0, DATEDIFF(hh, 0, GETDATE())) + (#Hour + ':00:00 ' + #TimeFrame)
BEGIN
SET #dateStart = DATEADD(hh, 0, DATEDIFF(hh, 0, GETDATE() - (1 + #TimeSpan))) + (#Hour + ':00:00 ' + #TimeFrame)
SET #dateEnd = DATEADD(hh, 0, DATEDIFF(hh, 0, GETDATE())) + (#Hour + ':00:00 ' + #TimeFrame)
END
ELSE
BEGIN
SET #dateStart = DATEADD(hh, 0, DATEDIFF(hh, 0, GETDATE() - (2 + #TimeSpan))) + (#Hour + ':00:00 ' + #TimeFrame)
SET #dateEnd = DATEADD(hh, 0, DATEDIFF(hh, 0, GETDATE() - 1)) + (#Hour + ':00:00 ' + #TimeFrame)
END
END
ELSE -- Our TimeSpan is at least one full day.
BEGIN
IF GETDATE() > DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())) + (#Hour + ':00:00 ' + #TimeFrame)
BEGIN
SET #dateStart = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE() - (1 + (#TimeSpan/24)))) + (#Hour + ':00:00 ' + #TimeFrame)
SET #dateEnd = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())) + (#Hour + ':00:00 ' + #TimeFrame)
END
ELSE
BEGIN
SET #dateStart = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE() - (2 + (#TimeSpan/24)))) + (#Hour + ':00:00 ' + #TimeFrame)
SET #dateEnd = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE() - 1)) + (#Hour + ':00:00 ' + #TimeFrame)
END
END
#Hour, #TimeFrame and #TimeSpan are all parameters ready to be set by the report front-end, and default to '08', 'AM' and 24 respectively. I know that setting the day range works properly in the ELSE portion of the top-level if. I'm reasonably certain that the issue with setting the hour offset lies in how I'm using the DATEADD and DATEDIFF function here, but I haven't been able to figure out just where I'm making my miss step. Any help here would be greatly appreciated.
-- convert the required end hour to 24 hour format
DECLARE #EndHour INT
SET #EndHour = CASE WHEN #TimeFrame = 'AM' THEN #Hour ELSE #Hour + 12 END
-- set #DateEnd to the date-only portion of the current datetime
-- ie, the time portion will be set to 00:00:00
SET #DateEnd = DATEADD(day, 0, DATEDIFF(day, 0, GETDATE()))
-- add the required end hour
SET #DateEnd = DATEADD(hour, #EndHour, #DateEnd)
-- if #DateEnd is in the future then subtract 24 hours from it
IF #DateEnd > GETDATE()
SET #DateEnd = DATEADD(hour, -24, #DateEnd)
-- set #DateStart by subtracting the required timespan from #DateEnd
SET #DateStart = DATEADD(hour, -#TimeSpan, #DateEnd)
Why not just use a query like:
SELECT something
FROM aTable
WHERE timeCompleted BETWEEN #StartDate AND #EndDate
If you are concerned about the time being correct (i.e. the dates must be '01/01/1900 13:00:00' or something like that) just pass in the date by itself and add the time as a function in the SQL.
If this is not what you are intending please include more of the SQL so that we have a better understanding of what you are trying to accomplish.

Resources