Esempio n. 1
0
 private void StoreRelation()
 {
     using (IDataOperation operation = relationStorage.GetOperation())
     {
         operation.Store(CurrentItem);
     }
 }
Esempio n. 2
0
 /// <summary>
 /// Adds a link
 /// </summary>
 /// <param name="NewLink">The link</param>
 public virtual void AddLink(ILink NewLink)
 {
     if (NewLink.SourceComponent == this)
     {
         for (int iNewDO = 0; iNewDO < NewLink.DataOperationsCount; iNewDO++)
         {
             IDataOperation newDataOperation = NewLink.GetDataOperation(iNewDO);
             foreach (ILink link in _providingLinks)
             {
                 for (int iExistingDO = 0; iExistingDO < link.DataOperationsCount; iExistingDO++)
                 {
                     IDataOperation existingDataOperation = link.GetDataOperation(iExistingDO);
                     if (newDataOperation == existingDataOperation)
                     {
                         Event warning = new Event(EventType.Warning);
                         warning.Description = "DataOperation " + newDataOperation.ID + " has already been used. " +
                                               "It's argument values will overrule the values set previously for this operation.";
                         warning.Sender = this;
                         SendEvent(warning);
                     }
                 }
             }
         }
         _providingLinks.Add(NewLink);
     }
     if (NewLink.TargetComponent == this)
     {
         _acceptingLinks.Add(NewLink);
     }
 }
Esempio n. 3
0
 private void RetrieveRelation()
 {
     using (IDataOperation operation = relationStorage.GetOperation())
     {
         RelationItems = new ObservableCollection <ExemplaryItem>(operation.GetAll <ExemplaryItem>());
     }
 }
Esempio n. 4
0
        private void ExecuteDataOperation(MeterDataSet meterDataSet, DbAdapterContainer dbAdapterContainer)
        {
            IDataOperation dataOperation = null;

            try
            {
                // Create the data operation
                dataOperation = new openEASSandBoxOperation();

                // Provide system settings to the data operation
                ConnectionStringParser.ParseConnectionString(meterDataSet.ConnectionString, dataOperation);

                // Prepare for execution of the data operation
                dataOperation.Prepare(dbAdapterContainer);

                // Execute the data operation
                dataOperation.Execute(meterDataSet);

                // Load data from all data operations in a single transaction
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, GetTransactionOptions()))
                {
                    dataOperation.Load(dbAdapterContainer);
                    transactionScope.Complete();
                }
            }
            finally
            {
                // ReSharper disable once SuspiciousTypeConversion.Global
                if ((object)dataOperation != null)
                {
                    TryDispose(dataOperation as IDisposable);
                }
            }
        }
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="source">The Data Operation to copy</param>
 public DataOperation(IDataOperation source)
 {
     ID = source.ID;
     for (int i = 0; i < source.ArgumentCount; i++)
     {
         AddArgument(source.GetArgument(i));
     }
 }
Esempio n. 6
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="source">The Data Operation to copy</param>
 public DataOperation(IDataOperation source)
 {
     _id = source.ID;
     for (int i = 0; i < source.ArgumentCount; i++)
     {
         _arguments.Add(source.GetArgument(i));
     }
 }
Esempio n. 7
0
        public static T Execute <T>(this IDataOperation dataOperation, object parameters, T result)
        {
            if (dataOperation == null)
            {
                throw new ArgumentNullException("dataOperation");
            }
            var statementName = GetMethodNameFromRuntimeStack(2);

            return(dataOperation.Execute(statementName, parameters, result));
        }
        public T ExecuteNonQuery <T>(IDataOperation <T> op)
        {
            using (var cn = new SqlConnection(this.connectionString))
            {
                var cmd = op.ConstructCommand(cn);
                cn.Open();

                int rc = cmd.ExecuteNonQuery();

                T result = op.Return(cmd, rc);

                cn.Close();
                return(result);
            }
        }
Esempio n. 9
0
    /// <summary>
    /// For a given combination of inputExchangeItem, outputExchangeItem and list of dataOperation 
    /// it is decided if the dataOperations constitutes a valid set seen from a spatial settings 
    /// point of view. 
    /// </summary>
    /// <param name="inputExchangeItem">The input exchange item</param>
    /// <param name="outputExchangeItem">The output exchange item</param>
    /// <param name="SelectedDataOperations">List of selected dataOperations</param>
 		public override bool IsValid(IInputExchangeItem inputExchangeItem, IOutputExchangeItem outputExchangeItem, IDataOperation[] SelectedDataOperations)
		{
			bool returnValue = true;
			bool methodAvaileble = false;
			ElementMapper elementMapper = new ElementMapper();

			foreach (string idString in elementMapper.GetIDsForAvailableDataOperations(outputExchangeItem.ElementSet.ElementType,inputExchangeItem.ElementSet.ElementType))
			{
				if (ID == idString)
				{
					methodAvaileble = true;
				}
			}
			if (!methodAvaileble)
			{
				return false;
			}

			// --- check that only one SpatialMapping dataoperation is selected. ---
			int numberOfSelectedSpatialMappingDataOperations = 0;
			foreach (IDataOperation dataOperation in SelectedDataOperations)
			{
				for (int i = 0; i < dataOperation.ArgumentCount; i++)
				{
					if (dataOperation.GetArgument(i).Key == "Type")
					{
						if (dataOperation.GetArgument(i).Value == "SpatialMapping")
						{
                            numberOfSelectedSpatialMappingDataOperations++;  //this counting is done to check if the same dataOpertion is added twise

							if (dataOperation.ID != ID) //the selected dataoperation must be this dataOperation
							{
								returnValue = false; //the selected dataoperation must be this 
							}
						}
					}
				}
			}

			if (numberOfSelectedSpatialMappingDataOperations > 1)
			{
				returnValue = false;
			}
			
			return returnValue;			
		}
Esempio n. 10
0
        /// <summary>
        /// Adds a data operation
        /// </summary>
        /// <param name="dataOperation">The data operation</param>
        public void AddDataOperation(IDataOperation dataOperation)
        {
            if (!(dataOperation is ICloneable))
            {
                // Data Operation can not be cloned, issue warning
                Event warning = new Event(EventType.Warning);
                warning.Description = "DataOperation " + dataOperation.ID + " can not be cloned yet!";
                warning.Sender      = _sourceComponent;
                _sourceComponent.SendEvent(warning);

                _dataOperations.Add(dataOperation);
            }
            else
            {
                _dataOperations.Add(((ICloneable)dataOperation).Clone());
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Adds a data operation
        /// </summary>
        /// <param name="dataOperation">The data operation</param>
        public void AddDataOperation(IDataOperation dataOperation)
        {
            if (!(dataOperation is ICloneable))
            {
                // Data Operation can not be cloned, issue warning
                // TODO: how to do this
                throw new System.NotImplementedException();
                //Event warning = new Event(EventType.Warning);
                //warning.Description = "DataOperation " + dataOperation.ID + " can not be cloned yet!";
                //warning.Sender = _sourceComponent;
                //_sourceComponent.SendEvent(warning);

                _dataOperations.Add(dataOperation);
            }
            else
            {
                _dataOperations.Add(((ICloneable)dataOperation).Clone());
            }
        }
        /// <summary>
        /// Asynchronously execute the given data operation expected to not return any values.
        /// </summary>
        /// <param name="op"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public async Task <T> ExecuteNonQueryAsync <T>(IDataOperation <T> op, TaskFactory <T> factory = null)
        {
            if (factory == null)
            {
                factory = new TaskFactory <T>();
            }

            using (var cn = new SqlConnection(this.connectionString))
            {
                var cmd = op.ConstructCommand(cn);
                cn.Open();

                int rc = await cmd.ExecuteNonQueryAsync();

                T result = op.Return(cmd, rc);

                cn.Close();
                return(result);
            }
        }
Esempio n. 13
0
        private void ExecuteDataOperation(MeterDataSet meterDataSet)
        {
            IDataOperation dataOperation = null;

            try
            {
                // Create the data operation
                dataOperation = new openEASSandBoxOperation();

                // Provide system settings to the data operation
                ConnectionStringParser.ParseConnectionString(meterDataSet.ConnectionString, dataOperation);

                // Execute the data operation
                dataOperation.Execute(meterDataSet);
            }
            finally
            {
                // ReSharper disable once SuspiciousTypeConversion.Global
                if ((object)dataOperation != null)
                {
                    TryDispose(dataOperation as IDisposable);
                }
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="source">The Data Operation to copy</param>
 public DataOperation(IDataOperation source)
 {
     ID = source.ID;
     for (int i=0;i<source.ArgumentCount;i++)
         AddArgument(source.GetArgument(i));
 }
Esempio n. 15
0
        /// <summary>
        /// Constructs a new <see cref="PropertyManager">PropertyManager</see> from <c>object</c>
        /// of known type.
        /// </summary>
        /// <param name="obj">Object of known type.</param>
        /// <param name="allReadOnly">If true, all properties are readonly.</param>
        /// <returns>Returns new <see cref="PropertyManager">PropertyManager</see>
        /// or <c>null</c> if object's type isn't known.</returns>
        /// <remarks>A this time this method knowns following types:
        /// <list>
        /// <item><see cref="IQuantity">IQuantity</see></item>
        /// <item><see cref="IElementSet">IElementSet</see></item>
        /// <item><see cref="IDataOperation">IDataOperation</see></item>
        /// <item><see cref="ILinkableComponent">ILinkableComponent</see></item>
        /// </list>
        /// Method saves <c>obj</c> parameter to <see cref="Tag">Tag</see> property, but you can
        /// use it for any purpose.
        /// </remarks>
        public static PropertyManager ConstructPropertyManager(object obj, bool allReadOnly)
        {
            PropertyManager prop = null;

            if (obj is IQuantity)
            {
                IQuantity quantity = (IQuantity)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("Description", quantity.Description, true, "Description of this Quantity.", "General");
                prop.SetProperty("ID", quantity.ID, true, "ID of this Quantity.", "General");
                prop.SetProperty("ValueType", quantity.ValueType.ToString(), true, "Type of this Quantity's value.", "General");

                // Dimensions
                prop.SetProperty("AmountOfSubstance", quantity.Dimension.GetPower(DimensionBase.AmountOfSubstance).ToString(), true, "The amount of substance in mole.", "Dimensions");
                prop.SetProperty("Currency", quantity.Dimension.GetPower(DimensionBase.Currency).ToString(), true, "Currency in Euro.", "Dimensions");
                prop.SetProperty("ElectricCurrent", quantity.Dimension.GetPower(DimensionBase.ElectricCurrent).ToString(), true, "Electric current in ampere.", "Dimensions");
                prop.SetProperty("Length", quantity.Dimension.GetPower(DimensionBase.Length).ToString(), true, "Length in meter.", "Dimensions");
                prop.SetProperty("LuminousIntensity", quantity.Dimension.GetPower(DimensionBase.LuminousIntensity).ToString(), true, "Luminous intensity in candela.", "Dimensions");
                prop.SetProperty("Mass", quantity.Dimension.GetPower(DimensionBase.Mass).ToString(), true, "Mass in kilogram.", "Dimensions");
                prop.SetProperty("Temperature", quantity.Dimension.GetPower(DimensionBase.Temperature).ToString(), true, "Temperature in kelvin.", "Dimensions");
                prop.SetProperty("Time", quantity.Dimension.GetPower(DimensionBase.Time).ToString(), true, "Time in second.", "Dimensions");

                // Unit
                prop.SetProperty("ConversionFactorToSI", quantity.Unit.ConversionFactorToSI.ToString(), true, "Multiplicative coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("OffSetToSI", quantity.Unit.OffSetToSI.ToString(), true, "Additive coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("UnitDescription", quantity.Unit.Description, true, "Description of this unit.", "Unit");
                prop.SetProperty("UnitID", quantity.Unit.ID, true, "ID of this unit.", "Unit");
            }
            else if (obj is IElementSet)
            {
                IElementSet elementSet = (IElementSet)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("ID", elementSet.ID, true, "ID of this ElementSet", "General");
                prop.SetProperty("Version", elementSet.Version.ToString(), true, "Version of this ElementSet.", "General");
                prop.SetProperty("SpatialReferenceID", elementSet.SpatialReference.ID, true, "ID of this ElementSet's SpatialReference", "General");
                prop.SetProperty("Description", elementSet.Description, true, "Description of this ElementSet.", "General");
                prop.SetProperty("ElementCount", elementSet.ElementCount.ToString(), true, "Count of elements of this ElementSet.", "General");
                prop.SetProperty("ElementType", elementSet.ElementType.ToString(), true, "Type of elements in this ElementSet.", "General");
            }
            else if (obj is IDataOperation)
            {
                IDataOperation dataOperation = (IDataOperation)obj;
                prop = new PropertyManager();

                string DataOperationID = "DataOperationID";

                // small trick to avoid that some argument's name is same as DataOperationID.
                // it's not quite pure, but it works:-)
                bool conflict;
                do
                {
                    conflict = false;
                    for (int i = 0; i < dataOperation.ArgumentCount; i++)
                    {
                        if (dataOperation.GetArgument(i).Key == DataOperationID)
                        {
                            DataOperationID += " ";
                            conflict         = true;
                            break;
                        }
                    }
                }while(conflict);

                // General
                prop.SetProperty(DataOperationID, dataOperation.ID, true, "ID of this DataOperation", "General");

                // Arguments
                for (int i = 0; i < dataOperation.ArgumentCount; i++)
                {
                    IArgument arg = dataOperation.GetArgument(i);
                    prop.SetProperty(arg.Key, arg.Value, arg.ReadOnly || allReadOnly, arg.Description, "Arguments");
                }
            }
            else if (obj is ILinkableComponent)
            {
                ILinkableComponent linkableComponent = (ILinkableComponent)obj;
                prop = new PropertyManager();

                DateTime
                    timeHorizonStart  = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.Start.ModifiedJulianDay),
                    timeHorizonEnd    = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.End.ModifiedJulianDay),
                    earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.EarliestInputTime.ModifiedJulianDay);

                // General
                prop.SetProperty("ComponentID", linkableComponent.ComponentID, true, "ID the component.", "General");
                prop.SetProperty("ComponentDescription", linkableComponent.ComponentDescription, true, "Description of this component.", "General");
                prop.SetProperty("InputExchangeItemCount", linkableComponent.InputExchangeItemCount.ToString(), true, "Number of input exchange items.", "General");
                prop.SetProperty("OutputExchangeItemCount", linkableComponent.OutputExchangeItemCount.ToString(), true, "Number of output exchange items.", "General");
                prop.SetProperty("ModelID", linkableComponent.ModelID, true, "ID of the model (model=component+data).", "General");
                prop.SetProperty("ModelDescription", linkableComponent.ModelDescription, true, "Description of the model.", "General");
                prop.SetProperty("TimeHorizonStart", timeHorizonStart.ToString(), true, "Start of component's timehorizon.", "General");
                prop.SetProperty("TimeHorizonEnd", timeHorizonEnd.ToString(), true, "End of component's timehorizon.", "General");
                prop.SetProperty("ValidationMessage", linkableComponent.Validate(), true, "Validation string generated by component. No error ocured if it's empty.", "General");
                prop.SetProperty("EarliestInputTime", earliestInputTime.ToString(), true, "Earliest time for which component needs next input.", "General");

                string implementsIManageState = obj is IManageState ? "yes" : "no";
                prop.SetProperty("ImplementsIManageState", implementsIManageState, true, "Describes whether model implements IManageState interface.", "General");
            }

            if (prop != null)
            {
                prop.Tag = obj;
            }

            return(prop);
        }
		/// <summary>
		/// Sets which one Quantity, one ElementSet and some DataOperations are currently checked.
		/// </summary>
		/// <param name="elementSet">ElementSet</param>
		/// <param name="quantity">Quantity</param>
		/// <param name="selectedDataOperations">Array of DataOperations which will be checked. If null no one will be checked.</param>.
		/// <remarks>Only one Quantity and one ElementSet can be checked at the time. DataOperations
		/// corresponding to Quantity->ElementSet exchange item can be checked as needed,
		/// all other cannot be checked.</remarks>
		public void SetCheckedExchangeItem( IQuantity quantity, IElementSet elementSet, IDataOperation[] selectedDataOperations )
		{
			ClearCheckboxes(); 

			if( quantity==null )
				return;

			treeView1.BeginUpdate();

			// note: we don't have to set _checked... members here,
			// because treeView1_AfterCheck event handler will do it

			// check Quantity (if any matching)
			for( int i = 0; i < treeView1.Nodes.Count; i++ )
				if( treeView1.Nodes[i].Text == quantity.ID )
				{
					treeView1.Nodes[i].Checked = true;
					
					// check ElementSet (if any matching)
					if( elementSet!=null )
						for( int j = 0; j < treeView1.Nodes[i].Nodes.Count; j++ )
							if( treeView1.Nodes[i].Nodes[j].Text == elementSet.ID )
							{
								treeView1.Nodes[i].Nodes[j].Checked = true;
								
								// check selected data operations (if any matching)
								if( selectedDataOperations != null )
								{
									foreach( IDataOperation dataOperation in selectedDataOperations )
										for( int k=0; k<treeView1.Nodes[i].Nodes[j].Nodes.Count; k++ )
											if( treeView1.Nodes[i].Nodes[j].Nodes[k].Text == dataOperation.ID )
											{
												treeView1.Nodes[i].Nodes[j].Nodes[k].Checked = true;												
											}
								}

								//goto Finish;
								break;
							}
					//goto Finish;
					break;
				}

			//Finish:

			treeView1.EndUpdate();
		}
Esempio n. 17
0
        /// <summary>
        /// Checks whether the current data operation is valid for the combination of
        /// input and output exchange items
        /// </summary>
        /// <param name="inputExchangeItem">The input exchange item</param>
        /// <param name="outputExchangeItem">The output exchange item</param>
        /// <param name="SelectedDataOperations">The selected data operations</param>
        /// <returns>True if the data operation is valid</returns>
        public virtual bool IsValid(IInputExchangeItem inputExchangeItem,IOutputExchangeItem outputExchangeItem,
			IDataOperation[] SelectedDataOperations)
        {
            return true;
        }
Esempio n. 18
0
		/// <summary>
		/// Adds a data operation
		/// </summary>
		/// <param name="dataOperation">The data operation</param>
		public void AddDataOperation (IDataOperation dataOperation)
		{
			if ( ! (dataOperation is ICloneable ) )
			{
				// Data Operation can not be cloned, issue warning
				Event warning = new Event(EventType.Warning);
				warning.Description = "DataOperation " + dataOperation.ID + " can not be cloned yet!";
				warning.Sender = _sourceComponent;
				_sourceComponent.SendEvent(warning);

				_dataOperations.Add(dataOperation);
			}
			else
			{
				_dataOperations.Add(((ICloneable)dataOperation).Clone());
			}
		}
Esempio n. 19
0
            public bool IsValid(IInputExchangeItem inputExchangeItem, IOutputExchangeItem outputExchangeItem,
			                    IDataOperation[] SelectedDataOperations)
            {
                throw new NotImplementedException();
            }
Esempio n. 20
0
 public PaymentService(IDataOperation dataOperation)
 {
     _dataOperation = dataOperation;
 }
Esempio n. 21
0
 public DataOperationContext(IDataOperation dataOperation, IDictionary items) : base(items)
 {
     this.DataOperation = dataOperation;
 }
Esempio n. 22
0
        private void AddToBuffer(ILink link)
        {
            // ----------------------------------------------------------------------------------------------------
            // The method adds values associated with the link.source to a SmartBuffer.
            // ----------------------------------------------------------------------------------------------------

            //dictionary of values indexed by their date\time
            SortedDictionary <DateTime, ArrayList> dict = new SortedDictionary <DateTime, ArrayList>();

            //create a buffer instance to temporarily store data
            SmartBuffer _smartBuffer = new SmartBuffer();

            //set the relaxation factor, if specifed in *.omi file.
            if (_relaxationFactor > 0)
            {
                _smartBuffer.RelaxationFactor = _relaxationFactor;
            }

            //get link.source quantity and elementset
            IQuantity   sourceQuantity   = link.SourceQuantity;
            IElementSet sourceElementSet = link.SourceElementSet;

            string sql = "SELECT DISTINCT ds.SeriesID " +
                         "FROM DataValues dv " +
                         "INNER JOIN DataSeries ds ON dv.SeriesID = ds.SeriesID " +
                         "INNER JOIN DataThemes dt ON dv.SeriesID = dt.SeriesID " +
                         "INNER JOIN Sites s ON ds.SiteID = s.SiteID " +
                         "INNER JOIN DataThemeDescriptions dtd On dt.ThemeID = dtd.ThemeID " +
                         "WHERE dtd.ThemeName = '" + sourceElementSet.ID.ToString() + "' " +
                         "ORDER BY s.SiteName ASC";

            DataTable tbl = _db.LoadTable("values", sql);

            //get the number of series' in this theme
            Dictionary <string, int> sites = new Dictionary <string, int>();

            //get the number of sites in this series
            int k = 0;

            foreach (DataRow row in tbl.Rows)
            {
                if (!sites.ContainsKey(Convert.ToString(row["SeriesID"])))
                {
                    sites.Add(Convert.ToString(row["SeriesID"]), k);
                    k++;
                }
            }


            //query the db for values associated with source quantity and elementset
            //TODO: LOOKUP BY THEMENAME, NOT THEMEID
            sql = "SELECT ds.SeriesID, dv.LocalDateTime, dv.DataValue " +
                  "FROM DataValues dv " +
                  "INNER JOIN DataSeries ds ON dv.SeriesID = ds.SeriesID " +
                  "INNER JOIN DataThemes dt ON dv.SeriesID = dt.SeriesID " +
                  "INNER JOIN DataThemeDescriptions dtd On dt.ThemeID = dtd.ThemeID " +
                  "WHERE dtd.ThemeName = '" + sourceElementSet.ID.ToString() + "' " +
                  "ORDER BY dv.LocalDateTime ASC";
            //"ORDER BY dv.DataValue ASC";

            tbl = _db.LoadTable("values", sql);

            //get the number of series' in this theme
            List <DateTime> t = new List <DateTime>();
            Dictionary <DateTime, double[]> Times = new Dictionary <DateTime, double[]>();

            //get the number of sites in this series
            //int k = 0;
            //foreach (DataRow row in tbl.Rows)
            //{
            //    if (!sites.ContainsKey(Convert.ToString(row["SeriesID"])))
            //    {
            //        sites.Add(Convert.ToString(row["SeriesID"]), k);
            //        k++;
            //    }

            //    if(!t.Contains(Convert.ToDateTime(row["LocalDateTime"])))
            //        t.Add(Convert.ToDateTime(row["LocalDateTime"]));
            //}
            //initialize a dictionary to hold the times and values
            foreach (DataRow row in tbl.Rows)
            {
                if (!Times.ContainsKey(Convert.ToDateTime(row["LocalDateTime"])))
                {
                    Times.Add(Convert.ToDateTime(row["LocalDateTime"]), new double[sites.Count]);
                }
            }
            //Times.OrderBy<pair,
            Times.OrderBy(pair => pair.Value);
            foreach (DataRow row in tbl.Rows)
            {
                double   v  = Convert.ToDouble(row["DataValue"]);
                string   id = Convert.ToString(row["SeriesID"]);
                DateTime dt = Convert.ToDateTime(row["LocalDateTime"]);
                Times[dt][sites[id]] = v;
            }


            for (int i = 0; i <= t.Count - 1; i++)
            {
                double[] vals = new double[sites.Count];
                DateTime dt   = t[i];
                foreach (DataRow row in tbl.Rows)
                {
                    double v  = Convert.ToDouble(row["DataValue"]);
                    string id = Convert.ToString(row["SeriesID"]);

                    //add v to vals in the location defined by its site id
                    vals[sites[id]] = v;
                }

                ArrayList a = new ArrayList();
                a.Add(vals);
                dict.Add(t[i], a);
            }
            ////check to see if time/value combination has been already added
            //if (dict.ContainsKey(dt))
            //{
            //    //if yes, add value to existing dictionary
            //    ArrayList a = dict[dt];
            //    a.Add(v);
            //}
            //else
            //{
            //    //if not, add value to new dictionary
            //    ArrayList a = new ArrayList();
            //    a.Add(v);
            //    dict.Add(dt, a);
            //}

            //double[] valueset = null;
            //ITimeStamp time_stmp = null;
            ////add dictionary to the smart buffer
            //foreach (KeyValuePair<DateTime, ArrayList> kvp in dict)
            //{
            //    time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //    valueset = (double[])kvp.Value.ToArray(typeof(double));
            //    _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            //}


            // //sort the dictionary
            //var sortDict = from keys in Times.Keys
            //           orderby Times[keys] ascending
            //           select keys;

            ////Times = (Dictionary<DateTime, double[]>)sortDict;

            //foreach (KeyValuePair<DateTime, double[]> kvp in Times.OrderBy(key => key.Value))
            //{

            //    time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //    valueset = kvp.Value;
            //    _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            //}

            //add dictionary to the smart buffer
            double[]   valueset  = null;
            ITimeStamp time_stmp = null;

            foreach (KeyValuePair <DateTime, double[]> kvp in Times)
            {
                time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
                valueset  = kvp.Value;
                _smartBuffer.AddValues(time_stmp, new ScalarSet(valueset));
            }

            //if ExactMatch is requested, then save the times for using in the GetValues method
            try
            {
                if (_exactMatch)
                {
                    List <double> times = new List <double>();
                    foreach (KeyValuePair <DateTime, double[]> kvp in Times)
                    {
                        time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
                        times.Add(time_stmp.ModifiedJulianDay);
                    }
                    _times.Add(link.ID, times);
                }
            }
            catch (Exception) { }

            ////if ExactMatch is requested, then save the times for using in the GetValues method
            //try
            //{
            //    if (_exactMatch)
            //    {
            //        List<double> times = new List<double>();
            //        foreach (KeyValuePair<DateTime, ArrayList> kvp in dict)
            //        {

            //            time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(kvp.Key));
            //            times.Add(time_stmp.ModifiedJulianDay);
            //        }
            //        _times.Add(link.ID, times);
            //    }
            //}
            //catch (Exception) { }

            //store the number of elements for this link
            _elementCount.Add(link.ID, valueset.Length);

            //store the lastest known time for this link
            _endTimes.Add(link.ID, (TimeStamp)time_stmp);
            //store the smart buffer based on linkID
            _buffer.Add(link.ID, _smartBuffer);

            //initialize the last index variable
            _lastIndex.Add(link.ID, 0);

            //adjust start time based on target component
            if (link.TargetComponent.TimeHorizon.Start.ModifiedJulianDay > this.EarliestInputTime.ModifiedJulianDay)
            {
                this._earliestInputTime = link.TargetComponent.TimeHorizon.Start.ModifiedJulianDay;
            }


            #region Initialize Element Mapper

            try
            {
                //get the first (stored) data operation
                IDataOperation dataOp = link.GetDataOperation(0);
                //get dataOperation description
                string dataOpDesc = dataOp.GetArgument(1).Value;
                //add a element mapper instance to the mapper dictionary
                mapper.Add(link.ID, new ElementMapper());
                //initialize the element mapper and create a mapping matrix
                mapper[link.ID].Initialise(dataOpDesc, link.SourceElementSet, link.TargetElementSet);
            }
            catch (Exception e) { }

            #endregion
        }
Esempio n. 23
0
    /// <summary>
    /// Redecalration of the overloaded constructor from the base class. 
    /// The redeclaration is probably needed since constructors can not be 
    /// marked as virtual.
    /// </summary>
    public DataOperation(IDataOperation source) : base(source)
		{
		}
		/// <summary>
		/// Adds a data operation.
		/// </summary>
		/// <param name="dataOperation">The data operation to be added</param>
		public void AddDataOperation(IDataOperation dataOperation)
		{
			_dataOperations.Add(dataOperation);
		}
Esempio n. 25
0
        public void UseCase02()
        {
            try
            {
                ILinkableComponent simpleRiver;
                simpleRiver = new Oatc.OpenMI.Examples.ModelComponents.SimpleRiver.Wrapper.SimpleRiverOpenMIComponent();
                Argument[] arguments = new Argument[1];
                arguments[0] = new Argument("FilePath", @"..\..\", true, "description");

                ILinkableComponent runoffLC = new RunoffDataLC();
                Oatc.OpenMI.Examples.TriggerComponents.SimpleTrigger.Trigger trigger = new Oatc.OpenMI.Examples.TriggerComponents.SimpleTrigger.Trigger();

                simpleRiver.Initialize(arguments);
                runoffLC.Initialize(new Argument[0]);
                trigger.Initialize(new Argument[0]);

                // --- DataOperations -----
                int dataOperationCount = runoffLC.GetOutputExchangeItem(0).DataOperationCount;
                int dataoperationIndex = -999;
                for (int i = 0; i < dataOperationCount; i++)
                {
                    for (int n = 0; n < runoffLC.GetOutputExchangeItem(0).GetDataOperation(i).ArgumentCount; n++)
                    {
                        if (runoffLC.GetOutputExchangeItem(0).GetDataOperation(i).GetArgument(n).Value == "Weighted Mean")
                        {
                            dataoperationIndex = i;
                        }
                    }
                }
                IDataOperation dataOperation = runoffLC.GetOutputExchangeItem(0).GetDataOperation(dataoperationIndex);

                ArrayList dataOperations = new ArrayList();
                dataOperations.Add(dataOperation);

                //-- Create links --
                Link runoffLCToSimpleRiverLink =
                    new Link(runoffLC,                                                            //source LinkableComponent
                             runoffLC.GetOutputExchangeItem(0).ElementSet,                        //source ElementSet
                             runoffLC.GetOutputExchangeItem(0).Quantity,                          //source Quantity
                             simpleRiver,                                                         //Target LinkableComponent
                             simpleRiver.GetInputExchangeItem(7).ElementSet,                      //target ElementSet
                             simpleRiver.GetInputExchangeItem(7).Quantity,                        //target Quantity
                             "runoffLCToSimpleRiverLink",                                         //linkID
                             "runoffLCToSimpleRiverLink Description",                             //link description
                             dataOperations);                                                     //dataOperations


                Link simpleRiverToTriggerLink =
                    new Link(simpleRiver,
                             simpleRiver.GetOutputExchangeItem(2).ElementSet,
                             simpleRiver.GetOutputExchangeItem(2).Quantity, trigger,
                             simpleRiver.GetOutputExchangeItem(2).ElementSet,
                             simpleRiver.GetOutputExchangeItem(2).Quantity,
                             "ID2");

                runoffLC.AddLink(runoffLCToSimpleRiverLink);
                simpleRiver.AddLink(runoffLCToSimpleRiverLink);

                simpleRiver.AddLink(simpleRiverToTriggerLink);
                trigger.AddLink(simpleRiverToTriggerLink);

                IListener eventListener = new Oatc.OpenMI.Examples.EventListeners.SimpleEventListener.EventListener();
                for (int i = 0; i < eventListener.GetAcceptedEventTypeCount(); i++)
                {
                    for (int n = 0; n < simpleRiver.GetPublishedEventTypeCount(); n++)
                    {
                        if (eventListener.GetAcceptedEventType(i) == simpleRiver.GetPublishedEventType(n))
                        {
                            simpleRiver.Subscribe(eventListener, eventListener.GetAcceptedEventType(i));
                        }
                    }
                    for (int n = 0; n < runoffLC.GetPublishedEventTypeCount(); n++)
                    {
                        if (eventListener.GetAcceptedEventType(i) == runoffLC.GetPublishedEventType(n))
                        {
                            runoffLC.Subscribe(eventListener, eventListener.GetAcceptedEventType(i));
                        }
                    }
                }

                simpleRiver.Prepare();
                runoffLC.Prepare();
                trigger.Prepare();

                double startTime = simpleRiver.TimeHorizon.Start.ModifiedJulianDay;

                Oatc.OpenMI.Sdk.Backbone.TimeStamp[] times = new Oatc.OpenMI.Sdk.Backbone.TimeStamp[5];
                times[0] = new TimeStamp(startTime + 1);
                times[1] = new TimeStamp(startTime + 2);
                times[2] = new TimeStamp(startTime + 3);
                times[3] = new TimeStamp(startTime + 4);
                times[4] = new TimeStamp(startTime + 5);

                trigger.Run(times);

//				Assert.AreEqual(3.8,((ScalarSet) trigger.ResultsBuffer.GetValuesAt(0)).data[0]);
                Assert.AreEqual(5.6 + 3 + 4.0 / 3.0, ((ScalarSet)trigger.ResultsBuffer.GetValuesAt(1)).data[0]);              //ts1
//				Assert.AreEqual(9.1,((ScalarSet) trigger.ResultsBuffer.GetValuesAt(2)).data[0]);
                Assert.AreEqual(8.6 + 3 + 4.0 / 3.0, ((ScalarSet)trigger.ResultsBuffer.GetValuesAt(3)).data[0]);              //ts2
//				Assert.AreEqual(12.1,((ScalarSet) trigger.ResultsBuffer.GetValuesAt(4)).data[0]);

                simpleRiver.Finish();
                runoffLC.Finish();
                trigger.Finish();
            }
            catch (System.Exception e)
            {
                Oatc.OpenMI.Examples.ExeptionHandlers.SimpleExceptionHandler.ExceptionHandler.WriteException(e);
                throw (e);
            }
        }
		/// <summary>
		/// Gets nodes of tree that are currently checked.
		/// </summary>
		/// <param name="quantity">Currently checked quantity or <c>null</c> if not checked.</param>
		/// <param name="elementSet">Currently checked elementSet or <c>null</c> if not checked.</param>
		/// <param name="selectedDataOperations">Currently checked data operations or <c>null</c> if no checked.</param>
		public void GetCheckedExchangeItem( out IQuantity quantity, out IElementSet elementSet, out IDataOperation[] selectedDataOperations )
		{
			quantity = _checkedQuantity;
			elementSet = _checkedElementSet;
			if( _checkedDataOperations==null )
				selectedDataOperations = null;
			else
				selectedDataOperations = (IDataOperation[])_checkedDataOperations.ToArray( typeof(IDataOperation) );
		}
Esempio n. 27
0
 public DataOperationContext(IDataOperation dataOperation, IDictionary items)
     : base(items)
 {
     this.DataOperation = dataOperation;
 }
Esempio n. 28
0
 /// <summary>
 /// Adds a data operation.
 /// </summary>
 /// <param name="dataOperation">The data operation to be added</param>
 public void AddDataOperation(IDataOperation dataOperation)
 {
     _dataOperations.Add(dataOperation);
 }
Esempio n. 29
0
        /// <summary>
        /// Loads composition from XML document.
        /// </summary>
        /// <param name="omiRelativeDirectory">Directory the OMI files are relative to.</param>
        /// <param name="xmlDocument">XML document</param>
        private void LoadFromXmlDocument(string omiRelativeDirectory, XmlDocument xmlDocument)
        {
            // once you choose to load new file, all previously opened models are closed
            Release();

            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = new CultureInfo("");


            XmlElement xmlRoot   = (XmlElement)xmlDocument.ChildNodes[0];
            XmlElement xmlModels = (XmlElement)xmlRoot.ChildNodes[0];
            XmlElement xmlLinks  = (XmlElement)xmlRoot.ChildNodes[1];

            // run properties aren't mandatory
            XmlElement xmlRunProperties = null;

            if (xmlRoot.ChildNodes.Count > 2)
            {
                xmlRunProperties = (XmlElement)xmlRoot.ChildNodes[2];
            }

            // check
            if (xmlRoot.GetAttribute("version") != "1.0")
            {
                throw (new FormatException("Version of file not supported. Currently supported only version '1.0'"));
            }
            if (xmlModels.Name != "models" ||
                xmlLinks.Name != "links")
            {
                throw (new FormatException("Unknown file format ('models' or 'links' tag not present where expected)."));
            }
            if (xmlRunProperties != null)
            {
                if (xmlRunProperties.Name != "runproperties")
                {
                    throw (new FormatException("Unknown file format ('runproperties' tag not present where expected)."));
                }
            }

            // read UIModels
            foreach (XmlElement xmlUiModel in xmlModels.ChildNodes)
            {
                try
                {
                    UIModel uiModel = AddModel(omiRelativeDirectory, xmlUiModel.GetAttribute("omi"));

                    uiModel.Rect.X      = Int32.Parse(xmlUiModel.GetAttribute("rect_x"));
                    uiModel.Rect.Y      = Int32.Parse(xmlUiModel.GetAttribute("rect_y"));
                    uiModel.Rect.Width  = Int32.Parse(xmlUiModel.GetAttribute("rect_width"));
                    uiModel.Rect.Height = Int32.Parse(xmlUiModel.GetAttribute("rect_height"));
                }
                catch (Exception e)
                {
                    throw (new Exception(
                               "Model cannot be added to composition due to exception.\n" +
                               "OMI filename: " + xmlUiModel.GetAttribute("omi") + "\n" +
                               "Exception: " + e.ToString()));
                }
            }

            // read UILinks
            foreach (XmlElement xmlUiLink in xmlLinks.ChildNodes)
            {
                // find models corresponding to this UIConnection
                UIModel providingModel = null, acceptingModel = null;
                foreach (UIModel uiModel in _models)
                {
                    if (uiModel.ModelID == xmlUiLink.GetAttribute("model_providing"))
                    {
                        providingModel = uiModel;
                        break;
                    }
                }
                foreach (UIModel uiModel in _models)
                {
                    if (uiModel.ModelID == xmlUiLink.GetAttribute("model_accepting"))
                    {
                        acceptingModel = uiModel;
                        break;
                    }
                }

                if (providingModel == null || acceptingModel == null)
                {
                    throw (new Exception(
                               "One model (or both) corresponding to this link cannot be found...\n" +
                               "Providing model: " + xmlUiLink.GetAttribute("model_providing") + "\n" +
                               "Accepting model: " + xmlUiLink.GetAttribute("model_accepting")));
                }

                // construct UIConnection
                UIConnection uiLink = new UIConnection(providingModel, acceptingModel);

                // read OpenMI Links
                foreach (XmlElement xmlLink in xmlUiLink.ChildNodes)
                {
                    // find corresponding exchange items
                    IOutputExchangeItem outputExchangeItem = null;
                    IInputExchangeItem  inputExchangeItem  = null;

                    int    count = providingModel.LinkableComponent.OutputExchangeItemCount;
                    string sourceElementSetID = xmlLink.GetAttribute("source_elementset");
                    string sourceQuantityID   = xmlLink.GetAttribute("source_quantity");
                    for (int i = 0; i < count; i++)
                    {
                        if (sourceElementSetID == providingModel.LinkableComponent.GetOutputExchangeItem(i).ElementSet.ID &&
                            sourceQuantityID == providingModel.LinkableComponent.GetOutputExchangeItem(i).Quantity.ID)
                        {
                            outputExchangeItem = providingModel.LinkableComponent.GetOutputExchangeItem(i);
                            break;
                        }
                    }

                    for (int i = 0; i < acceptingModel.LinkableComponent.InputExchangeItemCount; i++)
                    {
                        if (xmlLink.GetAttribute("target_elementset") == acceptingModel.LinkableComponent.GetInputExchangeItem(i).ElementSet.ID &&
                            xmlLink.GetAttribute("target_quantity") == acceptingModel.LinkableComponent.GetInputExchangeItem(i).Quantity.ID)
                        {
                            inputExchangeItem = acceptingModel.LinkableComponent.GetInputExchangeItem(i);
                            break;
                        }
                    }

                    if (outputExchangeItem == null || inputExchangeItem == null)
                    {
                        throw (new Exception(
                                   "Cannot find exchange item\n" +
                                   "Providing model: " + providingModel.ModelID + "\n" +
                                   "Accepting model: " + acceptingModel.ModelID + "\n" +
                                   "Source ElementSet: " + xmlLink.GetAttribute("source_elementset") + "\n" +
                                   "Source Quantity: " + xmlLink.GetAttribute("source_quantity") + "\n" +
                                   "Target ElementSet: " + xmlLink.GetAttribute("target_elementset") + "\n" +
                                   "Target Quantity: " + xmlLink.GetAttribute("target_quantity")));
                    }


                    // read selected DataOperation's IDs, find their equivalents
                    // in outputExchangeItem, and add these to link
                    ArrayList dataOperationsToAdd = new ArrayList();

                    foreach (XmlElement xmlDataOperation in xmlLink.ChildNodes)
                    {
                        for (int i = 0; i < outputExchangeItem.DataOperationCount; i++)
                        {
                            IDataOperation dataOperation = outputExchangeItem.GetDataOperation(i);
                            if (dataOperation.ID == xmlDataOperation.GetAttribute("id"))
                            {
                                // set data operation's arguments if any
                                foreach (XmlElement xmlArgument in xmlDataOperation.ChildNodes)
                                {
                                    string argumentKey = xmlArgument.GetAttribute("key");
                                    for (int j = 0; j < dataOperation.ArgumentCount; j++)
                                    {
                                        IArgument argument = dataOperation.GetArgument(j);
                                        if (argument.Key == argumentKey && !argument.ReadOnly)
                                        {
                                            argument.Value = xmlArgument.GetAttribute("value");
                                        }
                                    }
                                }

                                dataOperationsToAdd.Add(dataOperation);
                                break;
                            }
                        }
                    }

                    // now construct the Link...
                    Link link = new Link(
                        providingModel.LinkableComponent,
                        outputExchangeItem.ElementSet,
                        outputExchangeItem.Quantity,
                        acceptingModel.LinkableComponent,
                        inputExchangeItem.ElementSet,
                        inputExchangeItem.Quantity,
                        "No description available.",
                        xmlLink.GetAttribute("id"),
                        dataOperationsToAdd);


                    // ...add the link to the list
                    uiLink.Links.Add(link);

                    // and add it to both LinkableComponents
                    uiLink.AcceptingModel.LinkableComponent.AddLink(link);
                    uiLink.ProvidingModel.LinkableComponent.AddLink(link);
                }

                // add new UIConnection to list of connections
                _connections.Add(uiLink);
            }

            // read run properties (if present)
            if (xmlRunProperties != null)
            {
                string str = xmlRunProperties.GetAttribute("listenedeventtypes");
                if (str.Length != (int)EventType.NUM_OF_EVENT_TYPES)
                {
                    throw (new FormatException("Invalid number of event types in 'runproperties' tag, expected " + EventType.NUM_OF_EVENT_TYPES + ", but only " + str.Length + " found."));
                }
                for (int i = 0; i < (int)EventType.NUM_OF_EVENT_TYPES; i++)
                {
                    switch (str[i])
                    {
                    case '1': _listenedEventTypes[i] = true; break;

                    case '0': _listenedEventTypes[i] = false; break;

                    default: throw (new FormatException("Unknown format of 'listenedeventtypes' attribute in 'runproperties' tag."));
                    }
                }
                _triggerInvokeTime = DateTime.Parse(xmlRunProperties.GetAttribute("triggerinvoke"));

                _logFileName = xmlRunProperties.GetAttribute("logfilename");
                if (_logFileName != null)
                {
                    _logFileName = _logFileName.Trim();
                    if (_logFileName == "")
                    {
                        _logFileName = null; // if not set, logfile isn't used
                    }
                }


                str = xmlRunProperties.GetAttribute("showeventsinlistbox");
                if (str == null || str == "" || str == "1")
                {
                    _showEventsInListbox = true; // if not set, value is true
                }
                else
                {
                    _showEventsInListbox = false;
                }

                str = xmlRunProperties.GetAttribute("runinsamethread");
                if (str == "1")
                {
                    _runInSameThread = true;
                }
            }


            Thread.CurrentThread.CurrentCulture = currentCulture;
        }
Esempio n. 30
0
 public void AddDataOperation(IDataOperation dataOperation)
 {
     throw new NotImplementedException();
 }
Esempio n. 31
0
        public void LinearTimeInterpolation()
        {
            Console.Write("Begin Linear Interpolation Test...");

            //create the his component
            DbReader his = new DbReader();

            IArgument[] arguments = new IArgument[1];
            arguments[0] = new Argument("DbPath", @"..\data\cuahsi-his\demo.db", true, "Database");
            his.Initialize(arguments);

            //create a trigger component
            Trigger trigger = new Trigger();

            trigger.Initialize(null);

            //link the two components
            Link link = new Link();

            link.ID = "link-1";
            link.TargetElementSet = trigger.GetInputExchangeItem(0).ElementSet;
            link.TargetQuantity   = trigger.GetInputExchangeItem(0).Quantity;
            link.TargetComponent  = trigger;


            link.SourceElementSet = his.GetOutputExchangeItem(1).ElementSet;
            link.SourceQuantity   = his.GetOutputExchangeItem(1).Quantity;
            link.TargetComponent  = his;


            //Spatial interpolation
            IDataOperation dataOp = (his).GetOutputExchangeItem(0).GetDataOperation(7);

            link.AddDataOperation(dataOp);


            //run configuration
            his.AddLink(link);

            trigger.Validate();
            his.Validate();

            //prepare
            his.Prepare();

            DateTime dt = Convert.ToDateTime("2009-08-20T21:40:00");

            SmartBuffer _smartBuffer = new SmartBuffer();

            //Add all values to buffer in 10min intervals
            Console.Write("Storing values in the smart buffer (10min resolution)... ");
            while (dt <= Convert.ToDateTime("2009-08-21T02:00:00"))
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(dt));
                ScalarSet  scalarset = (ScalarSet)his.GetValues(time_stmp, "link-1");

                if (scalarset.Count == 0)
                {
                    int       f         = his.GetOutputExchangeItem(1).ElementSet.ElementCount;
                    ArrayList zeroArray = new ArrayList();
                    for (int i = 0; i <= f - 1; i++)
                    {
                        zeroArray.Add(0.0);
                    }

                    double[] zeros = (double[])zeroArray.ToArray(typeof(double));

                    scalarset = new ScalarSet(zeros);
                }

                _smartBuffer.AddValues(time_stmp, scalarset);

                dt = dt.AddMinutes(10);
            }
            Console.WriteLine("done.\n\n");

            //request values from the smart buffer at 5min intervals
            dt = Convert.ToDateTime("2009-08-20T21:40:00");
            while (dt <= Convert.ToDateTime("2009-08-21T02:00:00"))
            {
                ITimeStamp time_stmp = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(dt));

                //Get values at requested time
                ScalarSet scalarset = (ScalarSet)_smartBuffer.GetValues(time_stmp);

                Console.WriteLine("GetValues: " + dt.ToString("s"));


                //loop through interpolated values
                int i = 0;
                foreach (double d in scalarset.data)
                {
                    Console.WriteLine(link.SourceElementSet.GetElementID(i).ToString() + " " + d.ToString());
                    ++i;
                }
                dt = dt.AddMinutes(5);
            }

            Console.Write("done. \n");
        }
Esempio n. 32
0
 /// <summary>
 /// Redecalration of the overloaded constructor from the base class.
 /// The redeclaration is probably needed since constructors can not be
 /// marked as virtual.
 /// </summary>
 public DataOperation(IDataOperation source) : base(source)
 {
 }