How to check for a specific value in List<T> foreach loop - asp.net

Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.
For example how do I…
If (value.something_2 == "Null")
{
value.something_2 == ".";
}
Elseif (value.something_2 == " ")
{
value.something_2 == "0";
}
How would I incorporate the above example within the “foreach” loop?
See code below.
protected void MyReport(string filename, IMyRepository repository)
{
using (FileStream fileStream = new FileStream(Server.MapPath(#"~/Includes/") + filename, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
List<Report> _report = repository.GetMyReport().ToList();
foreach (var value in _report)
{
String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_1,
values.something_2,
value.something_3);
String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_4,
values.something_5,
value.something_6);
Writer.WriteLine(row01);
Writer.WriteLine(row02);
}
}
writer.Close();
}
}

There is no clever built-in String.Format that you can do for this if that's what you have in mind. However, the compiler has some tricks that can reduce the amount of code you need to write e.g.
// if it's null, assign it to "."
var s2 = value.something_2 ?? ".";
// it can never be null here, so if there is whitespace default to "0"
value.something_2 = String.IsNullOrWhitespace(s2) ? "0" : s2;

If I'm understanding what you're saying, it might be easier just to have another function returning the (possibly) modified string and just pass each of your values into it, inline.
Sting row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", myFunc(value.somthing_1), myFunc(values.something_2), myFunc(value.something_3));
and then have this in the same class
private string myFunc(string something){
if (something == “Null”){
return “.“;
} else if (something == “ “) {
return “0”;
} else {
return something;
}
}

Related

Are Guids unique when using a U-SQL Extractor?

As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors

How can i get columns added on column?

heres my code below...
TableColumn tc = new TableColumn();
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}
and i try to override commit method for editing cells.
public void commit(Object val) {
// Get the table
TableView<MainTable> t = this.getTableView();
// Get the selected row/column
MainTable selectedRow = t.getItems().get(this.getTableRow().getIndex());
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
// Get current property name
String propertyName = ((PropertyValueFactory) selectedColumn.getCellValueFactory()).getProperty();
// Create a method name conforming to java standards ( setProperty )
propertyName = ("" + propertyName.charAt(0)).toUpperCase() + propertyName.substring(1);
// Try to run the update
try {
// Type specific checks - could be done inside each setProperty() method
if(val instanceof Double) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, double.class);
method.invoke(selectedRow, (double) val);
}
if(val instanceof String) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, String.class);
method.invoke(selectedRow, (String) val);
}
if(val instanceof Integer) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, int.class);
method.invoke(selectedRow, (int) val);
}
} catch (Exception e) {
e.printStackTrace();
}
// CommitEdit for good luck
commitEdit((String) val);
}
and i got ArrayIndexOutofBoundsException on console view.
so my question is
how can i select getcolumns added other column???
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
i think this code has to be changed...
anyone got ideas??
Nested columns are not part of the TableView.columns list.
If you need the corresponding TableView column, just go up through the hierarchy until you reach a column without a parentColumn:
TableColumn<MainTable, ?> selectedColumn = this.getTableColumn();
TableColumn<MainTable, ?> c = selectedColumn;
while ((c = selectedColumn.getParentColumn()) != null) {
selectedColumn = c;
}
If you just need the column itself, simply use this.getTableColumn(), instead of finding the index of the column in the columns list and then accessing that index in the same list. (I guess the latter is what you need.)
Furthermore, if PropertyValueFactory returns properties of the item class, you could use this property to set the value instead of using reflection:
ObservableValue obs = selectedColumn.getCellObservableValue(this.getIndex());
if (obs instanceof WritableValue) {
((WritableValue) obs).setValue(val);
} else {
// reflecitive approach
}
Furthermore you shouldn't add null as a nested column, but you're doing it here:
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}

Is it possible to use a Kleene Operator for Flex Formatters?

is it possible to use a Kleene Operator (Kleene Star) for the Formatters?
I want to use a phoneFormatter, which puts a minus after the 5th number and afterwards it should be possible to have a variable number of numbers.
E.g.: 0172-555666999, 0160-44552 etc.
That is how I started, but I don't know which character belongs after the last hash (it is not a star, I already tried it ;-) ):
<fx:Declarations>
<mx:PhoneFormatter id="mPhoneFormat"
formatString="####-#"/>
</fx:Declarations>
The default PhoneFormatter expects the input string to have the same number of characters as the format string. They don't support regular expression patterns (like * to match the element zero or more times).
However, it's pretty easy to make your own formatter. To do this, I extended the PhoneFormatter class and overrode its format() method. I copied and pasted the original format() method and made the following modifications:
comment out the code that compared the length of the source string with the length of the format string
compare the length of the formatted string. If the original string is longer, append the remaining chars from the original string to the formatted string.
This probably won't handle all of your use cases, but it should be pretty straightforward to modify this to your needs.
package
{
import mx.formatters.PhoneFormatter;
import mx.formatters.SwitchSymbolFormatter;
public class CustomPhoneNumberFormatter extends PhoneFormatter
{
public function CustomPhoneNumberFormatter()
{
super();
}
override public function format(value:Object):String
{
// Reset any previous errors.
if (error)
error = null;
// --value--
if (!value || String(value).length == 0 || isNaN(Number(value)))
{
error = defaultInvalidValueError;
return "";
}
// --length--
var fStrLen:int = 0;
var letter:String;
var n:int;
var i:int;
n = formatString.length;
for (i = 0; i < n; i++)
{
letter = formatString.charAt(i);
if (letter == "#")
{
fStrLen++;
}
else if (validPatternChars.indexOf(letter) == -1)
{
error = defaultInvalidFormatError;
return "";
}
}
// if (String(value).length != fStrLen)
// {
// error = defaultInvalidValueError;
// return "";
// }
// --format--
var fStr:String = formatString;
if (fStrLen == 7 && areaCode != -1)
{
var aCodeLen:int = 0;
n = areaCodeFormat.length;
for (i = 0; i < n; i++)
{
if (areaCodeFormat.charAt(i) == "#")
aCodeLen++;
}
if (aCodeLen == 3 && String(areaCode).length == 3)
{
fStr = String(areaCodeFormat).concat(fStr);
value = String(areaCode).concat(value);
}
}
var dataFormatter:SwitchSymbolFormatter = new SwitchSymbolFormatter();
var source:String = String(value);
var returnValue:String = dataFormatter.formatValue(fStr, value);
if (source.length > returnValue.length)
{
returnValue = returnValue + source.substr(returnValue.length-1);
}
return returnValue;
}
}
}

Flex DatagridColumn LabelFunction Additonal Parameters

I have a datagridcolumn where a labelFunction is defined:
private function myLabelFunction(item:Object, column:DataGridColumn):String
{
var returnVal:String;
var nm:NumericFormatter;
nm.decimalSeparatorTo = ".";
nm.precision = additionalParameter;
returnVal = nmTwoDecimals.format(item[column.dataField]);
if (returnVal == '0.00')
{
returnVal = '';
}
return returnVal;
}
Would it be possible to add an additional parameter so that I could pass the property values for the formatter which I intend to use?
Like for example:
private function myLabelFunction(item:Object, column:DataGridColumn, precisionParam:int):String
{
var returnVal:String;
var nm:NumericFormatter;
nm.decimalSeparatorTo = ".";
nm.precision = precisionParam;
returnVal = nmTwoDecimals.format(item[column.dataField]);
if (returnVal == '0.00')
{
returnVal = '';
}
return returnVal;
}
Thanks.
You would have to extend the DataGridColumn class. After creating your new class simply override the existing itemToLabel function:
public function itemToLabel(data:Object):String
{
if (!data)
return " ";
if (labelFunction != null)
return labelFunction(data, this);
if (owner.labelFunction != null)
return owner.labelFunction(data, this);
if (typeof(data) == "object" || typeof(data) == "xml")
{
try
{
if ( !hasComplexFieldName )
data = data[dataField];
else
data = deriveComplexColumnData( data );
}
catch(e:Error)
{
data = null;
}
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return " ";
}
The line 'return labelFunction(data, this);' is what calls the labelFunction (will also check the owner datagrid for a labelfunction). 'data' in 'itemToLabel' is your object. You could either include the precision value you want in the object or hard code it in the extended class (or inject, or singleton, class var, whatever you like).
At this point you can go ahead and pass it as a third parameter to your new labelFunction.
In your label function for the datagrid column, you can access the assigned data field by using the dataField property, see the following syntax below:
"supposing your label function is called formatNumbers_LabelFunction"
private function formatNumbers_LabelFunction(item:Object, column:DataGridColumn):String{
//Write any code logic you want to apply on your data field ;)
//In this example, I'm using a number formatter to edit numbers
return myCustomNumberFormatter.format(item[column.dataField]);
}
This way, you can use a generic label function to handle some unified operations on your displayed data
And besides that, you can also access to any data field that is in the data provider by just calling its name like this:
item.YourFieldName
where item is the firs parameter [of type Object] in your label function method
This would work:
<DataGridColumn labelFunction="{function(item:Object, column:DataGridColumn):String { return anotherLabelFunction(item,column,2) }}" />
// Elsewhere ...
function anotherLabelFunction(item:Object,column:DataGridColumn,precision:int):String
{
// Do your business
}

To check if an object is empty or not

I want to check in my function if a passed argument of type object is empty or not. Sometimes it is empty but still not null thus I can not rely on null condition. Is there some property like 'length'/'size' for flex objects which I can use here.
Please help.
Thanks in advance.
If you mean if an Object has no properties:
var isEmpty:Boolean = true;
for (var n in obj) { isEmpty = false; break; }
This is some serious hack but you can use:
Object.prototype.isEmpty = function():Boolean {
for(var i in this)
if(i != "isEmpty")
return false
return true
}
var p = {};
trace(p.isEmpty()); // true
var p2 = {a:1}
trace(p2.isEmpty()); // false
You can also try:
ObjectUtil.getClassInfo(obj).properties.length > 0
The good thing about it is that getClassInfo gives you much more info about the object, eg. you get the names of all the properties in the object, which might come in handy.
If object containes some 'text' but as3 doesn't recognize it as a String, convert it to string and check if it's empty.
var checkObject:String = myObject;
if(checkObject == '')
{
trace('object is empty');
}
Depends on what your object is, or rather what you expect it to have. For example if your object is supposed to contain some property called name that you are looking for, you might do
if(objSomeItem == null || objSomeItem.name == null || objSomeItem.name.length == 0)
{
trace("object is empty");
}
or if your object is actually supposed to be something else, like an array you could do
var arySomeItems = objSomeItem as Array;
if(objSomeItem == null || arySomeItems == null || arySomeItems.length == 0)
{
trace("object is empty");
}
You could also use other ways through reflection, such as ObjectUtil.getClassInfo, then enumerate through the properties to check for set values.... this class help:
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
public class ReflectionUtils
{
/** Returns an Array of All Properties of the supplied object */
public static function GetVariableNames(objItem:Object):Array
{
var xmlPropsList:XMLList = describeType(objItem)..variable;
var aryVariables:Array = new Array();
if (xmlPropsList != null)
{
for (var i:int; i < xmlPropsList.length(); i++)
{
aryVariables.push(xmlPropsList[i].#name);
}
}
return aryVariables;
}
/** Returns the Strongly Typed class of the specified library item */
public static function GetClassByName($sLinkageName:String):Class
{
var tObject:Class = getDefinitionByName($sLinkageName) as Class;
return tObject;
}
/** Constructs an instance of the speicified library item */
public static function ConstructClassByName($sLinkageName:String):Object
{
var tObject:Class = GetClassByName($sLinkageName);
//trace("Found Class: " + tMCDefinition);
var objItem:* = new tObject();
return objItem;
}
public static function DumpObject(sItemName:String, objItem:Object):void
{
trace("*********** Object Dump: " + sItemName + " ***************");
for (var sKey:String in objItem)
{
trace(" " + sKey +": " + objItem[sKey]);
}
}
//}
}
Another thing to note is you can use a simple for loop to check through an objects properties, thats what this dumpobject function is doing.
You can directly check it as follow,
var obj:Object = new Object();
if(obj == null)
{
//Do something
}
I stole this from a similar question relating to JS. It requires FP 11+ or a JSON.as library.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
can use use the hasProperty method to check for length
var i:int = myObject.hasProperty("length") ? myObject.length: 0;

Resources