Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Useful Helper Methods

Here are a few generic methods to help you out:

The GetValue method has an argument named timeContext, which is an object. Your output calculation
will want a specific AFTime instead of an object. One of many ways to determine that is this method:

private static AFTime ToAFTime(object timeContext)


{
if (timeContext is AFTime)
{
return (AFTime)timeContext;
}
else if (timeContext is AFTimeRange)
{
return ((AFTimeRange)timeContext).EndTime;
}
return AFTime.NowInWholeSeconds;
}

You may find the need to make sure the measurement attribute is a numeric data type. This could be
done in the GetInputs method or in GetValue.

private static bool IsNumericType(TypeCode typeCode)


{
switch (typeCode)
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}

If you wanted to know the data type associated with an AFAttribute, you will need an extra call. Here's a
small snippet:

IsNumericType(Type.GetTypeCode(attr.Type))

If you want to know the data type of an AFValue's Value, this is more direct:

IsNumericType(value.ValueTypeCode)

And finally, as the world is not perfect, neither is data. You may have bad data or data completely
missing. There are many ways in .NET to deal with this situation. You could use nullable values such as
int? or single?. My approach is to treat all numerics as a double and let double.NaN represent any kind of
bad or missing data scenario.

private static double ToDouble(AFValue value)


{
if (value == null || !value.IsGood || !IsNumericType(value.ValueTypeCode))
{
return double.NaN;
}
// https://techsupport.osisoft.com/Documentation/PI-AF-
SDK/html/M_OSIsoft_AF_Asset_AFValue_ValueAsDouble.htm
return value.ValueAsDouble();
}

You might also like