コード例 #1
0
ファイル: EndAggregate.cs プロジェクト: yuriik83/UA-.NET
        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            List<DataValue> l = new List<DataValue>(bucket.Values);
            DataValue dv = l.Count > 0 ? GetDataValue(l) : null;
            if (SteppedVariable && dv == null)
                dv = bucket.LateBound.Value;

            DataValue retval = new DataValue();
            StatusCode code = StatusCodes.BadNoData;
            if (dv != null)
            {
                code = StatusCode.IsNotGood(dv.StatusCode)
                    ? StatusCodes.UncertainDataSubNormal
                    : StatusCodes.Good;
                retval.SourceTimestamp = dv.SourceTimestamp;
                retval.Value = dv.Value;
                code.AggregateBits = AggregateBits.Raw;
                if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
            }
            else
            {
                retval.SourceTimestamp = bucket.From;
            }
            retval.StatusCode = code;
            return retval;
        }
コード例 #2
0
        private IEnumerable<Control> getBasicRegionBlocks()
        {
            var rs = new UpdateRegionSet();
            var pb = PostBack.CreateIntermediate( rs.ToSingleElementArray(), DataUpdate, id: "basic" );
            yield return new Paragraph( new PostBackButton( pb, new ButtonActionControlStyle( "Toggle Basic Region Below" ), usesSubmitBehavior: false ) );

            var regionControls = new List<Control>();
            var dynamicFieldValue = new DataValue<string>();
            if( info.Toggled ) {
                regionControls.Add(
                    FormItem.Create(
                        "Dynamic Field",
                        new EwfTextBox( "This was just added!" ),
                        validationGetter: control => new EwfValidation( ( pbv, validator ) => dynamicFieldValue.Value = control.GetPostBackValue( pbv ), pb ) ).ToControl() );
            }
            else
                regionControls.Add( new Paragraph( "Nothing here yet." ) );
            yield return
                new NamingPlaceholder(
                    new Section( "Basic Update Region", regionControls, style: SectionStyle.Box ).ToSingleElementArray(),
                    updateRegionSets: rs.ToSingleElementArray() );

            pb.AddModificationMethod( () => parametersModification.Toggled = !parametersModification.Toggled );
            pb.AddModificationMethod(
                () =>
                AddStatusMessage( StatusMessageType.Info, info.Toggled ? "Dynamic field value was '{0}'.".FormatWith( dynamicFieldValue.Value ) : "Dynamic field added." ) );
        }
コード例 #3
0
ファイル: DataHandler.cs プロジェクト: tjom/MIRPCADB
        private DataValue val; //additional information like color

        #endregion Fields

        #region Constructors

        public DataEntry(int id, double pca_x, double pca_y, DataValue val)
        {
            this.id = id;
            this.pca_x = pca_x;
            this.pca_y = pca_y;
            this.val = val;
        }
コード例 #4
0
        List<DataValue> _Items;			// list of DataValue

		public DataValues(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
		{
			DataValue dv;
            _Items = new List<DataValue>();
			// Loop thru all the child nodes
			foreach(XmlNode xNodeLoop in xNode.ChildNodes)
			{
				if (xNodeLoop.NodeType != XmlNodeType.Element)
					continue;
				switch (xNodeLoop.Name)
				{
					case "DataValue":
						dv = new DataValue(r, this, xNodeLoop);
						break;
					default:	
						dv=null;		// don't know what this is
						// don't know this element - log it
						OwnerReport.rl.LogError(4, "Unknown DataValues element '" + xNodeLoop.Name + "' ignored.");
						break;
				}
				if (dv != null)
					_Items.Add(dv);
			}
			if (_Items.Count == 0)
				OwnerReport.rl.LogError(8, "For DataValues at least one DataValue is required.");
			else
                _Items.TrimExcess();
		}
コード例 #5
0
        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            int numGood = 0;
            int numBad = 0;
            DataValue previous = RightState(bucket.EarlyBound.Value) ? bucket.EarlyBound.Value : null;
            double total = 0.0;

            DataValue retval = new DataValue { SourceTimestamp = bucket.From };
            StatusCode code = StatusCodes.BadNoData;

            foreach (DataValue v in bucket.Values)
            {
                if (state.RawValueIsGood(v))
                {
                    numGood += 1;
                    if (previous != null)
                        total += (v.SourceTimestamp - previous.SourceTimestamp).TotalMilliseconds;
                    previous = RightState(v) ? v : null;
                }
                else
                {
                    numBad += 1;
                }
            }
            if (previous != null)
                total += (bucket.LateBound.Value.SourceTimestamp - previous.SourceTimestamp).TotalMilliseconds;
            retval.Value = total;
            code = ComputeStatus(context, numGood, numBad, bucket).Code;
            code.AggregateBits = AggregateBits.Calculated;
            if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
            retval.StatusCode = code;
            return retval;
        }
コード例 #6
0
ファイル: TotalAggregate.cs プロジェクト: yuriik83/UA-.NET
 public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
 {
     int numGood = 0;
     int numBad = 0;
     double total = 0.0;
     foreach (DataValue v in bucket.Values)
     {
         if (state.RawValueIsGood(v))
         {
             numGood += 1;
             total += Convert.ToDouble(v.Value, CultureInfo.InvariantCulture);
         }
         else
         {
             numBad += 1;
         }
     }
     DataValue retval = new DataValue { SourceTimestamp = bucket.From };
     StatusCode code = ComputeStatus(context, numGood, numBad, bucket).Code;
     code.AggregateBits = AggregateBits.Calculated;
     if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
     if (StatusCode.IsNotBad(code))
         retval.Value = total;
     retval.StatusCode = code;
     GoodDataCount = numGood;
     return retval;
 }
コード例 #7
0
ファイル: ValueConverter.cs プロジェクト: stophun/fdotoolbox
        /// <summary>
        /// Gets the CLR value.
        /// </summary>
        /// <param name="val">The val.</param>
        /// <returns></returns>
        public static object GetClrValue(DataValue val)
        {
            if (val == null || val.IsNull())
                return null;

            switch (val.DataType)
            {
                case DataType.DataType_BLOB:
                    return ((BLOBValue)val).Data;
                case DataType.DataType_Boolean:
                    return ((BooleanValue)val).Boolean;
                case DataType.DataType_Byte:
                    return ((ByteValue)val).Byte;
                case DataType.DataType_CLOB:
                    return ((CLOBValue)val).Data;
                case DataType.DataType_DateTime:
                    return ((DateTimeValue)val).DateTime;
                case DataType.DataType_Decimal:
                    return ((DecimalValue)val).Decimal;
                case DataType.DataType_Double:
                    return ((DoubleValue)val).Double;
                case DataType.DataType_Int16:
                    return ((Int16Value)val).Int16;
                case DataType.DataType_Int32:
                    return ((Int32Value)val).Int32;
                case DataType.DataType_Int64:
                    return ((Int64Value)val).Int64;
                case DataType.DataType_Single:
                    return ((SingleValue)val).Single;
                case DataType.DataType_String:
                    return ((StringValue)val).String;
                default:
                    return null;
            }
        }
コード例 #8
0
        public PropertyValueSnak(PropertyId propertyId, DataValue value)
        {
            if (propertyId == null || value == null)
            {
                throw new ArgumentNullException("The property id and value must not be null");
            }

            PropertyId = propertyId;
            Value = value;
        }
コード例 #9
0
ファイル: DeltaAggregate.cs プロジェクト: yuriik83/UA-.NET
        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            int numGood = 0;
            int numBad = 0;
            DataValue firstGoodDv = null;
            DataValue lastGoodDv = null;
            DataValue lastDv = null;
            bool uncertainDataSubNormal = false;
            double delta = double.NaN;
            
            foreach (DataValue dv in bucket.Values)
            {
                if (state.RawValueIsGood(dv))
                {
                    if (firstGoodDv == null)
                    {
                        firstGoodDv = dv;
                    }
                    lastGoodDv = dv;                   
                    numGood++;
                }
                else
                {
                    // check for non-good value occuring before first good value
                    if (firstGoodDv == null)
                        uncertainDataSubNormal = true;
                    numBad++;
                }
                lastDv = dv;
            }
            if (firstGoodDv != null)
            {
                double fv = Convert.ToDouble(firstGoodDv.Value);
                double lv = Convert.ToDouble(lastGoodDv.Value);
                delta = lv - fv;
            }
            
            // check for non-good value occuring after latest good value
            if (!uncertainDataSubNormal && lastGoodDv != null && lastGoodDv.SourceTimestamp < lastDv.SourceTimestamp)
                uncertainDataSubNormal = true;

            StatusCode code = (uncertainDataSubNormal)
                ? StatusCodes.UncertainDataSubNormal
                : (numGood > 0) ? StatusCodes.Good : StatusCodes.BadNoData;
            DataValue retval = new DataValue { SourceTimestamp = bucket.From };
            if (!double.IsNaN(delta))
                retval.Value = delta;
            code.AggregateBits = AggregateBits.Calculated;
            if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
            retval.StatusCode = code;
            return retval;
        }
コード例 #10
0
        protected abstract bool Comparison(DataValue value1, DataValue value2); // true if keep value1.

        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            int numGood = 0;
            int numBad = 0;
            DataValue valueToKeep = new DataValue() { SourceTimestamp = bucket.From, StatusCode = StatusCodes.BadNoData };
            bool moreData = false;
            bool hasGoodData = false;
            foreach (DataValue dv in bucket.Values)
            {
                if (state.RawValueIsGood(dv))
                {
                    hasGoodData = true;
                    if (valueToKeep.StatusCode == StatusCodes.BadNoData)
                    {
                        valueToKeep = dv;
                    }
                    else
                    {
                        moreData = valueToKeep == dv;
                        if (Comparison(dv, valueToKeep))
                        {
                            valueToKeep = dv;
                        }
                    }
                    numGood++;
                }
                else
                {
                    numBad++;
                    if (!hasGoodData)
                        valueToKeep = dv;
                }
            }
            DataValue retval = valueToKeep.StatusCode == StatusCodes.BadNoData ? valueToKeep : (DataValue)valueToKeep.Clone();
            if (hasGoodData)
            {
                StatusCode code = StatusCodes.Good;
                code = ComputeStatus(context, numGood, numBad, bucket).Code;
                code.AggregateBits = moreData ? AggregateBits.ExtraData : AggregateBits.Raw;
                if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
                retval.StatusCode = code;
            } // numGood = 0, hasGoodData = false beyond this point, i.e., no good data
            else if(numBad > 0)
            {
                retval.Value = null;
                retval.StatusCode = StatusCodes.Bad;
                retval.StatusCode = retval.StatusCode.SetAggregateBits(AggregateBits.Raw);
            }
            return retval;
        }
コード例 #11
0
 public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
 {
     DataValue retval = new DataValue { SourceTimestamp = bucket.From };
     StatusCode code = StatusCodes.BadNoData;
     DataValue boundValue = context.IsReverseAggregation ? bucket.LateBound.Value : bucket.EarlyBound.Value;
     if (boundValue != null)
     {
         code = bucket.EarlyBound.Value.StatusCode.Code;
         code.AggregateBits = bucket.EarlyBound.Value.StatusCode.AggregateBits;
         retval.Value = Convert.ToDouble(bucket.EarlyBound.Value.Value, CultureInfo.InvariantCulture);
     }
     if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
     retval.StatusCode = code;
     return retval;
 }
コード例 #12
0
        /// <summary>
        /// Builds this LookupBox and returns the panel.
        /// </summary>
        public WebControl BuildLookupBoxPanel()
        {
            var val = new DataValue<string>();
            var postBack = PostBack.CreateFull( id: postBackId, actionGetter: () => new PostBackAction( handler( val.Value ) ) );

            var textBox = FormItem.Create(
                "",
                new EwfTextBox( "", postBack: postBack ) { Width = new Unit( pixelWidth ) },
                validationGetter: control => new EwfValidation( ( pbv, validator ) => val.Value = control.GetPostBackValue( pbv ), postBack ) );
            textBox.Control.SetWatermarkText( defaultText );
            if( autoCompleteService != null )
                textBox.Control.SetupAutoComplete( autoCompleteService, AutoCompleteOption.PostBackOnItemSelect );

            return new Block( textBox.ToControl() ) { CssClass = "ewfLookupBox" };
        }
コード例 #13
0
        private Box test1( DataModification dm, Action<string> setValue )
        {
            var box = new EwfTextBox( "" );
            box.SetupAutoComplete( TestService.GetInfo(), AutoCompleteOption.NoPostBack );

            var dv = new DataValue<string>();
            dm.AddTopValidationMethod( ( pbvd, validator ) => dv.Value = box.GetPostBackValue( pbvd ) );
            dm.AddModificationMethod( () => setValue( dv.Value ) );

            return
                new Box(
                    "Autofill behavior. Typing more than 3 characters should bring up autofill options from a web service. " +
                    "Selecting an item or changing the text will no cause a post-back. This value show appear when submitting the page's submit button.",
                    box.ToSingleElementArray() );
        }
コード例 #14
0
ファイル: RangeAggregate.cs プロジェクト: yuriik83/UA-.NET
        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            int numGood = 0;
            int numBad = 0;
            double minV = double.MaxValue;
            double maxV = double.MinValue;
            bool uncertainDataSubNormal = false;
            double range = double.NaN;

            foreach (DataValue dv in bucket.Values)
            {
                if (state.RawValueIsGood(dv))
                {
                    double v = Convert.ToDouble(dv.Value);
                    if (minV > v)
                    {
                        minV = v;
                    }
                    if (maxV < v)
                    {
                        maxV = v;
                    }
                    numGood++;
                }
                else
                {
                    uncertainDataSubNormal = true;
                    numBad++;
                }
            }
            if (minV != double.MaxValue && maxV != double.MinValue)
            {
                range = Math.Abs(maxV - minV);
            }

            StatusCode code = (uncertainDataSubNormal)
                ? StatusCodes.UncertainDataSubNormal
                : StatusCodes.Good;
            if (numGood + numBad == 0) code = StatusCodes.BadNoData;
            DataValue retval = new DataValue { SourceTimestamp = bucket.From };
            if (!double.IsNaN(range))
                retval.Value = range;
            code.AggregateBits = AggregateBits.Calculated;
            if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
            retval.StatusCode = code;
            return retval;
        }
コード例 #15
0
 public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
 {
     StatusCode returnCode = StatusCodes.BadNoData;
     foreach(DataValue dv in bucket.Values)
     {
         if (returnCode == StatusCodes.BadNoData)
         {
             returnCode = dv.StatusCode;
         }
         else
         {
             // StatusCodes.Bad = 0x80000000
             // StatusCodes.Uncertain = 0x40000000
             // StatusCodes.Good = 0x00000000
             uint code = dv.StatusCode.Code >> 28;   // 7 Hexadecimal digits = 28 binary digits.
             switch (code)
             {
                 case 8: // 8 is maximum
                     returnCode = StatusCodes.Bad;
                     break;
                 case 4:
                     if(StatusCode.IsNotBad(returnCode))
                         returnCode = StatusCodes.Uncertain;
                     break;
                 case 0: // 0 is minimum 
                     break;
                 default:
                     Debug.Assert(true, "should not touch this line");
                     throw new Exception(String.Format("Unknown error in WorstQuality aggregate calculation, code = {0}", dv.StatusCode));
             }
         }
     }
     DataValue retVal = new DataValue() { SourceTimestamp = bucket.From };
     if (returnCode != StatusCodes.BadNoData)
     {
         retVal.Value = returnCode;
         StatusCode status = StatusCodes.Good;
         status.AggregateBits |= AggregateBits.Calculated;
         if (bucket.Incomplete) status.AggregateBits |= AggregateBits.Partial;
         retVal.StatusCode = status;
     }
     else
     {
         retVal.StatusCode = returnCode;
     }
     return retVal;
 }
コード例 #16
0
        protected override void loadData()
        {
            BasicPage.Instance.Body.Attributes[ "class" ] = CssElementCreator.SelectUserPageBodyCssClass;

            ph.AddControlsReturnThis( new PageName() );

            if( ConfigurationStatics.IsLiveInstallation ) {
                ph.AddControlsReturnThis(
                    new Paragraph(
                        new Strong( "Warning:" ),
                        " Do not impersonate a user without permission. Your actions will be attributed to the user you are impersonating, not to you.".GetLiteralControl() ) );
            }

            var pb = PostBack.CreateFull(
                actionGetter: () => new PostBackAction( new ExternalResourceInfo( info.ReturnUrl.Any() ? info.ReturnUrl : NetTools.HomeUrl ) ) );

            DataValue<User> user = new DataValue<User>();
            ph.AddControlsReturnThis(
                FormItem.Create(
                    "User's email address (leave blank for anonymous)",
                    new EwfTextBox( "" ),
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         var errorHandler = new ValidationErrorHandler( "user" );
                                                         var emailAddress = validator.GetEmailAddress( errorHandler, control.GetPostBackValue( pbv ), true );
                                                         if( errorHandler.LastResult != ErrorCondition.NoError )
                                                             return;
                                                         if( !emailAddress.Any() ) {
                                                             user.Value = null;
                                                             return;
                                                         }
                                                         user.Value = UserManagementStatics.GetUser( emailAddress );
                                                         if( user.Value == null )
                                                             validator.NoteErrorAndAddMessage( "The email address you entered does not match a user." );
                                                     },
                                                     pb ) ).ToControl(),
                new Paragraph(
                    new PostBackButton(
                        pb,
                        new ButtonActionControlStyle(
                            AppRequestState.Instance.ImpersonatorExists ? "Change User" : "Begin Impersonation",
                            buttonSize: ButtonActionControlStyle.ButtonSize.Large ) ) ) );

            pb.AddModificationMethod( () => UserImpersonationStatics.BeginImpersonation( user.Value ) );
        }
コード例 #17
0
        protected override void loadData()
        {
            var pb = PostBack.CreateFull( actionGetter: () => new PostBackAction( new ExternalResourceInfo( es.info.ReturnAndDestinationUrl ) ) );
            var fib = FormItemBlock.CreateFormItemTable();

            newPassword = new DataValue<string>();
            fib.AddFormItems(
                FormItem.Create(
                    "New password",
                    new EwfTextBox( "", masksCharacters: true ),
                    validationGetter: control => new EwfValidation( ( pbv, v ) => newPassword.Value = control.GetPostBackValue( pbv ), pb ) ) );
            var newPasswordConfirm = new DataValue<string>();
            fib.AddFormItems(
                FormItem.Create(
                    "Re-type new password",
                    new EwfTextBox( "", masksCharacters: true ),
                    validationGetter: control => new EwfValidation( ( pbv, v ) => newPasswordConfirm.Value = control.GetPostBackValue( pbv ), pb ) ) );
            pb.AddTopValidationMethod( ( pbv, validator ) => FormsAuthStatics.ValidatePassword( validator, newPassword, newPasswordConfirm ) );

            ph.AddControlsReturnThis( fib );
            EwfUiStatics.SetContentFootActions( new ActionButtonSetup( "Change Password", new PostBackButton( pb ) ) );

            pb.AddModificationMethod( modifyData );
        }
コード例 #18
0
ファイル: CountAggregate.cs プロジェクト: yuriik83/UA-.NET
 public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
 {
     int numGood = 0;
     int numBad = 0;
     foreach (DataValue v in bucket.Values)
     {
         if (state.RawValueIsGood(v))
         {
             numGood += 1;
         }
         else
         {
             numBad += 1;
         }
     }
     StatusCode code = StatusCodes.Good;
     DataValue retval = new DataValue { SourceTimestamp = bucket.From };
     retval.Value = numGood;
     code = ComputeStatus(context, numGood, numBad, bucket).Code;
     code.AggregateBits = AggregateBits.Calculated;
     if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
     retval.StatusCode = code;
     return retval;
 }
コード例 #19
0
        private Model.Data.DataTable GridToExecl(List <TemplateStock> tempStocks, out List <DataHeader> cellRanges)
        {
            TSGrid hsGrid      = _gridConfig.GetGid(GridStock);
            var    gridColumns = hsGrid.Columns;

            var sheetConfig = ConfigManager.Instance.GetImportConfig().GetSheet("stocktemplate");

            cellRanges = sheetConfig.Columns;
            var sheetColumns = ConfigManager.Instance.GetImportConfig().GetColumnHeader(cellRanges);
            Dictionary <string, DataColumnHeader> colHeadMap = new Dictionary <string, DataColumnHeader>();

            foreach (var column in sheetColumns)
            {
                //colHeadMap.Add(column.Name, column);
                var gridColumn = gridColumns.Find(p => p.Text.Equals(column.Name));
                if (gridColumn != null)
                {
                    if (!colHeadMap.ContainsKey(gridColumn.Name))
                    {
                        colHeadMap.Add(gridColumn.Name, column);
                    }
                }
            }

            //实体类标签名与Excel DataTable DataRow.Columns中列索引映射表
            Dictionary <string, int> excelNameColumnIndexMap = new Dictionary <string, int>();

            for (int i = 0, count = sheetColumns.Count; i < count; i++)
            {
                if (!excelNameColumnIndexMap.ContainsKey(sheetColumns[i].Name))
                {
                    excelNameColumnIndexMap.Add(sheetColumns[i].Name, i);
                }
            }

            Dictionary <string, int> fieldNameColumnIndexMap = new Dictionary <string, int>();

            for (int i = 0, count = gridColumns.Count; i < count; i++)
            {
                var column = gridColumns[i];
                int index  = sheetColumns.FindIndex(p => p.Name.Equals(column.Text));
                if (index >= 0)
                {
                    if (!fieldNameColumnIndexMap.ContainsKey(column.Name))
                    {
                        fieldNameColumnIndexMap.Add(column.Name, index);
                    }
                }
            }

            Model.Data.DataTable table = new Model.Data.DataTable
            {
                ColumnIndex = new Dictionary <string, int>(),
                Rows        = new List <Model.Data.DataRow>()
            };

            table.ColumnIndex = excelNameColumnIndexMap;

            var attFieldMap = GridViewBindingHelper.GetPropertyBinding(typeof(TemplateStock));

            foreach (var tempStock in tempStocks)
            {
                Model.Data.DataRow dataRow = new Model.Data.DataRow
                {
                    Columns = new List <DataValue>(table.ColumnIndex.Count)
                };

                foreach (var kv in attFieldMap)
                {
                    if (!attFieldMap.ContainsKey(kv.Key) || !fieldNameColumnIndexMap.ContainsKey(kv.Key))
                    {
                        continue;
                    }

                    string fieldName = attFieldMap[kv.Key];
                    int    valIndex  = fieldNameColumnIndexMap[kv.Key];

                    var field = tempStock.GetType().GetProperty(fieldName);
                    if (field == null)
                    {
                        continue;
                    }

                    Model.Data.DataValue dataValue = new DataValue();
                    if (colHeadMap.ContainsKey(kv.Key))
                    {
                        dataValue.Type = colHeadMap[kv.Key].Type;
                    }

                    dataValue.Value = field.GetValue(tempStock, null);

                    //dataRow.Columns[valIndex] = dataValue;
                    dataRow.Columns.Insert(valIndex, dataValue);
                }

                table.Rows.Add(dataRow);
            }

            return(table);
        }
コード例 #20
0
        public void UpdateProcessedData(DataValue rawValue, AggregateState state)
        {
            // step 1: compute new TimeSlice instances to enqueue, until we reach the one the
            // rawValue belongs in or we've reached the one that goes to the EndTime. Ensure
            // that the raw value is added to the last one created.
            TimeSlice tmpTS = null;

            if (m_pending == null)
            {
                m_pending = new Queue <TimeSlice>();
            }
            if (m_latest == null)
            {
                tmpTS = TimeSlice.CreateInitial(StartTime, EndTime, ProcessingInterval);
                if (tmpTS != null)
                {
                    m_pending.Enqueue(tmpTS);
                    m_latest = tmpTS;
                }
            }
            else
            {
                tmpTS = m_latest;
            }
            DateTime latestTime = (StartTime > EndTime) ? StartTime : EndTime;

            while ((tmpTS != null) && (state.HasTerminated || !tmpTS.AcceptValue(rawValue)))
            {
                tmpTS = TimeSlice.CreateNext(latestTime, ProcessingInterval, tmpTS);
                if (tmpTS != null)
                {
                    m_pending.Enqueue(tmpTS);
                    m_latest = tmpTS;
                }
            }

            // step 2: apply the aggregator to the head of the queue to see if we can convert
            // it into a processed point. If so, dequeue it and add the processed value to the
            // m_released list. Keep doing it until one of the TimeSlices returns null or we
            // run out of enqueued TimeSlices (should only happen on termination).
            if (m_released == null)
            {
                m_released = new List <DataValue>();
            }
            foreach (TimeSlice b in m_pending)
            {
                UpdateBoundingValues(b, state);
            }
            bool active = true;

            while ((m_pending.Count > 0) && active)
            {
                TimeSlice top      = m_pending.Peek();
                DataValue computed = null;
                if (!WaitForMoreData(top, state))
                {
                    computed = Compute(this, top, state);
                }
                if (computed != null)
                {
                    m_released.Add(computed);
                    m_pending.Dequeue();
                }
                else
                {
                    active = false;
                }
            }
        }
コード例 #21
0
 protected abstract bool RightStatusCode(DataValue dv);
コード例 #22
0
        /// <summary>
        /// Adds index ranges to the collection.
        /// </summary>
        private void AddWriteValues(
            Node node,
            WriteValueCollection nodesToWrite,
            params uint[] attributeIds)
        {
            if (attributeIds != null)
            {
                for (int ii = 0; ii < attributeIds.Length; ii++)
                {
                    WriteValue nodeToWrite = new WriteValue();

                    nodeToWrite.NodeId      = node.NodeId;
                    nodeToWrite.AttributeId = attributeIds[ii];

                    DataValue value = new DataValue();

                    ServiceResult result = node.Read(
                        null,
                        attributeIds[ii],
                        value);

                    value.StatusCode      = StatusCodes.Good;
                    value.ServerTimestamp = DateTime.MinValue;
                    value.SourceTimestamp = DateTime.MinValue;

                    if (ServiceResult.IsBad(result))
                    {
                        value.Value = null;
                    }

                    nodeToWrite.Value  = value;
                    nodeToWrite.Handle = node;

                    nodesToWrite.Add(nodeToWrite);

                    Array array = value.Value as Array;

                    if (array != null)
                    {
                        NumericRange range = new NumericRange(0, 1);

                        object subarray = array;
                        range.ApplyRange(ref subarray);

                        nodeToWrite = new WriteValue();

                        nodeToWrite.Value                 = new DataValue();
                        nodeToWrite.Value.Value           = subarray;
                        nodeToWrite.Value.StatusCode      = StatusCodes.Good;
                        nodeToWrite.Value.ServerTimestamp = DateTime.MinValue;
                        nodeToWrite.Value.SourceTimestamp = DateTime.MinValue;
                        nodeToWrite.NodeId                = node.NodeId;
                        nodeToWrite.AttributeId           = attributeIds[ii];
                        nodeToWrite.IndexRange            = "0";
                        nodeToWrite.Handle                = node;

                        nodesToWrite.Add(nodeToWrite);
                    }

                    nodeToWrite = new WriteValue();

                    nodeToWrite.Value                 = new DataValue();
                    nodeToWrite.Value.Value           = value.Value;
                    nodeToWrite.Value.StatusCode      = StatusCodes.Uncertain;
                    nodeToWrite.Value.ServerTimestamp = DateTime.MinValue;
                    nodeToWrite.Value.SourceTimestamp = DateTime.MinValue;
                    nodeToWrite.NodeId                = node.NodeId;
                    nodeToWrite.AttributeId           = attributeIds[ii];
                    nodeToWrite.Handle                = node;

                    nodesToWrite.Add(nodeToWrite);

                    nodeToWrite = new WriteValue();

                    nodeToWrite.Value                 = new DataValue();
                    nodeToWrite.Value.Value           = value.Value;
                    nodeToWrite.Value.StatusCode      = StatusCodes.Good;
                    nodeToWrite.Value.ServerTimestamp = DateTime.UtcNow;
                    nodeToWrite.Value.SourceTimestamp = DateTime.MinValue;
                    nodeToWrite.NodeId                = node.NodeId;
                    nodeToWrite.AttributeId           = attributeIds[ii];
                    nodeToWrite.Handle                = node;

                    nodesToWrite.Add(nodeToWrite);

                    nodeToWrite = new WriteValue();

                    nodeToWrite.Value                 = new DataValue();
                    nodeToWrite.Value.Value           = value.Value;
                    nodeToWrite.Value.StatusCode      = StatusCodes.Good;
                    nodeToWrite.Value.ServerTimestamp = DateTime.MinValue;
                    nodeToWrite.Value.SourceTimestamp = DateTime.UtcNow;
                    nodeToWrite.NodeId                = node.NodeId;
                    nodeToWrite.AttributeId           = attributeIds[ii];
                    nodeToWrite.Handle                = node;

                    nodesToWrite.Add(nodeToWrite);
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Calculates the Count aggregate for the timeslice.
        /// </summary>
        protected DataValue ComputeNumberOfTransitions(TimeSlice slice)
        {
            // get the values in the slice.
            List <DataValue> values = GetValues(slice);

            // check for empty slice.
            if (values == null)
            {
                return(GetNoDataValue(slice));
            }

            // determine whether a transition occurs at the StartTime
            double lastValue = Double.NaN;

            if (slice.EarlyBound != null)
            {
                if (StatusCode.IsGood(slice.EarlyBound.Value.StatusCode))
                {
                    try
                    {
                        lastValue = CastToDouble(slice.EarlyBound.Value);
                    }
                    catch (Exception)
                    {
                        lastValue = Double.NaN;
                    }
                }
            }

            // count the transitions.
            int count = 0;

            for (int ii = 0; ii < values.Count; ii++)
            {
                if (!IsGood(values[ii]))
                {
                    continue;
                }

                double nextValue = 0;

                try
                {
                    nextValue = CastToDouble(values[ii]);
                }
                catch (Exception)
                {
                    continue;
                }

                if (!Double.IsNaN(lastValue))
                {
                    if (lastValue != nextValue)
                    {
                        count++;
                    }
                }

                lastValue = nextValue;
            }

            // set the timestamp and status.
            DataValue value = new DataValue();

            value.WrappedValue    = new Variant(count, TypeInfo.Scalars.Int32);
            value.SourceTimestamp = GetTimestamp(slice);
            value.ServerTimestamp = GetTimestamp(slice);
            value.StatusCode      = value.StatusCode.SetAggregateBits(AggregateBits.Calculated);
            value.StatusCode      = GetValueBasedStatusCode(slice, values, value.StatusCode);

            // return result.
            return(value);
        }
コード例 #24
0
        /// <summary>
        /// Updates the history.
        /// </summary>
        public uint UpdateHistory(SystemContext context, DataValue value, PerformUpdateType performUpdateType)
        {
            var replaced = false;

            if (performUpdateType == PerformUpdateType.Remove)
            {
                return(StatusCodes.BadNotSupported);
            }

            if (StatusCode.IsNotBad(value.StatusCode))
            {
                var typeInfo = value.WrappedValue.TypeInfo;

                if (typeInfo == null)
                {
                    typeInfo = TypeInfo.Construct(value.Value);
                }

                if (typeInfo == null || typeInfo.BuiltInType != ArchiveItem.DataType || typeInfo.ValueRank != ValueRanks.Scalar)
                {
                    return(StatusCodes.BadTypeMismatch);
                }
            }

            var filter = string.Format(System.Globalization.CultureInfo.InvariantCulture, "SourceTimestamp = #{0}#", value.SourceTimestamp);

            var view = new DataView(
                ArchiveItem.DataSet.Tables[0],
                filter,
                null,
                DataViewRowState.CurrentRows);

            DataRow row = null;

            var ii = 0;

            for (; ii < view.Count;)
            {
                if (performUpdateType == PerformUpdateType.Insert)
                {
                    return(StatusCodes.BadEntryExists);
                }

                // add record indicating it was replaced.
                var modifiedRow = ArchiveItem.DataSet.Tables[1].NewRow();

                modifiedRow[0] = view[ii].Row[0];
                modifiedRow[1] = view[ii].Row[1];
                modifiedRow[2] = view[ii].Row[2];
                modifiedRow[3] = view[ii].Row[3];
                modifiedRow[4] = view[ii].Row[4];
                modifiedRow[5] = HistoryUpdateType.Replace;
                modifiedRow[6] = GetModificationInfo(context, HistoryUpdateType.Replace);

                ArchiveItem.DataSet.Tables[1].Rows.Add(modifiedRow);

                replaced = true;
                row      = view[ii].Row;
                break;
            }

            // add record indicating it was inserted.
            if (!replaced)
            {
                if (performUpdateType == PerformUpdateType.Replace)
                {
                    return(StatusCodes.BadNoEntryExists);
                }

                var modifiedRow = ArchiveItem.DataSet.Tables[1].NewRow();

                modifiedRow[0] = value.SourceTimestamp;
                modifiedRow[1] = value.ServerTimestamp;
                modifiedRow[2] = value;

                if (value.WrappedValue.TypeInfo != null)
                {
                    modifiedRow[3] = value.WrappedValue.TypeInfo.BuiltInType;
                    modifiedRow[4] = value.WrappedValue.TypeInfo.ValueRank;
                }
                else
                {
                    modifiedRow[3] = BuiltInType.Variant;
                    modifiedRow[4] = ValueRanks.Scalar;
                }

                modifiedRow[5] = HistoryUpdateType.Insert;
                modifiedRow[6] = GetModificationInfo(context, HistoryUpdateType.Insert);

                ArchiveItem.DataSet.Tables[1].Rows.Add(modifiedRow);

                row = ArchiveItem.DataSet.Tables[0].NewRow();
            }

            // add/update new record.
            row[0] = value.SourceTimestamp;
            row[1] = value.ServerTimestamp;
            row[2] = value;

            if (value.WrappedValue.TypeInfo != null)
            {
                row[3] = value.WrappedValue.TypeInfo.BuiltInType;
                row[4] = value.WrappedValue.TypeInfo.ValueRank;
            }
            else
            {
                row[3] = BuiltInType.Variant;
                row[4] = ValueRanks.Scalar;
            }

            if (!replaced)
            {
                ArchiveItem.DataSet.Tables[0].Rows.Add(row);
            }

            // accept all changes.
            ArchiveItem.DataSet.AcceptChanges();

            return(StatusCodes.Good);
        }
コード例 #25
0
        /// <summary>
        /// Reads an attribute for the node.
        /// </summary>
        protected virtual ServiceResult ReadAttribute(IOperationContext context, uint attributeId, DataValue value)
        {
            IList<string> locales = null;

            if (context != null)
            {
                locales = context.PreferredLocales;
            }

            switch (attributeId)
            {
                case Attributes.NodeId:
                {
                    value.Value = NodeId;
                    break;
                }

                case Attributes.NodeClass:
                {
                    value.Value = NodeClass;
                    break;
                }

                case Attributes.BrowseName:
                {
                    value.Value = BrowseName;
                    break;
                }

                case Attributes.DisplayName:
                {
                    value.Value = ResourceManager.Translate(locales, DisplayName);
                    break;
                }

                case Attributes.Description:
                {
                    value.Value = ResourceManager.Translate(locales, DisplayName);
                    break;
                }

                case Attributes.WriteMask:
                {
                    value.Value = (uint)WriteMask;
                    break;
                }

                case Attributes.UserWriteMask:
                {
                    value.Value = (uint)UserWriteMask;
                    break;
                }

                default:
                {
                    return StatusCodes.BadAttributeIdInvalid;
                }
            }

            return ServiceResult.Good;
        }
コード例 #26
0
ファイル: Dummy.cs プロジェクト: nsuchold/Mediator.Net
            public override VTQ Get()
            {
                Match match = rgxSinus.Match(func);

                if (match.Success)
                {
                    Duration period    = Duration.Parse(match.Groups[1].Value);
                    double   amplitude = double.Parse(match.Groups[3].Value);
                    double   offset    = double.Parse(match.Groups[4].Value);
                    double   periodMS  = period.TotalMilliseconds;
                    long     now       = Timestamp.Now.JavaTicks;
                    double   x         = (now - BaseDate) % periodMS;
                    double   radian    = (x / periodMS) * 2.0 * Math.PI;
                    double   v         = amplitude * Math.Sin(radian) + offset;
                    return(new VTQ(Timestamp.Now.TruncateMilliseconds(), Quality.Good, DataValue.FromFloat((float)v)));
                }
                else
                {
                    return(new VTQ(Timestamp.Now.TruncateMilliseconds(), Quality.Bad, DataValue.FromFloat(0)));
                }
            }
コード例 #27
0
ファイル: Class1.cs プロジェクト: AVerutin/OPCClient
        /// <summary>
        /// Получить значение тега по его адресу
        /// </summary>
        /// <param name="nodeID">Адрес тега</param>
        /// <returns>Значение тега</returns>
        public DataValue ReadValue(string nodeID)
        {
            DataValue value = _session.ReadValue(nodeID);

            return(value);
        }
コード例 #28
0
        private void ForceUpdateObjectAttribute(SimulationEvent e)
        {
            string objectId      = ((StringValue)e["ObjectID"]).value;
            string attributeName = ((StringValue)e["AttributeName"]).value;

            if (!objectProxies.ContainsKey(objectId))
            {
                return;
            }
            try
            {
                if (!objectProxies[objectId].GetKeys().Contains(attributeName))
                {
                    return;
                }
                if (!objectProxies[objectId][attributeName].IsOwner())
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                return;
            }

            DataValue attributeValue = e["AttributeValue"];

            if (attributeValue.dataType != "WrapperType")
            {
                return;
            }
            attributeValue = ((WrapperValue)attributeValue).value;
            SimulationObjectProxy obj = null;

            //depending on the attribute, you might have specific functionality
            switch (attributeName)
            {
            case "FuelCapacity":
                ChangeObjectFuelCapacity(attributeValue as DoubleValue, objectId);
                break;

            case "FuelAmount":
                ChangeObjectFuelAmount(attributeValue as DoubleValue, objectId);
                break;

            case "FuelConsumptionRate":
                ChangeObjectFuelRate(attributeValue as DoubleValue, objectId);
                break;

            case "FuelDepletionState":
                ChangeObjectFuelDepleteState(attributeValue as StringValue, objectId);
                break;

            default:
                break;
            }

            //try
            //{
            //    obj[attributeName].SetDataValue(attributeValue);
            //}
            //catch (Exception ex)
            //{
            //    return;
            //}

            attributeValue = null;
            obj            = null;
        }
コード例 #29
0
        private void TimeTick(SimulationEvent e)
        {
            int       oldTime = time;
            DataValue dv      = null;


            dv   = e["Time"];
            time = ((IntegerValue)dv).value;

            double dTime = ((double)(time - oldTime)) / 1000;
            SimulationObjectProxy obProx = null;

            double throttle            = 0;
            double fuelAmount          = 0;
            double fuelConsumptionRate = 0;
            bool   dockedToParent      = false;

            foreach (string id in objectProxies.Keys)
            {
                obProx = objectProxies[id];

                dv = obProx["FuelConsumptionRate"].GetDataValue();
                fuelConsumptionRate = ((DoubleValue)dv).value;
                if (fuelConsumptionRate == 0)
                {
                    continue;
                }
                dv             = obProx["DockedToParent"].GetDataValue();
                dockedToParent = ((BooleanValue)dv).value;
                if (dockedToParent)
                {
                    continue;
                }



                dv         = obProx["FuelAmount"].GetDataValue();
                fuelAmount = ((DoubleValue)dv).value;
                if (fuelAmount == 0)
                {
                    continue;
                }

                dv         = obProx["Throttle"].GetDataValue();
                throttle   = ((DoubleValue)dv).value;
                dv         = obProx["FuelAmount"].GetDataValue();
                fuelAmount = ((DoubleValue)dv).value;


                fuelAmount -= dTime * throttle * fuelConsumptionRate;

                if (fuelAmount <= 0)
                {
                    fuelAmount = 0;
                    // Send state change
                    dv = obProx["FuelDepletionState"].GetDataValue();
                    if (dv != null)
                    {
                        SimulationEvent sc = SimulationEventFactory.BuildEvent(ref simModel, "StateChange");
                        ((StringValue)sc["ObjectID"]).value = id;
                        ((StringValue)sc["NewState"]).value = ((StringValue)dv).value;
                        ((IntegerValue)sc["Time"]).value    = time;
                        distClient.PutEvent(sc);
                    }
                }

                dv = obProx["FuelAmount"].GetDataValue();
                ((DoubleValue)dv).value = fuelAmount;
                obProx["FuelAmount"].SetDataValue(dv);
            }
        }
コード例 #30
0
            public void Run()
            {
                byte[]    bytes = new byte[255];
                Random    rand = new Random();
                int       create = 0, read = 0, write = 0, delete = 0;
                Stopwatch time = new Stopwatch();

                time.Start();

                try
                {
                    Dictionary <KeyInfo, DataValue> values = new Dictionary <KeyInfo, DataValue>(new KeyInfoEquality());
                    for (int i = 0; i < _recordCount; i++)
                    {
                        create++;
                        KeyInfo k = new KeyInfo();
                        rand.NextBytes(bytes);
                        DataValue v = new DataValue(k, bytes);

                        _data.Add(k, v);
                        Interlocked.Increment(ref RecordsCreated);
                        values.Add(k, v);
                    }

                    Dictionary <KeyInfo, DataValue> found = new Dictionary <KeyInfo, DataValue>(values, new KeyInfoEquality());
                    foreach (KeyValuePair <KeyInfo, DataValue> kv in _data)
                    {
                        read++;
                        found.Remove(kv.Key);
                    }

                    Assert.AreEqual(0, found.Count);

                    foreach (KeyValuePair <KeyInfo, DataValue> kv in values)
                    {
                        read++;
                        DataValue test;
                        Assert.IsTrue(_data.TryGetValue(kv.Key, out test));
                        Assert.AreEqual(kv.Key.UID, test.Key.UID);
                        Assert.AreEqual(kv.Value.Hash, test.Hash);
                        Assert.AreEqual(kv.Value.Bytes, test.Bytes);
                    }

                    foreach (KeyValuePair <KeyInfo, DataValue> kv in values)
                    {
                        bytes = kv.Value.Bytes;
                        Array.Reverse(bytes);

                        write++;
                        _data[kv.Key] = new DataValue(kv.Key, bytes);
                        read++;
                        Assert.AreEqual(bytes, _data[kv.Key].Bytes);
                    }

                    foreach (KeyInfo key in new List <KeyInfo>(values.Keys))
                    {
                        delete++;
                        Assert.IsTrue(_data.Remove(key));
                        values.Remove(key);
                    }
                }
                finally
                {
                    time.Stop();
                    Trace.TraceInformation("thread {0,3} complete ({1}c/{2}r/{3}w/{4}d) in {5:n0}ms",
                                           Thread.CurrentThread.ManagedThreadId,
                                           create, read, write, delete, time.ElapsedMilliseconds);
                }
            }
コード例 #31
0
        public IPersistable CreateRIFObject(ObjectType objectType, ref IntermediateFormatReader context)
        {
            IPersistable persistable = null;

            if (objectType == ObjectType.Null)
            {
                return(null);
            }
            IDOwner    parentIDOwner    = m_parentIDOwner;
            ReportItem parentReportItem = m_parentReportItem;

            switch (objectType)
            {
            case ObjectType.PageSection:
                persistable        = new PageSection(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.Line:
                persistable        = new Line(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.Rectangle:
                persistable        = new Rectangle(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.Image:
                persistable        = new Image(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.TextBox:
                persistable        = new TextBox(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.SubReport:
                persistable        = new SubReport(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.Grouping:
                persistable = new Grouping(ConstructionPhase.Deserializing);
                break;

            case ObjectType.Sorting:
                persistable = new Sorting(ConstructionPhase.Deserializing);
                break;

            case ObjectType.ReportItemCollection:
                persistable = new ReportItemCollection();
                break;

            case ObjectType.ReportItemIndexer:
                persistable = default(ReportItemIndexer);
                break;

            case ObjectType.Style:
                persistable = new Style(ConstructionPhase.Deserializing);
                break;

            case ObjectType.AttributeInfo:
                persistable = new AttributeInfo();
                break;

            case ObjectType.Visibility:
                persistable = new Visibility();
                break;

            case ObjectType.ExpressionInfo:
                persistable = new ExpressionInfo();
                break;

            case ObjectType.ExpressionInfoTypeValuePair:
                persistable = new ExpressionInfoTypeValuePair();
                break;

            case ObjectType.DataAggregateInfo:
                persistable = new DataAggregateInfo();
                break;

            case ObjectType.RunningValueInfo:
                persistable = new RunningValueInfo();
                break;

            case ObjectType.Filter:
                persistable = new Filter();
                break;

            case ObjectType.DataSource:
                persistable = new DataSource();
                break;

            case ObjectType.DataSet:
                persistable = new DataSet();
                break;

            case ObjectType.ReportQuery:
                persistable = new ReportQuery();
                break;

            case ObjectType.Field:
                persistable = new Field();
                break;

            case ObjectType.ParameterValue:
                persistable = new ParameterValue();
                break;

            case ObjectType.ReportSnapshot:
                persistable = new ReportSnapshot();
                break;

            case ObjectType.DocumentMapNode:
                persistable = new DocumentMapNode();
                break;

            case ObjectType.DocumentMapBeginContainer:
                persistable = DocumentMapBeginContainer.Instance;
                break;

            case ObjectType.DocumentMapEndContainer:
                persistable = DocumentMapEndContainer.Instance;
                break;

            case ObjectType.ReportInstance:
                persistable = new ReportInstance();
                break;

            case ObjectType.ParameterInfo:
                persistable = new ParameterInfo();
                break;

            case ObjectType.ValidValue:
                persistable = new ValidValue();
                break;

            case ObjectType.ParameterDataSource:
                persistable = new ParameterDataSource();
                break;

            case ObjectType.ParameterDef:
                persistable = new ParameterDef();
                break;

            case ObjectType.ProcessingMessage:
                persistable = new ProcessingMessage();
                break;

            case ObjectType.CodeClass:
                persistable = default(CodeClass);
                break;

            case ObjectType.Action:
                persistable = new Action();
                break;

            case ObjectType.RenderingPagesRanges:
                persistable = default(RenderingPagesRanges);
                break;

            case ObjectType.IntermediateFormatVersion:
                persistable = new IntermediateFormatVersion();
                break;

            case ObjectType.ImageInfo:
                persistable = new ImageInfo();
                break;

            case ObjectType.ActionItem:
                persistable = new ActionItem();
                break;

            case ObjectType.DataValue:
                persistable = new DataValue();
                break;

            case ObjectType.CustomReportItem:
                persistable        = new CustomReportItem(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.SortFilterEventInfoMap:
                persistable = new SortFilterEventInfoMap();
                break;

            case ObjectType.SortFilterEventInfo:
                persistable = new SortFilterEventInfo();
                break;

            case ObjectType.EndUserSort:
                persistable = new EndUserSort();
                break;

            case ObjectType.ScopeLookupTable:
                persistable = new ScopeLookupTable();
                break;

            case ObjectType.Tablix:
                persistable        = new Tablix(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.TablixHeader:
                persistable = new TablixHeader();
                break;

            case ObjectType.TablixMember:
                persistable = new TablixMember();
                break;

            case ObjectType.TablixColumn:
                persistable = new TablixColumn();
                break;

            case ObjectType.TablixRow:
                persistable = new TablixRow();
                break;

            case ObjectType.TablixCornerCell:
                persistable = new TablixCornerCell();
                break;

            case ObjectType.TablixCell:
                persistable = new TablixCell();
                break;

            case ObjectType.Chart:
                persistable        = new Chart(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.ChartMember:
                persistable = new ChartMember();
                break;

            case ObjectType.ChartSeries:
                persistable = new ChartSeries();
                break;

            case ObjectType.ChartDataPoint:
                persistable = new ChartDataPoint();
                break;

            case ObjectType.ChartDataPointValues:
                persistable = new ChartDataPointValues();
                break;

            case ObjectType.ChartArea:
                persistable = new ChartArea();
                break;

            case ObjectType.ChartLegend:
                persistable = new ChartLegend();
                break;

            case ObjectType.ChartLegendTitle:
                persistable = new ChartLegendTitle();
                break;

            case ObjectType.ChartAxis:
                persistable = new ChartAxis();
                break;

            case ObjectType.ThreeDProperties:
                persistable = new ChartThreeDProperties();
                break;

            case ObjectType.ChartDataLabel:
                persistable = new ChartDataLabel();
                break;

            case ObjectType.ChartMarker:
                persistable = new ChartMarker();
                break;

            case ObjectType.ChartTitle:
                persistable = new ChartTitle();
                break;

            case ObjectType.ChartAxisScaleBreak:
                persistable = new ChartAxisScaleBreak();
                break;

            case ObjectType.ChartDerivedSeries:
                persistable = new ChartDerivedSeries();
                break;

            case ObjectType.ChartBorderSkin:
                persistable = new ChartBorderSkin();
                break;

            case ObjectType.ChartNoDataMessage:
                persistable = new ChartNoDataMessage();
                break;

            case ObjectType.ChartItemInLegend:
                persistable = new ChartItemInLegend();
                break;

            case ObjectType.ChartEmptyPoints:
                persistable = new ChartEmptyPoints();
                break;

            case ObjectType.ChartNoMoveDirections:
                persistable = new ChartNoMoveDirections();
                break;

            case ObjectType.ChartFormulaParameter:
                persistable = new ChartFormulaParameter();
                break;

            case ObjectType.ChartLegendColumn:
                persistable = new ChartLegendColumn();
                break;

            case ObjectType.ChartLegendColumnHeader:
                persistable = new ChartLegendColumnHeader();
                break;

            case ObjectType.ChartLegendCustomItem:
                persistable = new ChartLegendCustomItem();
                break;

            case ObjectType.ChartLegendCustomItemCell:
                persistable = new ChartLegendCustomItemCell();
                break;

            case ObjectType.ChartAlignType:
                persistable = new ChartAlignType();
                break;

            case ObjectType.ChartElementPosition:
                persistable = new ChartElementPosition();
                break;

            case ObjectType.ChartSmartLabel:
                persistable = new ChartSmartLabel();
                break;

            case ObjectType.ChartStripLine:
                persistable = new ChartStripLine();
                break;

            case ObjectType.ChartAxisTitle:
                persistable = new ChartAxisTitle();
                break;

            case ObjectType.ChartCustomPaletteColor:
                persistable = new ChartCustomPaletteColor();
                break;

            case ObjectType.GridLines:
                persistable = new ChartGridLines();
                break;

            case ObjectType.ChartTickMarks:
                persistable = new ChartTickMarks();
                break;

            case ObjectType.DataMember:
                persistable = new DataMember();
                break;

            case ObjectType.CustomDataRow:
                persistable = new CustomDataRow();
                break;

            case ObjectType.DataCell:
                persistable = new DataCell();
                break;

            case ObjectType.Variable:
                persistable = new Variable();
                break;

            case ObjectType.Page:
                persistable = new Page();
                break;

            case ObjectType.Paragraph:
                persistable = new Paragraph();
                break;

            case ObjectType.TextRun:
                persistable = new TextRun();
                break;

            case ObjectType.Report:
                persistable        = new Report(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.GaugePanel:
                persistable        = new GaugePanel(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.GaugeMember:
                persistable = new GaugeMember();
                break;

            case ObjectType.GaugeRow:
                persistable = new GaugeRow();
                break;

            case ObjectType.GaugeCell:
                persistable = new GaugeCell();
                break;

            case ObjectType.BackFrame:
                persistable = new BackFrame();
                break;

            case ObjectType.CapImage:
                persistable = new CapImage();
                break;

            case ObjectType.FrameBackground:
                persistable = new FrameBackground();
                break;

            case ObjectType.FrameImage:
                persistable = new FrameImage();
                break;

            case ObjectType.CustomLabel:
                persistable = new CustomLabel();
                break;

            case ObjectType.GaugeImage:
                persistable = new GaugeImage();
                break;

            case ObjectType.GaugeInputValue:
                persistable = new GaugeInputValue();
                break;

            case ObjectType.GaugeLabel:
                persistable = new GaugeLabel();
                break;

            case ObjectType.GaugePanelItem:
                persistable = new GaugePanelItem();
                break;

            case ObjectType.GaugeTickMarks:
                persistable = new GaugeTickMarks();
                break;

            case ObjectType.LinearGauge:
                persistable = new LinearGauge();
                break;

            case ObjectType.LinearPointer:
                persistable = new LinearPointer();
                break;

            case ObjectType.LinearScale:
                persistable = new LinearScale();
                break;

            case ObjectType.NumericIndicator:
                persistable = new NumericIndicator();
                break;

            case ObjectType.PinLabel:
                persistable = new PinLabel();
                break;

            case ObjectType.PointerCap:
                persistable = new PointerCap();
                break;

            case ObjectType.PointerImage:
                persistable = new PointerImage();
                break;

            case ObjectType.RadialGauge:
                persistable = new RadialGauge();
                break;

            case ObjectType.RadialPointer:
                persistable = new RadialPointer();
                break;

            case ObjectType.RadialScale:
                persistable = new RadialScale();
                break;

            case ObjectType.ScaleLabels:
                persistable = new ScaleLabels();
                break;

            case ObjectType.ScalePin:
                persistable = new ScalePin();
                break;

            case ObjectType.ScaleRange:
                persistable = new ScaleRange();
                break;

            case ObjectType.IndicatorImage:
                persistable = new IndicatorImage();
                break;

            case ObjectType.StateIndicator:
                persistable = new StateIndicator();
                break;

            case ObjectType.Thermometer:
                persistable = new Thermometer();
                break;

            case ObjectType.TickMarkStyle:
                persistable = new TickMarkStyle();
                break;

            case ObjectType.TopImage:
                persistable = new TopImage();
                break;

            case ObjectType.LookupInfo:
                persistable = new LookupInfo();
                break;

            case ObjectType.LookupDestinationInfo:
                persistable = new LookupDestinationInfo();
                break;

            case ObjectType.ReportSection:
                persistable = new ReportSection();
                break;

            case ObjectType.MapFieldDefinition:
                persistable = new MapFieldDefinition();
                break;

            case ObjectType.MapFieldName:
                persistable = new MapFieldName();
                break;

            case ObjectType.MapLineLayer:
                persistable = new MapLineLayer();
                break;

            case ObjectType.MapShapefile:
                persistable = new MapShapefile();
                break;

            case ObjectType.MapPolygonLayer:
                persistable = new MapPolygonLayer();
                break;

            case ObjectType.MapSpatialDataRegion:
                persistable = new MapSpatialDataRegion();
                break;

            case ObjectType.MapSpatialDataSet:
                persistable = new MapSpatialDataSet();
                break;

            case ObjectType.MapPointLayer:
                persistable = new MapPointLayer();
                break;

            case ObjectType.MapTile:
                persistable = new MapTile();
                break;

            case ObjectType.MapTileLayer:
                persistable = new MapTileLayer();
                break;

            case ObjectType.MapField:
                persistable = new MapField();
                break;

            case ObjectType.MapLine:
                persistable = new MapLine();
                break;

            case ObjectType.MapPolygon:
                persistable = new MapPolygon();
                break;

            case ObjectType.MapPoint:
                persistable = new MapPoint();
                break;

            case ObjectType.MapLineTemplate:
                persistable = new MapLineTemplate();
                break;

            case ObjectType.MapPolygonTemplate:
                persistable = new MapPolygonTemplate();
                break;

            case ObjectType.MapMarkerTemplate:
                persistable = new MapMarkerTemplate();
                break;

            case ObjectType.Map:
                persistable        = new Map(m_parentReportItem);
                m_parentReportItem = (ReportItem)persistable;
                break;

            case ObjectType.MapBorderSkin:
                persistable = new MapBorderSkin();
                break;

            case ObjectType.MapDataRegion:
                persistable = new MapDataRegion(m_parentReportItem);
                break;

            case ObjectType.MapMember:
                persistable = new MapMember();
                break;

            case ObjectType.MapRow:
                persistable = new MapRow();
                break;

            case ObjectType.MapCell:
                persistable = new MapCell();
                break;

            case ObjectType.MapLocation:
                persistable = new MapLocation();
                break;

            case ObjectType.MapSize:
                persistable = new MapSize();
                break;

            case ObjectType.MapGridLines:
                persistable = new MapGridLines();
                break;

            case ObjectType.MapBindingFieldPair:
                persistable = new MapBindingFieldPair();
                break;

            case ObjectType.MapCustomView:
                persistable = new MapCustomView();
                break;

            case ObjectType.MapDataBoundView:
                persistable = new MapDataBoundView();
                break;

            case ObjectType.MapElementView:
                persistable = new MapElementView();
                break;

            case ObjectType.MapViewport:
                persistable = new MapViewport();
                break;

            case ObjectType.MapLimits:
                persistable = new MapLimits();
                break;

            case ObjectType.MapColorScale:
                persistable = new MapColorScale();
                break;

            case ObjectType.MapColorScaleTitle:
                persistable = new MapColorScaleTitle();
                break;

            case ObjectType.MapDistanceScale:
                persistable = new MapDistanceScale();
                break;

            case ObjectType.MapTitle:
                persistable = new MapTitle();
                break;

            case ObjectType.MapLegend:
                persistable = new MapLegend();
                break;

            case ObjectType.MapLegendTitle:
                persistable = new MapLegendTitle();
                break;

            case ObjectType.MapBucket:
                persistable = new MapBucket();
                break;

            case ObjectType.MapColorPaletteRule:
                persistable = new MapColorPaletteRule();
                break;

            case ObjectType.MapColorRangeRule:
                persistable = new MapColorRangeRule();
                break;

            case ObjectType.MapCustomColorRule:
                persistable = new MapCustomColorRule();
                break;

            case ObjectType.MapCustomColor:
                persistable = new MapCustomColor();
                break;

            case ObjectType.MapLineRules:
                persistable = new MapLineRules();
                break;

            case ObjectType.MapPolygonRules:
                persistable = new MapPolygonRules();
                break;

            case ObjectType.MapSizeRule:
                persistable = new MapSizeRule();
                break;

            case ObjectType.MapMarkerImage:
                persistable = new MapMarkerImage();
                break;

            case ObjectType.MapMarker:
                persistable = new MapMarker();
                break;

            case ObjectType.MapMarkerRule:
                persistable = new MapMarkerRule();
                break;

            case ObjectType.MapPointRules:
                persistable = new MapPointRules();
                break;

            case ObjectType.PageBreak:
                persistable = new PageBreak();
                break;

            case ObjectType.DataScopeInfo:
                persistable = new DataScopeInfo();
                break;

            case ObjectType.LinearJoinInfo:
                persistable = new LinearJoinInfo();
                break;

            case ObjectType.IntersectJoinInfo:
                persistable = new IntersectJoinInfo();
                break;

            case ObjectType.BucketedDataAggregateInfos:
                persistable = new BucketedDataAggregateInfos();
                break;

            case ObjectType.DataAggregateInfoBucket:
                persistable = new DataAggregateInfoBucket();
                break;

            case ObjectType.NumericIndicatorRange:
                persistable = new NumericIndicatorRange();
                break;

            case ObjectType.IndicatorState:
                persistable = new IndicatorState();
                break;

            case ObjectType.SharedDataSetQuery:
                persistable = new SharedDataSetQuery();
                break;

            case ObjectType.DataSetCore:
                persistable = new DataSetCore();
                break;

            case ObjectType.DataSetParameterValue:
                persistable = new DataSetParameterValue();
                break;

            case ObjectType.RIFVariantContainer:
                persistable = new RIFVariantContainer();
                break;

            case ObjectType.IdcRelationship:
                persistable = new IdcRelationship();
                break;

            case ObjectType.DefaultRelationship:
                persistable = new DefaultRelationship();
                break;

            case ObjectType.JoinCondition:
                persistable = new Relationship.JoinCondition();
                break;

            case ObjectType.BandLayoutOptions:
                persistable = new BandLayoutOptions();
                break;

            case ObjectType.LabelData:
                persistable = new LabelData();
                break;

            case ObjectType.Slider:
                persistable = new Slider();
                break;

            case ObjectType.Coverflow:
                persistable = new Coverflow();
                break;

            case ObjectType.PlayAxis:
                persistable = new PlayAxis();
                break;

            case ObjectType.BandNavigationCell:
                persistable = new BandNavigationCell();
                break;

            case ObjectType.Tabstrip:
                persistable = new Tabstrip();
                break;

            case ObjectType.NavigationItem:
                persistable = new NavigationItem();
                break;

            case ObjectType.ScopedFieldInfo:
                persistable = new ScopedFieldInfo();
                break;

            default:
                Global.Tracer.Assert(condition: false, "Unsupported object type: " + objectType);
                break;
            }
            IDOwner iDOwner = persistable as IDOwner;

            if (iDOwner != null)
            {
                iDOwner.ParentInstancePath = m_parentIDOwner;
                m_parentIDOwner            = iDOwner;
            }
            persistable.Deserialize(context);
            m_parentIDOwner    = parentIDOwner;
            m_parentReportItem = parentReportItem;
            return(persistable);
        }
コード例 #32
0
        public override DataValue Compute(IAggregationContext context, TimeSlice bucket, AggregateState state)
        {
            int numGood = 0;
            int numBad = 0;
            int nTransitions = 0;
            long stateCode = -1;
            IEnumerator<DataValue> enumerator = bucket.Values.GetEnumerator();
            bool bucketValueNotEmpty = enumerator.MoveNext();
            if (bucketValueNotEmpty && enumerator.Current != null)
            {
                if (bucket.EarlyBound != null)
                {
                    if (enumerator.Current.SourceTimestamp == bucket.EarlyBound.Timestamp && bucket.EarlyBound.PriorPoint != null)
                    {
                        stateCode = Convert.ToInt32(Convert.ToBoolean(bucket.EarlyBound.PriorPoint.Value));
                    }
                    else if (bucket.EarlyBound.Value != null)
                    {
                        stateCode = Convert.ToInt32(Convert.ToBoolean(bucket.EarlyBound.Value.Value));
                    }
                }
            }

            // viz. UA MultiStateNodeState & TwoStateNodeState, 
            // assume DataValue.Value is either an EnumValueType or a bool
            if (bucketValueNotEmpty)
            {
                do
                {
                    DataValue dv = enumerator.Current;
                    if (state.RawValueIsGood(dv))
                    {
                        EnumValueType ev = dv.Value as EnumValueType;
                        if (ev == null)
                        {
                            bool b;
                            if (bool.TryParse(dv.Value.ToString(), out b))
                            {
                                if (stateCode < 0)
                                    stateCode = b ? 1 : 0;
                                else if (b.CompareTo(Convert.ToBoolean(stateCode)) != 0)
                                {
                                    nTransitions++;
                                    stateCode = b ? 1 : 0;
                                }
                            }
                            else
                                continue;
                        }
                        else
                        {
                            long s = ev.Value;
                            if (stateCode < 0)
                                stateCode = s;
                            else if (!s.Equals(stateCode))
                            {
                                nTransitions++;
                                stateCode = s;
                            }
                        }
                        numGood++;
                    }
                    else
                    {
                        numBad++;
                    }
                } while (enumerator.MoveNext());
            }

            StatusCode code = ComputeStatus(context, numGood, numBad, bucket).Code;
            DataValue retval = new DataValue { SourceTimestamp = bucket.From, Value = nTransitions };
            code.AggregateBits = AggregateBits.Calculated;
            if (bucket.Incomplete) code.AggregateBits |= AggregateBits.Partial;
            retval.StatusCode = code;
            return retval;
        }
コード例 #33
0
#pragma warning disable RECS0154 // Parameter is never used
        /// <summary>
        /// Updates the history.
        /// </summary>
        public uint UpdateAnnotations(SystemContext context, Annotation annotation, DataValue value, PerformUpdateType performUpdateType)
#pragma warning restore RECS0154 // Parameter is never used
        {
            var replaced = false;

            var filter = string.Format(System.Globalization.CultureInfo.InvariantCulture, "SourceTimestamp = #{0}#", value.SourceTimestamp);

            var view = new DataView(
                ArchiveItem.DataSet.Tables[2],
                filter,
                null,
                DataViewRowState.CurrentRows);

            DataRow row = null;

            for (var ii = 0; ii < view.Count; ii++)
            {
                var current = (Annotation)view[ii].Row[5];

                replaced = current.UserName == annotation.UserName;

                if (performUpdateType == PerformUpdateType.Insert)
                {
                    if (replaced)
                    {
                        return(StatusCodes.BadEntryExists);
                    }
                }

                if (replaced)
                {
                    row = view[ii].Row;
                    break;
                }
            }

            // add record indicating it was inserted.
            if (!replaced)
            {
                if (performUpdateType == PerformUpdateType.Replace || performUpdateType == PerformUpdateType.Remove)
                {
                    return(StatusCodes.BadNoEntryExists);
                }

                row = ArchiveItem.DataSet.Tables[2].NewRow();
            }

            // add/update new record.
            if (performUpdateType != PerformUpdateType.Remove)
            {
                row[0] = value.SourceTimestamp;
                row[1] = value.ServerTimestamp;
                row[2] = new DataValue(new ExtensionObject(annotation), StatusCodes.Good, value.SourceTimestamp, value.ServerTimestamp);
                row[3] = BuiltInType.ExtensionObject;
                row[4] = ValueRanks.Scalar;
                row[5] = annotation;

                if (!replaced)
                {
                    ArchiveItem.DataSet.Tables[2].Rows.Add(row);
                }
            }

            // delete record.
            else
            {
                row.Delete();
            }

            // accept all changes.
            ArchiveItem.DataSet.AcceptChanges();

            return(StatusCodes.Good);
        }
コード例 #34
0
ファイル: ComAeAreaBrowser.cs プロジェクト: yuriik83/UA-.NET
        /// <summary>
        /// Returns whether the specified node allows event notification. (Is the EventNotifier attribute set to SubscribeToEvents?)
        /// </summary>
        /// <param name="nodeId">The NodeId of the node being checked.</param>
        private bool IsEventNotificationListAllowed(NodeId nodeId)
        {
            //only nodes that allow event notification 
            DataValue value = new DataValue();
            try
            {
                Node node = m_session.ReadNode(nodeId);
                ServiceResult result = node.Read(null, Attributes.EventNotifier, value);
                if (result.Code == StatusCodes.BadAttributeIdInvalid)
                    value.Value = (byte)0; //no EventNotifier attribute found
            }
            catch (Exception e)
            {
                //we will assume either no attributes or no EventNotifier attribute
                Utils.Trace(e, "Unexpected error in IsEventNotificationListAllowed");
                value.Value = (byte)0;
            }

            return System.Convert.ToBoolean((byte)value.Value & EventNotifiers.SubscribeToEvents);

        }
コード例 #35
0
        /// <summary>
        /// Read a value node from server
        /// </summary>
        /// <typeparam name="T">type of value</typeparam>
        /// <param name="tag">node id</param>
        /// <returns>实际值</returns>
        public T ReadNode <T>(string tag)
        {
            DataValue dataValue = ReadNode(new NodeId(tag));

            return((T)dataValue.Value);
        }
コード例 #36
0
        /// <summary>
        /// Calculates the StdDev, Variance, StdDev2 and Variance2 aggregates for the timeslice.
        /// </summary>
        protected DataValue ComputeTimeAverage(TimeSlice slice, bool useSimpleBounds, int valueType)
        {
            // get the values in the slice.
            List<DataValue> values = null;

            if (useSimpleBounds)
            {
                values = GetValuesWithSimpleBounds(slice);
            }
            else
            {
                values = GetValuesWithInterpolatedBounds(slice);
            }

            // check for empty slice.
            if (values == null || values.Count == 0)
            {
                return GetNoDataValue(slice);
            }

            // get the regions.
            List<SubRegion> regions = GetRegionsInValueSet(values, !useSimpleBounds, Stepped);

            double total = 0;
            double totalDuration = 0;
            bool nonGoodRegionsExists = false;

            for (int ii = 0; ii < regions.Count; ii++)
            {
                double duration = regions[ii].Duration/1000.0;

                if (StatusCode.IsNotBad(regions[ii].StatusCode))
                {
                    total += (regions[ii].StartValue + regions[ii].EndValue) * duration / 2;
                    totalDuration += duration;
                }

                if (StatusCode.IsNotGood(regions[ii].StatusCode))
                {
                    nonGoodRegionsExists = true;
                }
            }

            // check if no good data.
            if (totalDuration == 0)
            {
                return GetNoDataValue(slice);
            }

            // select the result.
            double result = 0;

            switch (valueType)
            {
                case 1: { result = total/totalDuration; break; }
                case 2: { result = total; break; }
            }

            // set the timestamp and status.
            DataValue value = new DataValue();
            value.WrappedValue = new Variant(result, TypeInfo.Scalars.Double);
            value.SourceTimestamp = GetTimestamp(slice);
            value.ServerTimestamp = GetTimestamp(slice);

            if (useSimpleBounds)
            {
                value.StatusCode = GetTimeBasedStatusCode(regions, value.StatusCode);
            }
            else
            {
                value.StatusCode = StatusCodes.Good;

                if (nonGoodRegionsExists)
                {
                    value.StatusCode = StatusCodes.UncertainDataSubNormal;
                }
            }

            value.StatusCode = value.StatusCode.SetAggregateBits(AggregateBits.Calculated);

            // return result.
            return value;
        }
コード例 #37
0
        /// <summary>
        /// Verifies the index range result for a scalar value.
        /// </summary>
        private bool VerifyIndexRangeForScalar(IVariableBase variable, BuiltInType type, DataValue result)
        {
            // allow DA status codes to be returned before checking the
            if (IsDaBadStatus(result.StatusCode))
            {
                return(true);
            }

            if (result.StatusCode != StatusCodes.BadIndexRangeInvalid)
            {
                if (type != BuiltInType.ByteString && type != BuiltInType.String && type != BuiltInType.Variant)
                {
                    Log(
                        "Wrong error code when reading index range for scalar value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable,
                        variable.NodeId,
                        variable.Value,
                        result.StatusCode);

                    return(false);
                }

                if (type == BuiltInType.String)
                {
                    string value = result.Value as string;

                    if (value != null && value.Length > 2)
                    {
                        Log(
                            "Too much data return when reading index range for sting value '{0}'. NodeId = {1}, Value = {2}, ReturnedValue = {3}",
                            variable,
                            variable.NodeId,
                            variable.Value,
                            result.Value);

                        return(false);
                    }
                }

                if (type == BuiltInType.ByteString)
                {
                    byte[] value = result.Value as byte[];

                    if (value != null && value.Length > 2)
                    {
                        Log(
                            "Too much data return when reading index range for ByteString value '{0}'. NodeId = {1}, Value = {2}, ReturnedValue = {3}",
                            variable,
                            variable.NodeId,
                            variable.Value,
                            result.Value);

                        return(false);
                    }
                }

                if (type == BuiltInType.Variant)
                {
                    Array value = result.Value as Array;

                    if (value != null && value.Length > 2)
                    {
                        Log(
                            "Too much data return when reading index range for Variant value '{0}'. NodeId = {1}, Value = {2}, ReturnedValue = {3}",
                            variable,
                            variable.NodeId,
                            variable.Value,
                            result.Value);

                        return(false);
                    }
                }
            }
            else
            {
                if (type == BuiltInType.ByteString || type == BuiltInType.String)
                {
                    Log(
                        "Error returned reading index range for ByteString or String value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable,
                        variable.NodeId,
                        variable.Value,
                        result.StatusCode);

                    return(false);
                }
            }

            return(true);
        }
コード例 #38
0
		/// <summary>
		/// Applies the filter to value to determine if the new value should be kept.
		/// </summary>
		protected virtual bool ApplyFilter(DataValue value, ServiceResult error)
		{
            if (value == null) throw new ArgumentNullException("value");

            bool changed = ValueChanged(
                value,
                error,
                m_lastValue,
                m_lastError,
                m_filterToUse as DataChangeFilter,
                m_range);

            return changed;
        }
コード例 #39
0
        private bool VerifyDataEncoding(IVariableBase variable, BuiltInType type, QualifiedName dataEncoding, DataValue result)
        {
            // allow DA status codes to be returned before checking the
            if (IsDaBadStatus(result.StatusCode))
            {
                return(true);
            }

            IList <INode> encodings = Session.NodeCache.Find(
                variable.DataType,
                ReferenceTypeIds.HasEncoding,
                false,
                true);

            if (StatusCode.IsBad(result.StatusCode))
            {
                for (int ii = 0; ii < encodings.Count; ii++)
                {
                    if (encodings[ii].BrowseName == dataEncoding)
                    {
                        Log(
                            "Did not return a valid value for a supported data encoding '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                            variable,
                            variable.NodeId,
                            variable.Value,
                            result.StatusCode);

                        return(false);
                    }
                }

                return(true);
            }

            ExtensionObject extension = result.Value as ExtensionObject;

            if (extension != null)
            {
                for (int ii = 0; ii < encodings.Count; ii++)
                {
                    if (encodings[ii].BrowseName == dataEncoding)
                    {
                        if (ExpandedNodeId.ToNodeId(extension.TypeId, Session.NamespaceUris) != encodings[ii].NodeId)
                        {
                            Log(
                                "Did not return value with correct data encoding '{0}'. NodeId = {1}, Expected = {2}, Actual = {3}",
                                variable,
                                variable.NodeId,
                                encodings[ii].NodeId,
                                extension.TypeId);

                            return(false);
                        }
                    }
                }
            }

            ExtensionObject[] extensions = result.Value as ExtensionObject[];

            if (extensions != null)
            {
                for (int jj = 0; jj < extensions.Length; jj++)
                {
                    extension = extensions[jj];

                    for (int ii = 0; ii < encodings.Count; ii++)
                    {
                        if (encodings[ii].BrowseName == dataEncoding)
                        {
                            if (ExpandedNodeId.ToNodeId(extension.TypeId, Session.NamespaceUris) != encodings[ii].NodeId)
                            {
                                Log(
                                    "Did not return value with correct data encoding '{0}'. NodeId = {1}, Expected = {2}, Actual = {3}",
                                    variable,
                                    variable.NodeId,
                                    encodings[ii].NodeId,
                                    extension.TypeId);

                                return(false);
                            }
                        }
                    }
                }
            }

            return(true);
        }
コード例 #40
0
        /// <summary>
		/// Adds an event to the queue.
		/// </summary>
        public virtual void QueueValue(DataValue value, ServiceResult error)
        {
            QueueValue(value, error, false);
        }
コード例 #41
0
        /// <summary>
        /// Verifies the index range result for a scalar value.
        /// </summary>
        private bool VerifyIndexRangeForArray(IVariableBase variable, BuiltInType type, string indexRange, DataValue result)
        {
            // allow DA status codes.
            if (IsDaBadStatus(result.StatusCode))
            {
                return(true);
            }

            Array array = result.Value as Array;

            if (array == null)
            {
                if (result.StatusCode != StatusCodes.BadIndexRangeNoData)
                {
                    Log(
                        "Wrong error code when reading index range for array value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable,
                        variable.NodeId,
                        variable.Value,
                        result.StatusCode);

                    return(false);
                }

                return(true);
            }

            if (indexRange == "10000000:20000000")
            {
                Log(
                    "Expected BadIndexRangeNoData for array value '{0}'. NodeId = {1}, Value = {2}, ReturnedValue = {3}",
                    variable,
                    variable.NodeId,
                    variable.Value,
                    result.Value);

                return(false);
            }

            if (array.Length > 2)
            {
                Log(
                    "Too much data return when reading index range for array value '{0}'. NodeId = {1}, Value = {2}, ReturnedValue = {3}",
                    variable,
                    variable.NodeId,
                    variable.Value,
                    result.Value);

                return(false);
            }


            return(true);
        }
コード例 #42
0
        /// <summary>
        /// Adds a value to the queue.
        /// </summary>
        private void AddValueToQueue(DataValue value, ServiceResult error)
        {            
            if (m_queueSize > 1)
            {
                m_queue.QueueValue(value, error);
            }

            if (m_lastValue != null)
            {
                m_readyToTrigger = true;
            }

            // save last value recieved.
            m_lastValue = value;
            m_lastError = error;
            m_readyToPublish = true;

            Utils.Trace("QUEUE VALUE[{0}]: Value={1} CODE={2}<{2:X8}> OVERFLOW={3}", m_id, m_lastValue.WrappedValue, m_lastValue.StatusCode.Code, m_lastValue.StatusCode.Overflow);
        }
コード例 #43
0
 private static string AddSuffix(DataValue dataValue)
 {
     return($"{HistoricalDataValues.GetStringValue(dataValue)}Geoff");
 }
コード例 #44
0
        /// <summary>
        /// Validates the nodes and reads the values from the underlying source.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="nodesToRead">The nodes to read.</param>
        /// <param name="values">The values.</param>
        /// <param name="errors">The errors.</param>
        /// <param name="nodesToValidate">The nodes to validate.</param>
        /// <param name="cache">The cache.</param>
        protected override void Read(
            ServerSystemContext context,
            IList <ReadValueId> nodesToRead,
            IList <DataValue> values,
            IList <ServiceResult> errors,
            List <NodeHandle> nodesToValidate,
            IDictionary <NodeId, NodeState> cache)
        {
            ComDaClientManager system = (ComDaClientManager)this.SystemContext.SystemHandle;
            ComDaClient        client = system.SelectClient((ServerSystemContext)SystemContext, false);

            ReadRequestCollection requests = new ReadRequestCollection();

            for (int ii = 0; ii < nodesToValidate.Count; ii++)
            {
                NodeHandle handle = nodesToValidate[ii];

                lock (Lock)
                {
                    NodeState source = ValidateNode(context, handle, cache);

                    if (source == null)
                    {
                        continue;
                    }

                    DataValue   value      = values[handle.Index];
                    ReadValueId nodeToRead = nodesToRead[handle.Index];

                    // determine if request can be sent to the server.
                    bool queued = false;
                    errors[handle.Index] = requests.Add(source, nodeToRead, value, out queued);

                    if (queued)
                    {
                        continue;
                    }

                    // read built-in metadata.
                    errors[handle.Index] = source.ReadAttribute(
                        context,
                        nodeToRead.AttributeId,
                        nodeToRead.ParsedIndexRange,
                        nodeToRead.DataEncoding,
                        value);
                }
            }

            // read the values from the server.
            client.Read(requests);

            // extract the values from the results.
            for (int ii = 0; ii < nodesToValidate.Count; ii++)
            {
                NodeHandle  handle     = nodesToValidate[ii];
                DataValue   value      = values[handle.Index];
                ReadValueId nodeToRead = nodesToRead[handle.Index];

                lock (Lock)
                {
                    if (!requests.HasResult(nodeToRead))
                    {
                        continue;
                    }

                    errors[handle.Index] = requests.GetResult(context, handle.Node, nodeToRead, value, context.DiagnosticsMask);
                }
            }
        }
コード例 #45
0
        public void MatrixOverflow(
            EncodingType encoderType,
            BuiltInType builtInType
            )
        {
            Assume.That(builtInType != BuiltInType.Null);
            int matrixDimension = RandomSource.NextInt32(8) + 2;

            int[] dimensions = new int[matrixDimension];
            SetMatrixDimensions(dimensions);
            int   elements   = ElementsFromDimension(dimensions);
            Array randomData = DataGenerator.GetRandomArray(builtInType, false, elements, true);

            var matrix = new Matrix(randomData, builtInType, dimensions);

            for (int ii = 0; ii < matrixDimension; ii++)
            {
                if (ii % 2 == 0)
                {
                    matrix.Dimensions[ii] = 0x40000001;
                }
                else
                {
                    matrix.Dimensions[ii] = 4;
                }
            }

            var variant = new Variant(matrix);

            string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}";

            TestContext.Out.WriteLine(encodeInfo);
            TestContext.Out.WriteLine(variant);
            DataValue expected = CreateDataValue(builtInType, variant);

            Assert.IsNotNull(expected, "Expected DataValue is Null, " + encodeInfo);
            TestContext.Out.WriteLine("Expected:");
            TestContext.Out.WriteLine(expected);
            var      encoderStream = new MemoryStream();
            IEncoder encoder       = CreateEncoder(encoderType, Context, encoderStream, typeof(DataValue));

            encoder.WriteDataValue("DataValue", expected);
            Dispose(encoder);
            var    buffer = encoderStream.ToArray();
            string jsonFormatted;

            switch (encoderType)
            {
            case EncodingType.Json:
                jsonFormatted = PrettifyAndValidateJson(Encoding.UTF8.GetString(buffer));
                break;
            }
            var      decoderStream = new MemoryStream(buffer);
            IDecoder decoder       = CreateDecoder(encoderType, Context, decoderStream, typeof(DataValue));

            switch (encoderType)
            {
            case EncodingType.Json:
            {
                // check such matrix cannot be initialized when decoding from Json format
                // the exception is thrown while trying to construct the Matrix
                Assert.Throws(
                    typeof(ArgumentException),
                    () => {
                        decoder.ReadDataValue("DataValue");
                    });
                break;
            }

            case EncodingType.Xml:
            {
                // check such matrix cannot be initialized when decoding from Xml format
                // the exception is thrown while trying to construct the Matrix but is caught and handled
                decoder.ReadDataValue("DataValue");
                break;
            }

            case EncodingType.Binary:
            {
                // check such matrix cannot be initialized when decoding from Binary format
                // the exception is thrown before trying to construct the Matrix
                Assert.Throws(
                    typeof(ServiceResultException),
                    () => {
                        decoder.ReadDataValue("DataValue");
                    });
                break;
            }
            }
            Dispose(decoder);
        }
コード例 #46
0
        /// <summary>
        /// Connects the session if it is disconnected.
        /// </summary>
        public async Task ConnectSessionAsync(CancellationToken ct)
        {
            bool sessionLocked = false;

            try
            {
                EndpointDescription selectedEndpoint   = null;
                ConfiguredEndpoint  configuredEndpoint = null;
                sessionLocked = await LockSessionAsync();

                // if the session is already connected or connecting or shutdown in progress, return
                if (!sessionLocked || ct.IsCancellationRequested || State == SessionState.Connected || State == SessionState.Connecting)
                {
                    return;
                }

                Logger.Information($"Connect and monitor session and nodes on endpoint '{EndpointUrl.AbsoluteUri}' {(UseSecurity ? "with" : "without")} security.");
                State = SessionState.Connecting;
                try
                {
                    // release the session to not block for high network timeouts
                    ReleaseSession();
                    sessionLocked = false;

                    // start connecting
                    selectedEndpoint   = CoreClientUtils.SelectEndpoint(EndpointUrl.AbsoluteUri, UseSecurity);
                    configuredEndpoint = new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(OpcApplicationConfiguration.ApplicationConfiguration));
                    uint timeout = SessionTimeout * ((UnsuccessfulConnectionCount >= OpcSessionCreationBackoffMax) ? OpcSessionCreationBackoffMax : UnsuccessfulConnectionCount + 1);
                    Logger.Information($"Create {(UseSecurity ? "secured" : "unsecured")} session for endpoint URI '{EndpointUrl.AbsoluteUri}' with timeout of {timeout} ms.");
                    OpcUaClientSession = await Session.Create(
                        OpcApplicationConfiguration.ApplicationConfiguration,
                        configuredEndpoint,
                        true,
                        false,
                        ApplicationName,
                        timeout,
                        new UserIdentity(new AnonymousIdentityToken()),
                        null);
                }
                catch (Exception e)
                {
                    // save error info
                    if (e is ServiceResultException sre)
                    {
                        ServiceResultException = sre;
                    }
                    Logger.Error(e, $"Session creation to endpoint '{EndpointUrl.AbsoluteUri}' failed {++UnsuccessfulConnectionCount} time(s). Please verify if server is up and {ProgramName} configuration is correct.");
                    State = SessionState.Disconnected;
                    OpcUaClientSession = null;
                    return;
                }
                finally
                {
                    if (OpcUaClientSession != null)
                    {
                        sessionLocked = await LockSessionAsync();

                        if (sessionLocked)
                        {
                            Logger.Information($"Session successfully created with Id {OpcUaClientSession.SessionId}.");
                            if (!selectedEndpoint.EndpointUrl.Equals(configuredEndpoint.EndpointUrl.AbsoluteUri, StringComparison.OrdinalIgnoreCase))
                            {
                                Logger.Information($"the Server has updated the EndpointUrl to '{selectedEndpoint.EndpointUrl}'");
                            }

                            // init object state and install keep alive
                            UnsuccessfulConnectionCount          = 0;
                            OpcUaClientSession.KeepAliveInterval = OpcKeepAliveInterval * 1000;
                            OpcUaClientSession.KeepAlive        += StandardClient_KeepAlive;

                            // fetch the namespace array and cache it. it will not change as long the session exists.
                            DataValue namespaceArrayNodeValue = OpcUaClientSession.ReadValue(VariableIds.Server_NamespaceArray);
                            _namespaceTable.Update(namespaceArrayNodeValue.GetValue <string[]>(null));

                            // show the available namespaces
                            Logger.Information($"The session to endpoint '{selectedEndpoint.EndpointUrl}' has {_namespaceTable.Count} entries in its namespace array:");
                            int i = 0;
                            foreach (var ns in _namespaceTable.ToArray())
                            {
                                Logger.Information($"Namespace index {i++}: {ns}");
                            }

                            // fetch the minimum supported item sampling interval from the server.
                            DataValue minSupportedSamplingInterval = OpcUaClientSession.ReadValue(VariableIds.Server_ServerCapabilities_MinSupportedSampleRate);
                            _minSupportedSamplingInterval = minSupportedSamplingInterval.GetValue(0);
                            Logger.Information($"The server on endpoint '{selectedEndpoint.EndpointUrl}' supports a minimal sampling interval of {_minSupportedSamplingInterval} ms.");
                            State = SessionState.Connected;
                        }
                        else
                        {
                            State = SessionState.Disconnected;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, "Error in ConnectSessions.");
            }
            finally
            {
                if (sessionLocked)
                {
                    ReleaseSession();
                }
            }
        }
コード例 #47
0
        /// <summary>
        /// Reads the DataValues section
        /// </summary>
        protected override IList <Series> ReadDataValues(XmlReader r)
        {
            int valueCount;
            var lst = new List <DataValueWrapper>(Int32.TryParse(r.GetAttribute("count"), out valueCount) ? valueCount : 4);

            var qualifiers           = new Dictionary <string, Qualifier>();
            var methods              = new Dictionary <string, Method>();
            var sources              = new Dictionary <string, Source>();
            var qualityControlLevels = new Dictionary <string, QualityControlLevel>();
            var samples              = new Dictionary <string, Sample>();
            var offsets              = new Dictionary <string, OffsetType>();
            var seriesDictionary     = new Dictionary <string, Series>();

            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element)
                {
                    if (r.Name == "value")
                    {
                        //create a new empty data value and add it to the list
                        var wrapper = new DataValueWrapper();
                        var val     = new DataValue();
                        wrapper.DataValue = val;
                        lst.Add(wrapper);

                        if (r.HasAttributes)
                        {
                            var censorCode = r.GetAttribute("censorCode");
                            if (!string.IsNullOrEmpty(censorCode))
                            {
                                val.CensorCode = censorCode;
                            }
                            //fix by Jiri - sometimes the dateTime attribute is uppercase
                            var localDateTime = r.GetAttribute("dateTime");
                            if (string.IsNullOrEmpty(localDateTime))
                            {
                                localDateTime = r.GetAttribute("DateTime");
                            }
                            val.LocalDateTime = Convert.ToDateTime(localDateTime, CultureInfo.InvariantCulture);
                            val.DateTimeUTC   = val.LocalDateTime;
                            val.UTCOffset     = 0.0;

                            //method
                            var methodID = r.GetAttribute("methodID");
                            if (String.IsNullOrEmpty(methodID))
                            {
                                methodID = "0"; //when a method ID is unspecified
                            }
                            if (!methods.ContainsKey(methodID))
                            {
                                var newMethod = Method.Unknown;
                                methods.Add(methodID, newMethod);
                            }
                            wrapper.MethodID = methodID;

                            //quality control level
                            string qualityCode = r.GetAttribute("qualityControlLevel");
                            if (String.IsNullOrEmpty(qualityCode))
                            {
                                qualityCode = "unknown"; //when the quality control level is unspecified
                            }
                            if (!qualityControlLevels.ContainsKey(qualityCode))
                            {
                                var qualControl = QualityControlLevel.Unknown;
                                qualControl.Code        = qualityCode;
                                qualControl.Definition  = qualityCode;
                                qualControl.Explanation = qualityCode;
                                qualityControlLevels.Add(qualityCode, qualControl);
                            }

                            //source
                            var sourceID = r.GetAttribute("sourceID");
                            if (String.IsNullOrEmpty(sourceID))
                            {
                                sourceID = "0"; //when a source ID is unspecified
                            }
                            if (!sources.ContainsKey(sourceID))
                            {
                                sources.Add(sourceID, Source.Unknown);
                            }
                            wrapper.SourceID   = sourceID;
                            wrapper.SeriesCode = SeriesCodeHelper.CreateSeriesCode(methodID, qualityCode, sourceID); //----method-source-qualityControl combination----

                            //sample
                            var sampleID = r.GetAttribute("sampleID");
                            if (!String.IsNullOrEmpty(sampleID))
                            {
                                if (!samples.ContainsKey(sampleID))
                                {
                                    samples.Add(sampleID, Sample.Unknown);
                                }
                            }
                            wrapper.SampleID = sampleID;

                            //qualifiers
                            string qualifierCodes = r.GetAttribute("qualifiers");
                            if (!String.IsNullOrEmpty(qualifierCodes))
                            {
                                if (!qualifiers.ContainsKey(qualifierCodes))
                                {
                                    var newQualifier = new Qualifier {
                                        Code = qualifierCodes
                                    };
                                    qualifiers.Add(qualifierCodes, newQualifier);
                                    val.Qualifier = newQualifier;
                                }
                                else
                                {
                                    val.Qualifier = qualifiers[qualifierCodes];
                                }
                            }

                            //vertical offset
                            var offsetID = r.GetAttribute("offsetTypeID");
                            if (!String.IsNullOrEmpty(offsetID))
                            {
                                if (!offsets.ContainsKey(offsetID))
                                {
                                    offsets.Add(offsetID, new OffsetType());
                                }
                                var offsetValue = r.GetAttribute("offsetValue");
                                if (!String.IsNullOrEmpty(offsetValue))
                                {
                                    val.OffsetValue = Convert.ToDouble(offsetValue, CultureInfo.InvariantCulture);
                                }
                            }
                            wrapper.OffsetID = offsetID;

                            //data value
                            val.Value = Convert.ToDouble(r.ReadString(), CultureInfo.InvariantCulture);
                        }
                    }
                    else if (r.Name == "method")
                    {
                        var method        = ReadMethod(r);
                        var methodCodeKey = method.Code.ToString(CultureInfo.InvariantCulture);
                        if (methods.ContainsKey(methodCodeKey))
                        {
                            methods[methodCodeKey] = method;
                        }
                    }
                    else if (r.Name == "source")
                    {
                        var source        = ReadSource(r);
                        var sourceCodeKey = source.OriginId.ToString(CultureInfo.InvariantCulture);
                        if (sources.ContainsKey(sourceCodeKey))
                        {
                            sources[sourceCodeKey] = source;
                        }
                    }
                    else if (r.Name == "qualityControlLevel")
                    {
                        //quality control level seems to be included with each value
                    }
                    else if (r.Name == "qualifier")
                    {
                        ReadQualifier(r, qualifiers);
                    }
                    else if (r.Name == "offset")
                    {
                        ReadOffset(r, offsets);
                    }
                }
            }

            //to assign special properties of each data value
            foreach (var wrapper in lst)
            {
                var val = wrapper.DataValue;

                //which series does the data value belong to?
                var seriesCode = wrapper.SeriesCode;
                if (!seriesDictionary.ContainsKey(seriesCode))
                {
                    var newSeries = new Series();
                    seriesDictionary.Add(seriesCode, newSeries);
                    //assign method, source and qual.control level
                    //assign method, source and qual.control level
                    try
                    {
                        newSeries.Method = methods[SeriesCodeHelper.GetMethodCode(seriesCode)];
                        //fix by Jiri: fixes the case when sourceID is unspecified sources
                        //has more than one source entry
                        string sourceCode = SeriesCodeHelper.GetSourceCode(seriesCode);
                        if (sourceCode == "0" && sources.Count > 0)
                        {
                            foreach (string sc in sources.Keys)
                            {
                                if (sc != "0")
                                {
                                    sourceCode = sc;
                                    break;
                                }
                            }
                        }
                        newSeries.Source = sources[sourceCode];
                        newSeries.QualityControlLevel = qualityControlLevels[SeriesCodeHelper.GetQualityCode(seriesCode)];
                    }
                    catch { }
                }

                //add the data value to the correct series
                var series = seriesDictionary[seriesCode];
                series.DataValueList.Add(val);
                val.Series = series;

                Sample sample;
                if (!string.IsNullOrEmpty(wrapper.SampleID) &&
                    samples.TryGetValue(wrapper.SampleID, out sample))
                {
                    val.Sample = sample;
                }
                OffsetType offset;
                if (!string.IsNullOrEmpty(wrapper.OffsetID) &&
                    offsets.TryGetValue(wrapper.OffsetID, out offset))
                {
                    val.OffsetType = offset;
                }
                if (series.Method == null)
                {
                    series.Method = methods[wrapper.MethodID];
                }
                if (series.Source == null)
                {
                    series.Source = sources[wrapper.SourceID];
                }
            }

            //to check the qualifiers
            CheckQualifiers(qualifiers);
            return(seriesDictionary.Values.ToList());
        }
コード例 #48
0
ファイル: UAClient.cs プロジェクト: JDevbois/UA-.NETStandard
        /// <summary>
        /// Read a list of nodes from Server
        /// </summary>
        public void ReadNodes()
        {
            if (m_session == null || m_session.Connected == false)
            {
                Console.WriteLine("Session not connected!");
                return;
            }

            try
            {
                #region Read a node by calling the Read Service

                // build a list of nodes to be read
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection()
                {
                    // Value of ServerStatus
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus, AttributeId = Attributes.Value
                    },
                    // BrowseName of ServerStatus_StartTime
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.BrowseName
                    },
                    // Value of ServerStatus_StartTime
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.Value
                    }
                };

                // Read the node attributes
                DataValueCollection      resultsValues   = null;
                DiagnosticInfoCollection diagnosticInfos = null;
                Console.WriteLine("Reading nodes...");

                // Call Read Service
                m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    nodesToRead,
                    out resultsValues,
                    out diagnosticInfos);

                // Validate the results
                ClientBase.ValidateResponse(resultsValues, nodesToRead);

                // Display the results.
                foreach (DataValue result in resultsValues)
                {
                    Console.WriteLine("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode);
                }
                #endregion

                #region Read the Value attribute of a node by calling the Session.ReadValue method
                // Read Server NamespaceArray
                Console.WriteLine("Reading Value of NamespaceArray node...");
                DataValue namespaceArray = m_session.ReadValue(Variables.Server_NamespaceArray);
                // Display the result
                Console.WriteLine(String.Format("NamespaceArray Value = {0}", namespaceArray.ToString()));
                #endregion
            }
            catch (Exception ex)
            {
                // Log Error
                string logMessage = String.Format("Read Nodes Error : {0}.", ex.Message);
                Console.WriteLine(logMessage);
            }
        }
コード例 #49
0
        protected override void loadData()
        {
            var logInPb =
                PostBack.CreateFull(
                    actionGetter:
                        () =>
                        new PostBackAction( user.MustChangePassword ? ChangePassword.Page.GetInfo( info.ReturnUrl ) as ResourceInfo : new ExternalResourceInfo( info.ReturnUrl ) ) );
            var newPasswordPb = PostBack.CreateFull( id: "newPw", actionGetter: getSendNewPasswordAction );

            var registeredTable = EwfTable.Create( caption: "Registered users" );
            registeredTable.AddItem(
                new EwfTableItem(
                    ( "You may log in to this system if you have registered your email address with " + FormsAuthStatics.SystemProvider.AdministratingCompanyName ).ToCell(
                        new TableCellSetup( fieldSpan: 2 ) ) ) );

            emailAddress = new DataValue<string>();
            var emailVl = new BasicValidationList();
            registeredTable.AddItem(
                new EwfTableItem( "Email address", emailAddress.GetEmailAddressFormItem( "", "Please enter a valid email address.", emailVl ).ToControl() ) );
            logInPb.AddValidations( emailVl );
            newPasswordPb.AddValidations( emailVl );

            var password = new DataValue<string>();
            registeredTable.AddItem(
                new EwfTableItem(
                    "Password",
                    FormItem.Create(
                        "",
                        new EwfTextBox( "", masksCharacters: true ),
                        validationGetter: control => new EwfValidation( ( pbv, v ) => password.Value = control.GetPostBackValue( pbv ), logInPb ) ).ToControl() ) );

            if( FormsAuthStatics.PasswordResetEnabled ) {
                registeredTable.AddItem(
                    new EwfTableItem(
                        new PlaceHolder().AddControlsReturnThis(
                            "If you are a first-time user and do not know your password, or if you have forgotten your password, ".GetLiteralControl(),
                            new PostBackButton( newPasswordPb, new TextActionControlStyle( "click here to immediately send yourself a new password." ), usesSubmitBehavior: false ) )
                            .ToCell( new TableCellSetup( fieldSpan: 2 ) ) ) );
            }

            ph.AddControlsReturnThis( registeredTable );

            var specialInstructions = EwfUiStatics.AppProvider.GetSpecialInstructionsForLogInPage();
            if( specialInstructions != null )
                ph.AddControlsReturnThis( specialInstructions );
            else {
                var unregisteredTable = EwfTable.Create( caption: "Unregistered users" );
                unregisteredTable.AddItem( new EwfTableItem( "If you have difficulty logging in, please " + FormsAuthStatics.SystemProvider.LogInHelpInstructions ) );
                ph.AddControlsReturnThis( unregisteredTable );
            }

            EwfUiStatics.SetContentFootActions( new ActionButtonSetup( "Log In", new PostBackButton( logInPb ) ) );

            var logInMethod = FormsAuthStatics.GetLogInMethod(
                this,
                emailAddress,
                password,
                getUnregisteredEmailMessage(),
                "Incorrect password. If you do not know your password, enter your email address and send yourself a new password using the link below.",
                logInPb );
            logInPb.AddModificationMethod( () => user = logInMethod() );
        }
コード例 #50
0
        /// <summary>
        /// Publishes a value.
        /// </summary>
        private void Publish(
            OperationContext context,
            DataValue value,
            ServiceResult error,
            Queue <MonitoredItemNotification> notifications,
            Queue <DiagnosticInfo> diagnostics)
        {
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }

            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;

            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;

            if (m_lastError != null)
            {
                if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
                {
                    diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError);
                }
            }

            diagnostics.Enqueue(diagnosticInfo);
        }
コード例 #51
0
        /// <summary>
        /// Calculates the RegSlope, RegConst and RegStdDev aggregates for the timeslice.
        /// </summary>
        protected DataValue ComputeAverage(TimeSlice slice)
        {
            // get the values in the slice.
            List<DataValue> values = GetValues(slice);

            // check for empty slice.
            if (values == null || values.Count == 0)
            {
                return GetNoDataValue(slice);
            }

            // calculate total and count.
            int count = 0;
            double total = 0;

            for (int ii = 0; ii < values.Count; ii++)
            {
                if (StatusCode.IsGood(values[ii].StatusCode))
                {
                    try
                    {
                        double sample = CastToDouble(values[ii]);
                        total += sample;
                        count++;
                    }
                    catch
                    {
                        // ignore conversion errors.
                    }
                }
            }

            // check for empty slice.
            if (count == 0)
            {
                return GetNoDataValue(slice);
            }

            // select the result.
            double result = total/count;

            // set the timestamp and status.
            DataValue value = new DataValue();
            value.WrappedValue = new Variant(result, TypeInfo.Scalars.Double);
            value.SourceTimestamp = GetTimestamp(slice);
            value.ServerTimestamp = GetTimestamp(slice);
            value.StatusCode = value.StatusCode.SetAggregateBits(AggregateBits.Calculated);
            value.StatusCode = GetValueBasedStatusCode(slice, values, value.StatusCode);

            // return result.
            return value;
        }
コード例 #52
0
        private async void ShowMember(NodeId sourceId)
        {
            textBox_nodeId.Text = sourceId.ToString();
            // dataGridView1.Rows.Clear();
            int index = 0;
            ReferenceDescriptionCollection references;

            try
            {
                references = await Task.Run(() =>
                {
                    return(GetReferenceDescriptionCollection(sourceId));
                });
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(Text, exception);
                return;
            }
            if (references?.Count > 0)
            {
                // 获取所有要读取的子节点
                List <NodeId> nodeIds = new List <NodeId>();
                for (int ii = 0; ii < references.Count; ii++)
                {
                    ReferenceDescription target = references[ii];
                    nodeIds.Add((NodeId)target.NodeId);
                }
                DateTime dateTimeStart = DateTime.Now;
                // 获取所有的值
                DataValue[] dataValues = await Task.Run(() =>
                {
                    return(ReadOneNodeFiveAttributes(nodeIds));
                });

                label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
                // 显示
                for (int jj = 0; jj < dataValues.Length; jj += 5)
                {
                    AddDataGridViewNewRow(dataValues, jj, index++, nodeIds[jj / 5]);
                }
            }
            else
            {
                // 子节点没有数据的情况
                try
                {
                    DateTime  dateTimeStart = DateTime.Now;
                    DataValue dataValue     = CommonMethods.opcUaClient.ReadNode(sourceId);
                    if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension)
                    {
                        // 数组显示
                        AddDataGridViewArrayRow(sourceId, out index);
                    }
                    else
                    {
                        // 显示单个数本身
                        label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
                        AddDataGridViewNewRow(ReadOneNodeFiveAttributes(new List <NodeId>()
                        {
                            sourceId
                        }), 0, index++, sourceId);
                    }
                }
                catch (Exception exception)
                {
                    ClientUtils.HandleException(Text, exception);
                    return;
                }
            }
            ClearDataGridViewRows(index);
        }
コード例 #53
0
		/// <summary>
		/// Publishes a single data change notifications.
		/// </summary>
        protected virtual bool Publish(
            OperationContext                 context,
            Queue<MonitoredItemNotification> notifications,
            Queue<DiagnosticInfo>            diagnostics,
            DataValue                        value, 
            ServiceResult                    error)
        {            
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true), 
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }
            
            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true), 
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;
            
            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            ServerUtils.ReportPublishValue(m_nodeId, m_id, item.Value);
            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;
            
            if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
            {
                diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error);
            }

            diagnostics.Enqueue(diagnosticInfo);

            return false;
        }
コード例 #54
0
        private void AddDataGridViewNewRow(DataValue[] dataValues, int startIndex, int index, NodeId nodeId)
        {
            // int index = dataGridView1.Rows.Add();
            while (index >= dataGridView1.Rows.Count)
            {
                dataGridView1.Rows.Add();
            }
            DataGridViewRow dgvr = dataGridView1.Rows[index];

            dgvr.Tag = nodeId;
            if (dataValues[startIndex].WrappedValue.Value == null)
            {
                return;
            }
            NodeClass nodeclass = (NodeClass)dataValues[startIndex].WrappedValue.Value;

            dgvr.Cells[1].Value = dataValues[3 + startIndex].WrappedValue.Value;
            dgvr.Cells[5].Value = dataValues[4 + startIndex].WrappedValue.Value;
            dgvr.Cells[4].Value = GetDiscriptionFromAccessLevel(dataValues[2 + startIndex]);
            if (nodeclass == NodeClass.Object)
            {
                dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
                dgvr.Cells[2].Value = "";
                dgvr.Cells[3].Value = nodeclass.ToString();
            }
            else if (nodeclass == NodeClass.Method)
            {
                dgvr.Cells[0].Value = Properties.Resources.Method_636;
                dgvr.Cells[2].Value = "";
                dgvr.Cells[3].Value = nodeclass.ToString();
            }
            else if (nodeclass == NodeClass.Variable)
            {
                DataValue dataValue = dataValues[1 + startIndex];
                if (dataValue.WrappedValue.TypeInfo != null)
                {
                    dgvr.Cells[3].Value = dataValue.WrappedValue.TypeInfo.BuiltInType;
                    // dgvr.Cells[3].Value = dataValue.Value.GetType().ToString();
                    if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.Scalar)
                    {
                        dgvr.Cells[2].Value = dataValue.WrappedValue.Value;
                        dgvr.Cells[0].Value = Properties.Resources.Enum_582;
                    }
                    else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.OneDimension)
                    {
                        dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
                        dgvr.Cells[0].Value = Properties.Resources.brackets_Square_16xMD;
                    }
                    else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.TwoDimensions)
                    {
                        dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
                        dgvr.Cells[0].Value = Properties.Resources.Module_648;
                    }
                    else
                    {
                        dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
                        dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
                    }
                }
                else
                {
                    dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
                    dgvr.Cells[2].Value = dataValue.Value;
                    dgvr.Cells[3].Value = "null";
                }
            }
            else
            {
                dgvr.Cells[2].Value = "";
                dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
                dgvr.Cells[3].Value = nodeclass.ToString();
            }
        }
コード例 #55
0
        /// <summary>
        /// Applies the filter to value to determine if the new value should be kept.
        /// </summary>
        public static bool ValueChanged(
            DataValue value,
            ServiceResult error,
            DataValue lastValue,
            ServiceResult lastError, 
            DataChangeFilter filter,
            double range)
        {
            if (value == null) throw new ArgumentNullException("value");

            // select default data change filters.
            double deadband = 0.0;
            DeadbandType deadbandType = DeadbandType.None;
            DataChangeTrigger trigger = DataChangeTrigger.StatusValue;

            // apply filter.
            if (filter != null)
            {
                trigger = filter.Trigger;
                deadbandType = (DeadbandType)(int)filter.DeadbandType;
                deadband = filter.DeadbandValue;

                // when deadband is used and the trigger is StatusValueTimestamp, then it should behave as if trigger is StatusValue.
                if ((deadbandType != DeadbandType.None) && (trigger == DataChangeTrigger.StatusValueTimestamp))
                {
                    trigger = DataChangeTrigger.StatusValue;
                }
            }
            
            // get the current status.
            uint status = StatusCodes.Good;
            
            if (error != null)
            {
                status = error.StatusCode.Code;
            }
            else if (lastValue != null)
            {
                status = value.StatusCode.Code;
            }

            // get the last status.
            uint lastStatus = StatusCodes.Good;

            if (lastError != null)
            {
                lastStatus = lastError.StatusCode.Code;
            }
            else if (lastValue != null)
            {
                lastStatus = lastValue.StatusCode.Code;
            }

            // value changed if any status change occurrs.
            if (status != lastStatus)
            {
                return true;
            }

            // value changed if only one is null.
            if (value == null || lastValue == null)
            {
                return lastValue != null || value != null;
            }

            // check if timestamp has changed.
            if (trigger == DataChangeTrigger.StatusValueTimestamp)
            {
                if (lastValue.SourceTimestamp != value.SourceTimestamp)
                {
                    return true;
                }
            }

            // check if value changes are ignored.
            if (trigger == DataChangeTrigger.Status)
            {
                return false;
            }

            // check if reference to same object.
            if (!Equals(lastValue.Value, value.Value, deadbandType, deadband, range))
            {
                return true;
            }

            // must be equal.
            return false;
        }
コード例 #56
0
        /// <summary>
        /// Returns credit-card-collection hidden fields and a JavaScript function call getter that opens a Stripe Checkout modal window. If the window's submit
        /// button is clicked, the credit card is charged or otherwise used. Do not execute the getter until after the page tree has been built.
        /// </summary>
        /// <param name="testPublishableKey">Your test publishable API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="livePublishableKey">Your live publishable API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="name">See https://stripe.com/docs/checkout. Do not pass null.</param>
        /// <param name="description">See https://stripe.com/docs/checkout. Do not pass null.</param>
        /// <param name="amountInDollars">See https://stripe.com/docs/checkout, but note that this parameter is in dollars, not cents</param>
        /// <param name="testSecretKey">Your test secret API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="liveSecretKey">Your live secret API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="successHandler">A method that executes if the credit-card submission is successful. The first parameter is the charge ID and the second
        /// parameter is the amount of the charge, in dollars.</param>
        /// <param name="prefilledEmailAddressOverride">By default, the email will be prefilled with AppTools.User.Email if AppTools.User is not null. You can
        /// override this with either a specified email address (if user is paying on behalf of someone else) or the empty string (to force the user to type in the
        /// email address).</param>
        public static Tuple <IReadOnlyCollection <EtherealComponent>, Func <string> > GetCreditCardCollectionHiddenFieldsAndJsFunctionCall(
            string testPublishableKey, string livePublishableKey, string name, string description, decimal?amountInDollars, string testSecretKey,
            string liveSecretKey, Func <string, decimal, StatusMessageAndDestination> successHandler, string prefilledEmailAddressOverride = null)
        {
            if (!EwfApp.Instance.RequestIsSecure(HttpContext.Current.Request))
            {
                throw new ApplicationException("Credit-card collection can only be done from secure pages.");
            }
            EwfPage.Instance.ClientScript.RegisterClientScriptInclude(
                typeof(PaymentProcessingStatics),
                "Stripe Checkout",
                "https://checkout.stripe.com/checkout.js");

            if (amountInDollars.HasValue && amountInDollars.Value.DollarValueHasFractionalCents())
            {
                throw new ApplicationException("Amount must not include fractional cents.");
            }

            ResourceInfo successDestination = null;
            var          postBack           = PostBack.CreateFull(
                id: PostBack.GetCompositeId("ewfCreditCardCollection", description),
                actionGetter: () => new PostBackAction(successDestination));
            var token = new DataValue <string>();

            var hiddenFieldId = new HiddenFieldId();
            List <EtherealComponent> hiddenFields = new List <EtherealComponent>();

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                postBack.ToCollection(),
                () => hiddenFields.Add(
                    new EwfHiddenField("", validationMethod: (postBackValue, validator) => token.Value = postBackValue.Value, id: hiddenFieldId).PageComponent));

            postBack.AddModificationMethod(
                () => {
                // We can add support later for customer creation, subscriptions, etc. as needs arise.
                if (!amountInDollars.HasValue)
                {
                    throw new ApplicationException("Only simple charges are supported at this time.");
                }

                StripeCharge response;
                try {
                    response = new StripeGateway(ConfigurationStatics.IsLiveInstallation ? liveSecretKey : testSecretKey).Post(
                        new ChargeStripeCustomer
                    {
                        Amount = (int)(amountInDollars.Value * 100), Currency = "usd", Description = description.Any() ? description : null, Card = token.Value
                    });
                }
                catch (StripeException e) {
                    if (e.Type == "card_error")
                    {
                        throw new DataModificationException(e.Message);
                    }
                    throw new ApplicationException("A credit-card charge failed.", e);
                }

                try {
                    var messageAndDestination = successHandler(response.Id, amountInDollars.Value);
                    if (messageAndDestination.Message.Any())
                    {
                        EwfPage.AddStatusMessage(StatusMessageType.Info, messageAndDestination.Message);
                    }
                    successDestination = messageAndDestination.Destination;
                }
                catch (Exception e) {
                    throw new ApplicationException("An exception occurred after a credit card was charged.", e);
                }
            });

            FormAction action = new PostBackFormAction(postBack);

            action.AddToPageIfNecessary();
            return(Tuple.Create <IReadOnlyCollection <EtherealComponent>, Func <string> >(
                       hiddenFields,
                       () => {
                var jsTokenHandler = "function( token, args ) { " + hiddenFieldId.GetJsValueModificationStatements("token.id") + " " + action.GetJsStatements() +
                                     " }";
                return "StripeCheckout.open( { key: '" + (ConfigurationStatics.IsLiveInstallation ? livePublishableKey : testPublishableKey) + "', token: " +
                jsTokenHandler + ", name: '" + name + "', description: '" + description + "', " +
                (amountInDollars.HasValue ? "amount: " + amountInDollars.Value * 100 + ", " : "") + "email: '" +
                (prefilledEmailAddressOverride ?? (AppTools.User == null ? "" : AppTools.User.Email)) + "' } )";
            }));
        }
コード例 #57
0
		/// <summary>
		/// Updates the queue with a data value or an error.
		/// </summary>
        public virtual void QueueValue(DataValue value, ServiceResult error, bool bypassFilter)
        {
            lock (m_lock)
			{
                // this method should only be called for variables. 
                if ((m_typeMask & MonitoredItemTypeMask.DataChange) == 0)
                {
                    throw new ServiceResultException(StatusCodes.BadInternalError);
                }

				// check monitoring mode.
				if (m_monitoringMode == MonitoringMode.Disabled)
				{
					return;
				}
                
                // make a shallow copy of the value.
                if (value != null)
                {
                    Utils.Trace("RECEIVED VALUE[{0}] Value={1}", this.m_id, value.WrappedValue);

                    DataValue copy = new DataValue();

                    copy.WrappedValue = value.WrappedValue;
                    copy.StatusCode = value.StatusCode;
                    copy.SourceTimestamp = value.SourceTimestamp;
                    copy.SourcePicoseconds = value.SourcePicoseconds;
                    copy.ServerTimestamp = value.ServerTimestamp;
                    copy.ServerPicoseconds = value.ServerPicoseconds;
                    
                    value = copy;

                    // ensure the data value matches the error status code.
                    if (error != null && error.StatusCode.Code != 0)
                    {
                        value.StatusCode = error.StatusCode;
                    }
                }

                // create empty value if none provided.
                if (ServiceResult.IsBad(error))
                {
                    if (value == null)
                    {
                        value = new DataValue();
                        value.StatusCode = error.StatusCode;
                        value.SourceTimestamp = DateTime.UtcNow;
                        value.ServerTimestamp = DateTime.UtcNow;
                    }
                }

                // this should never happen.
                if (value == null)
                {
                    return;
                }
                    			
                // apply aggregate filter.
                if (m_calculator != null)
                {
                    if (!m_calculator.QueueRawValue(value))
                    {
                        Utils.Trace("Value received out of order: {1}, ServerHandle={0}", m_id, value.SourceTimestamp.ToLocalTime().ToString("HH:mm:ss.fff"));
                    }

                    DataValue processedValue = m_calculator.GetProcessedValue(false);

                    while (processedValue != null)
                    {
                        AddValueToQueue(processedValue, null);
                        processedValue = m_calculator.GetProcessedValue(false);
                    }

					return;
                }
            	
				// apply filter to incoming item.
                if (!m_alwaysReportUpdates && !bypassFilter)
                {
                    if (!ApplyFilter(value, error))
                    {
                        ServerUtils.ReportFilteredValue(m_nodeId, m_id, value);
                        return;
                    }
                }
                
                ServerUtils.ReportQueuedValue(m_nodeId, m_id, value);

                // add the value to the queue.
                AddValueToQueue(value, error);
			}
        }
コード例 #58
0
ファイル: DataSet.cs プロジェクト: worksofbarry/NetRPG
        public DataValue ToDataValue()
        {
            DataValue result = null;

            switch (this._Type)
            {
            case Types.Ind:
                result = new Ind(this._Name, (string)this._InitialValue);
                break;

            case Types.Varying:
                result = new VaryingCharacter(this._Name, this._Length, (string)this._InitialValue);
                break;

            case Types.Character:
                result = new Character(this._Name, this._Length, (string)this._InitialValue);
                break;

            case Types.Int8:
            case Types.Int16:
            case Types.Int32:
            case Types.Int64:
                result = new Int(this._Name, this._Type, Convert.ToInt32(this._InitialValue));
                break;

            case Types.Structure:
                result = new Structure(this._Name, this._Qualified);
                break;

            case Types.FixedDecimal:     //Packed / Zoned
                result = new FixedDecimal(this._Name, this._Type, this._Precision, Convert.ToDouble(this._InitialValue));
                break;

            case Types.Float:
            case Types.Double:
                result = new Float(this._Name, this._Type, Convert.ToDouble(this._InitialValue));
                break;

            case Types.Timestamp:
                result = new Timestamp(this._Name, Convert.ToInt32(this._InitialValue));
                break;

            case Types.File:
                if (this._WorkStation)
                {
                    result = new Typing.Files.Display(this._Name, this._File, this._UserOpen);
                }
                else
                {
                    result = new Typing.Files.JSONTable(this._Name, this._File, this._UserOpen);
                }
                break;

            default:
                Error.ThrowRuntimeError("DataSet.ToDataValue", this._Type.ToString() + " is not a ready data type.");
                break;
            }

            if (this._DataArea != null)
            {
                result.SetDataAreaName(this._DataArea);
            }
            if (IsArray())
            {
                result.SetArray(this._Dimentions);
            }
            if (this._Type == Types.Structure && _Subfields != null)
            {
                result.SetSubfields(_Subfields.ToArray()); //Must be run after array size has been set
            }
            return(result);
        }
コード例 #59
0
ファイル: ComDaProxy.cs プロジェクト: OPCFoundation/UA-.NET
        /// <summary>
        /// Converts a StatusCode returned during a Write to an HRESULT.
        /// </summary>
        internal static int MapWriteStatusToErrorCode(DataValue value, StatusCode statusCode)
        {
            // map bad status codes.
            if (StatusCode.IsBad(statusCode))
            {
                switch (statusCode.Code)
                {
                    case StatusCodes.BadTypeMismatch: 
                    {
                        // server may reject a null value without checking the status code.
                        if (StatusCode.IsBad(value.StatusCode) && value.Value == null)
                        {
                            return ResultIds.E_NOTSUPPORTED;
                        }

                        return ResultIds.E_BADTYPE;
                    }

                    case StatusCodes.BadOutOfMemory: { return ResultIds.E_OUTOFMEMORY; }
                    case StatusCodes.BadNodeIdInvalid: { return ResultIds.E_INVALIDITEMID; }
                    case StatusCodes.BadNodeIdUnknown: { return ResultIds.E_UNKNOWNITEMID; }
                    case StatusCodes.BadNotWritable: { return ResultIds.E_BADRIGHTS; }
                    case StatusCodes.BadUserAccessDenied: { return ResultIds.E_ACCESSDENIED; }
                    case StatusCodes.BadAttributeIdInvalid: { return ResultIds.E_UNKNOWNITEMID; }
                    case StatusCodes.BadWriteNotSupported: { return ResultIds.E_NOTSUPPORTED; }
                    case StatusCodes.BadOutOfRange: { return ResultIds.E_RANGE; }
                }

                return ResultIds.E_FAIL;
            }

            // ignore uncertain and success codes.
            return ResultIds.S_OK;
        }
コード例 #60
0
 public void Add(DataValue dataValue)
 {
     _integerValues.Add(dataValue._name, dataValue._vals);
 }