Say I have a custom data validation setup like this for a cell in Excel:
I then set the value of the cell in c# using Gembox Spreadsheet.
At this point, is there a way to verify (from c#) if the validation linked to this cell was successful or not?
What has been tried:
I did manage to find the DataValidation object linked to the cell via:
private DataValidation FindDatataValidationForCell(ExcelCell requiredCell)
{
foreach (DataValidation dv in requiredCell.Worksheet.DataValidations)
{
foreach (CellRange range in dv.CellRanges)
{
foreach (ExcelCell foundCell in range)
{
if (foundCell == requiredCell)
return dv;
}
}
}
return null;
}
But in the case of a custom validation, not sure where to go from here.
A workaround might be to write the formula read from the DataValidation object into a new (temporary) cell, and read the result, like this:
public bool IsValid(ExcelCell cell)
{
DataValidation dv = FindDatataValidationForCell(cell);
if (dv != null)
{
if (dv.Type == DataValidationType.Custom)
{
string str = dv.Formula1 as string;
if (str != null && str.StartsWith("="))
{
// dodgy: use a cell which is known to be unused somewhere on the worksheet.
var dummyCell = cell.Worksheet.Cells[100, 0];
dummyCell.Formula = str;
dummyCell.Calculate();
bool res = dummyCell.BoolValue;
dummyCell.Formula = null; // no longer required. Reset.
return res;
}
}
}
return true;
}
This does seem to work, but hoping there is a better way.
Or failing that, maybe a better way to work out a temporary dummy cell location.
Try using this latest bugfix version:
https://www.gemboxsoftware.com/spreadsheet/nightlybuilds/GBS49v1171.zip
Or this latest NuGet package:
Install-Package GemBox.Spreadsheet -Version 49.0.1171-hotfix
Now there is a DataValidation.Validate(ExcelCell) method that you can use.
Related
When I type a location starting with 'W', the related locations are listed below. But if I erase the already typed location and then type in a different one starting with 'L', then the list shows the previously listed options for the old location first(locations starting with 'W') then the options related to new location are listed.
Because of this the autocomplete list displays the locations starting with 'W' and then the locations starting with 'L',both.
I also tried placing options.removeAll(); as first statement in the filter method.
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String add) {
options.removeAll();
if(add.length() == 0) {
return false;
}
String[] l = searchLocations(add);
if(l == null || l.length == 0) {
return false;
}
for(String s : l) {
options.addItem(s);
}
return true;
}
};
//ac.setMinimumElementsShownInPopup(1);
ac.setMinimumLength(1);
Container c = stateMachine.findContainer(form);
AutoCompleteTextField oldac = (AutoCompleteTextField) stateMachine.findAddress(c);
c.replace(oldac, ac, null);
Is there a way to rectify this?
Thanks!!
Check out this live sample, this issue doesn't occur here so I'm guessing the problem with the preexisting results is related to the way you modified the the model.
I have this line of code:
if ((self.datasource?.contains((self.textField?.text)!)) != nil) {
if let _ = self.placeHolderWhileSelecting {
// some code
}
Is there more clear way to check if the element contains in array? I have Bool returned by contains function, I dont want to check if this Bool is nil
Edit: the solution is to change array to non-optional type.
You can use the if let where construct. This code prevent crashes if self.datasource or self.textField are nil
if let
list = self.datasource,
elm = self.textField?.text,
_ = self.placeHolderWhileSelecting
where list.contains(elm) {
// your code
}
Another possible solution, using optional chaining to get to self.textField.text and assuming datasource remains optional.
if let unwrappedArray = self.datasource, let unwrappedString = self.textField?.text {
if unwrappedArray.contains(unwrappedString) {
// Some code
}
}
I have the following code:
public fun findSomeLikeThis(): ArrayList<T>? {
val result = Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>
if (result == null) return null
return ArrayList(result)
}
If I call this like:
var list : ArrayList<Person>? = p1.findSomeLikeThis()
for (p2 in list) {
p2.delete()
p2.commit()
}
It would give me the error:
For-loop range must have an 'iterator()' method
Am I missing something here?
Your ArrayList is of nullable type. So, you have to resolve this. There are several options:
for (p2 in list.orEmpty()) { ... }
or
list?.let {
for (p2 in it) {
}
}
or you can just return an empty list
public fun findSomeLikeThis(): List<T> //Do you need mutable ArrayList here?
= (Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>)?.toList().orEmpty()
try
for(p2 in 0 until list.count()) {
...
...
}
I also face this problem when I loop on some thing it is not an array.
Example
fun maximum(prices: Array<Int>){
val sortedPrices = prices.sort()
for(price in sortedPrices){ // it will display for-loop range must have iterator here (because `prices.sort` don't return Unit not Array)
}
}
This is different case to this question but hope it help
This can also happen in Android when you read from shared preferences and are getting a (potentially) nullable iterable object back like StringSet. Even when you provide a default, the compiler is not able to determine that the returned value will never actually be null. The only way I've found around this is by asserting that the returned expression is not null using !! operator, like this:
val prefs = PreferenceManager.getDefaultSharedPreferences(appContext)
val searches = prefs.getStringSet("saved_searches", setOf())!!
for (search in searches){
...
}
I'm using ObjectEvents to give ActivityPoints to current user based on fields user filled.
Now for example if user register and fill FirstName I will give 10 points to user.
The problem is that I'm handling ObjectEvents.Update.After and inside it I'm updating userSettings.This causes a unlimited loop and application stops working.
is there any work around?
this is the code block:
var className = e.Object.TypeInfo.ObjectClassName;
DataClassInfo dci = DataClassInfoProvider.GetDataClass(className);
if (dci != null)
{
var fi = new FormInfo(dci.ClassFormDefinition);
if (fi != null)
{
var stopProccess = true;
var fields = new List<FormFieldInfo>();
foreach (var changedColumn in e.Object.ChangedColumns())
{
var field = fi.GetFormField(changedColumn);
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
if (!string.IsNullOrEmpty(activityPointMacro))
{
fields.Add(field);
stopProccess = false;
}
}
if (!stopProccess)
{
var contextResolver = CMSContext.CurrentResolver.CreateContextChild();
foreach (FormCategoryInfo info in fi.ItemsList.OfType<FormCategoryInfo>())
{
contextResolver.SetNamedSourceData(info.CategoryName, info);
}
EditingFormControl data = new EditingFormControl();
foreach (FormFieldInfo info2 in fi.ItemsList.OfType<FormFieldInfo>())
{
contextResolver.SetNamedSourceData(info2.Name, data);
}
foreach (var field in fields)
{
{
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
var activityPoint =
ValidationHelper.GetInteger(contextResolver.ResolveMacros(activityPointMacro), 0);
CMSContext.CurrentUser.UserSettings.UserActivityPoints += activityPoint;
CMSContext.CurrentUser.UserSettings.Update();
}
}
}
}
}
If you just need to give points for user fields then you could just use ObjectEvents.Update.Before, check fields are not empty and assign points. But i can see from the code, you want to have something more complex bulit over macro expressions. So I have a few suggestions for you.
1) ObjectEvents.Update.Before instead of ObjectEvents.Update.After still may be a good idea. Ideally you set your additional values and all is set during one update.
2) Watch only the class names you need
3) Always prefer Provider.SetInfo methods over info.Update(). In case of user settings it's best to set whole user info, so UserInfoProvider.SetUserInfo. Provider methods may add some additional important logic.
4) The code seems like it'll add the points with every update of a user
5) if you are still running into a loop, you need to flag somehow, that some part of code should not be executed again. The best way is to use RequestStockHelper class - add a bool value with a specificname like "PointsProcessed".
Here's what I'm currently doing/trying to do to accomplish my goal. But it is not removing the "row" the way I would like it too.
So, I'm making an object, then pushing it into an array. And the adding to the array part works fine and just as I expect.
var nearProfileInfoObj:Object = new Object();
nearProfileInfoObj.type = "userInfo";
nearProfileInfoObj.dowhat = "add";
nearProfileInfoObj.userid = netConnection.nearID;
nearProfileInfoObj.username = username_input_txt.text;
nearProfileInfoObj.sex = sex_input_txt.selectedItem.toString();
nearProfileInfoObj.age = age_input_txt.selectedItem;
nearProfileInfoObj.location = location_input_txt.text;
nearProfileInfoObj.headline = headline_input_txt.text;
theArray.push(nearProfileInfoObj);
So after that later on I need to be able to remove that object from the array, and it's not working the way I'm expecting. I want to take a variable whoLeft and capture their ID and then look in the array for that particular ID in the userid part of the object and if its there DELETE that whole "row".
I know you can do a filter with an array collection but that doesnt actually delete it. I need to delete it because I may be adding the same value again later on.
whoLeft = theiruserIDVariable;
theArray.filter(userLeaving);
public function userLeaving(element:*, index:int, arr:Array):Boolean
{
if (element.userid == whoLeft)
{
return false;
}
else
{
return true;
}
}
But this doesnt seem to be deleting the whole row like it implies. Does anyone know what i'm doing wrong?
Instead of modifying the original array, the new filtered array is returned by the filter method. So you need to assign the returned array to theArray.
Try this
theArray = theArray.filter(userLeaving);
EDIT This turned out to be slower than for loop:
An alternative to the hand coded loop could be something like this:
theArray.every(searchAndDestroy);
public function searchAndDestroy(element:*, index:int, arr:Array):Boolean
{
if (element.userid == whoLeft)
{
arr.splice(index,1);
return false;
}
return true;
}
As far as I know, every() terminates the first time the test function returns false. So the question is: for a big list, which is faster, the for loop or the loop that every() does with the overhead of the test function call.
EDIT #2 But this was faster than a for loop for a test I ran on an array of a million Points:
for each(var element:Object in theArray)
{
if (element.userid==whoLeft)
{
theArray.splice(theArray.indexOf(element),1);
break;
}
}
I think this is what you're looking for:
for(var i:uint = 0, len:uint = theArray.length; i<len; i++)
{
if(thisArray[i].id == whoLeft.id)
{
thisArray.splice(i, 1);
break;
}
}
However, do you really need it in an Array because you could always use a Dictionary which would mean accessing it by id which would be a lot simpler to remove.