dealing with a null date field - datetime

I have a date field on an XPage, this control may contain a date or be blank. In a repeat control I have this code:
var doc:NotesDocument = detailData.getDocument();
var sDate = doc.getItemValue("ACAutoStart");
doc.recycle()
return "Start Date = " + sDate
If ACAutoStart contains a date then it is displayed as [10/10/2013 12:34:15 AM MDT] if it is blank it displays as []. As I understand it the [] indicates that the result is an array but if I try using sDate[0] there is an error. I can't use getItemValueDateTime as it does not like the null return. How do I get this into a simple string value?

Replace your last line with return "Start Date = " + sDate.firstElement().
doc.getItemValue() returns an object of class java.util.Vector. As it is not an Array you get the first element with firstElement() instead of [0] .
UPDATE:
As you mentioned in your comment it has to work also for empty values and you added try:
var sDate = "";
try {sDate = doc.getItemValue("ACAutoStart").firstElement()} catch (e) {};
return "Start Date = " + sDate

...just as another way (returns converted NotesDateTime to Date):
function getJavaDateData(doc:NotesDocument, field:string)
{
var item:NotesItem = doc.getFirstItem(field);
if (item != null){
var dt:NotesDateTime = item.getDateTimeValue();
if (dt != null){
return dt.toJavaDate();
}
}
return null;
}
Off-course need to be adapted for your logic...

Related

Initialise jqueryeasyui datebox with current date

I am using jquery easyui edatagrid, where one column is of datebox type editor.
I want to auto select today date so that data entry is faster.
Code :
<th field="date" width="50" editor="{type:'datebox',options:{formatter:myformatter,parser:myparser,required:true}}">Date</th>
function myformatter(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return (d<10?('0'+d):d)+'/'+(m<10?('0'+m):m)+'/'+ y;
}
function myparser(s){
if (!s) return new Date();
var ss = (s.split('/'));
var d = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var y = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
}
You can set the date as soon as the grid data is loaded. For example, something like
$('.datebox input').each( function(){ $(this).val(formatDate(new Date())) });
It is a matter of getting the input fields. For me the above works, you can adjust it according to your code. Then you need a function that does the date formatting, for example
function formatDate(value) {
return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getYear();
}

XtraGrid AutoFilterRow custom range filtering

I'm trying to improve the AutoFilterRow functionality for one of my columns. The column will always consist of a string that represents a range of values like this: "num1 - num2". I would like to allow end users to type a value into the cell in the AutoFilterRow and in this particular column and the rows whose sections have a range that includes the number they typed. For instance, if I had 3 rows and each of their section attributes were the following: "1 - 4", "1 - 6", and "4 - 6", and a user types "3" into the AutoFilterRow cell for this column, I would expect the rows containing "1 - 4" and "1 - 6".
I have already overwritten the CreateAutoFilterCriterion in MyGridView to allow for additional operators as suggested in several examples found on this site:
protected override CriteriaOperator CreateAutoFilterCriterion(GridColumn column, AutoFilterCondition condition, object _value, string strVal)
{
if ((column.ColumnType == typeof(double) || column.ColumnType == typeof(float) || column.ColumnType == typeof(int)) && strVal.Length > 0)
{
BinaryOperatorType type = BinaryOperatorType.Equal;
string operand = string.Empty;
if (strVal.Length > 1)
{
operand = strVal.Substring(0, 2);
if (operand.Equals(">="))
type = BinaryOperatorType.GreaterOrEqual;
else if (operand.Equals("<="))
type = BinaryOperatorType.LessOrEqual;
else if (operand.Equals("<>"))
type = BinaryOperatorType.NotEqual;
}
if (type == BinaryOperatorType.Equal)
{
operand = strVal.Substring(0, 1);
if (operand.Equals(">"))
type = BinaryOperatorType.Greater;
else if (operand.Equals("<"))
type = BinaryOperatorType.Less;
else if (operand.Equals("!") || operand.Equals("~"))
type = BinaryOperatorType.NotEqual;
}
if (type != BinaryOperatorType.Equal)
{
string val = strVal.Replace(operand, string.Empty);
try
{
if (!val.IsEmpty())
{
if (column.ColumnType == typeof(double))
{
var num = Double.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
if (column.ColumnType == typeof(float))
{
var num = float.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
else
{
var num = int.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
}
// DateTime example:
// DateTime dt = DateTime.ParseExact(val, "d", column.RealColumnEdit.EditFormat.Format);
// return new BinaryOperator(column.FieldName, dt, type);
}
catch
{
return null;
}
}
}
//
// HERE IS WHERE I WANT TO ADD THE FUNCTIONALITY I'M SPEAKING OF
//
else if (column.FieldName == "SectionDisplayUnits")
{
try
{
if (!strVal.IsEmpty())
{
}
}
catch
{
return null;
}
}
return base.CreateAutoFilterCriterion(column, condition, _value, strVal);
}
How would I go about doing that? I figure I want to split each string with a call to Split(...) like this: cellString.Split(' - '). Then I would parse each string returned from the call to Split(...) into a number so that I could use inequality operators. But I'm just not sure how to go about doing this. Can I get some help? Thanks!
Update:
Please take a look here for a more in-depth discussion on this matter with myself and a knowledgeable DevExpress representative. I received a lot of help and I wanted to share this knowledge with whoever needs similar assistance. Here is the link.
Using C#, you would split the value into two parts, convert them to the number, and compare the value entered by the user with both values to ensure that it is greater or equal the first part and less or equal the second part.
In Criteria Language, the same functionality can be created using Function Operators. However, the expression will be a bit complex. Please try the following. It will work only if the format of values in the SectionDisplayUnits column is fixed, and the value always consists of two numbers delimited by "-".
string rangeDelimiter = "-";
return CriteriaOperator.Parse("toint(trim(substring(SectionDisplayUnits, 0, charindex(?, SectionDisplayUnits)))) <= ? && toint(trim(substring(SectionDisplayUnits, charindex(?, SectionDisplayUnits) + 1, len(SectionDisplayUnits) - charIndex(?, SectionDisplayUnits) - 1))) >= ?", rangeDelimiter, _value, rangeDelimiter, rangeDelimiter, _value);

Specific row withing a DataTable

I have a data table which has a "Total" column. I want to be able to get a specific rows "Total" not all rows.
public void maxValue()
{
string pass = (String)Session["name"];
DataTable table = (DataTable)Session["CocaCola"];
int total = table.AsEnumerable().Sum(r => r.Field<int>("Total"));
int totalAllowed = table.AsEnumerable().Sum(r => r.Field<Int32>("Total Allowed"));
if (total >= totalAllowed)
{
Label1.Text = "Total value exceeded the maximum of " + totalAllowed;
}
else if (total < totalAllowed)
{
Label1.Text = "Total value which is allowed :" + totalAllowed;
}
if (pass.Equals("Low"))
{
Label1.Text = "You are not allowed any assets at this Stage";
//SNS.Checked = false;
//TT.Checked = false;
//Music.Checked = false;
//SNS.Enabled = false;
//TT.Enabled = false;
//Music.Enabled = false;
}
}
As you can see my method works but add the column up which i dont want to do. How would i go about changing it?
You can do it this way
int yourTargetindex = 0; //Change this to get the value of your target element
int total =(from row in table.AsEnumerable()
select row.Field<int>("Total")).ElementAt(yourTargetindex);
//This will return the first value of "total" in the DataTable
You don't have to use linq. DataTable has built-in methods for this kind of operations:
var selectedTotal = table.Compute("sum(Total)", "columnX == 'x'");
This tell the table to calculate the sum of all Total cells in rows where columnX has the specified value.
Of course you can use linq. You would need to add a Where() before you calculate the sum.

Getting date as string - need to convert

Programming in Flex 4.5
I'm getting a date as a String.
I don't know what date or hour I'm getting.
I want to convert the string to date and take only the hours & minutes.
For example:
Getting - "2012-02-07T13:35:46+02:00"
I want to see: 13:35.
Suggestions or any other solutions?
After some digging, Solution:
var myDate:Date;
myDate = DateFormmater.parseDateString(myDateString);
var dateResult:String = myDate.getHours() + ":" + myDate.getMinutes();
Thanks anyway! :-)!
You can to use date.getHours() and date.getMinutes(). Try the following:
var d:Date = DateField.stringToDate("your_date_string","YYYY-MM-DD");
trace("hours: ", date.getHours()); // returns 13
trace("minutes: ", date.getMinutes()); // returns 35
private function init():void
{
var isoStr:String = "2012-02-07T13:35:46+02:00";
var d:Date = new Date;
d = isoToDate(isoStr)
trace(d.hours);
}
private function isoToDate(value:String):Date
{
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("+02:00", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I see you've already got the answer, but for future users, here it is.
var myDateString:String="2012-02-07T13:35:46+02:00"
//This is of the format <yyyy-mm-dd>T<hh:mm:ss><UTC-OFFSET AS hh:mm>
//You could write your own function to parse it, or use Flex's DateFormatter class
var myDate:Date=DateFormatter.parseDateString(myDateString);
//Now, myDate has the date as a Flex Date type.
//You can use the various date functions. In this case,
trace(myDate.getHours()); //Traces the hh value
trace(myDate.getMinutes()); //Traces the mm value

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

Resources