Ejemplo n.º 1
0
        public virtual string GetProperty(string strPropertyName, string strFormat, System.Globalization.CultureInfo formatProvider, DotNetNuke.Entities.Users.UserInfo accessingUser, DotNetNuke.Services.Tokens.Scope accessLevel, ref bool propertyNotFound)
        {
            switch (strPropertyName.ToLower())
            {
            case "componentid": // Int
                return(ComponentId.ToString(strFormat, formatProvider));

            case "moduleid": // Int
                return(ModuleId.ToString(strFormat, formatProvider));

            case "componentname": // NVarChar
                return(PropertyAccess.FormatString(ComponentName, strFormat));

            case "latestversion": // VarChar
                return(PropertyAccess.FormatString(LatestVersion, strFormat));

            case "description": // NVarCharMax
                if (Description == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(Description, strFormat));

            default:
                propertyNotFound = true;
                break;
            }

            return(Null.NullString);
        }
Ejemplo n.º 2
0
        public void Serialize_and_Deserialize_SceneWithEntityWithComponentAccessingAssetStoreDuringSerialization()
        {
            // Arrange
            var entity = new Entity();
            var componentToSerialize = new AssetStoreTestComponent();

            entity.AddComponent(componentToSerialize);

            var scene = TestSceneFactory.Create();

            scene.AddEntity(entity);

            _componentFactoryProvider.Get(ComponentId.Of <AssetStoreTestComponent>()).Returns(new AssetStoreTestComponent.Factory());

            // Act
            var actual = SerializeAndDeserialize(scene);

            // Assert
            Assert.That(componentToSerialize.SerializeAssetStore, Is.EqualTo(_assetStore));
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.RootEntities, Has.Count.EqualTo(1));
            var actualEntity = actual.RootEntities.Single();

            Assert.That(actualEntity.Components, Has.Count.EqualTo(1));
            var deserializedComponent = actualEntity.Components.ElementAt(0);

            Assert.That(deserializedComponent, Is.TypeOf <AssetStoreTestComponent>());
            Assert.That(((AssetStoreTestComponent)deserializedComponent).DeserializeAssetStore, Is.EqualTo(_assetStore));
        }
Ejemplo n.º 3
0
        public bool AddSymbol(ComponentId dataSourceId, Symbol symbol, out string operationResultMessage)
        {
            if (_dataSourceId.HasValue && _dataSourceId.Value != dataSourceId)
            {
                operationResultMessage = "One source per watch component currently supported.";
                SystemMonitor.Error(operationResultMessage);
                return(false);
            }

            _dataSourceId = dataSourceId;
            if (_delivery == null)
            {
                _delivery = base.ObtainDataDelivery(_dataSourceId.Value);
            }

            RuntimeDataSessionInformation info = _delivery.GetSymbolRuntimeSessionInformation(symbol);

            if (info == null)
            {
                operationResultMessage = "Failed to obtain symbol runtime session information.";
                return(false);
            }

            _delivery.SubscribeToData(info.Info, true, new DataSubscriptionInfo(true, false, null));
            _delivery.QuoteUpdateEvent += new QuoteUpdateDelegate(delivery_QuoteUpdateEvent);

            operationResultMessage = string.Empty;
            return(true);
        }
Ejemplo n.º 4
0
        protected override bool ProcessSubComponent(CalendarComponentBase calendarComponent)
        {
            bool         result       = true;
            TimeZoneRule timeZoneRule = calendarComponent as TimeZoneRule;

            if (timeZoneRule != null)
            {
                ushort      year        = timeZoneRule.Year;
                ComponentId componentId = calendarComponent.ComponentId;
                if (componentId != ComponentId.Standard)
                {
                    if (componentId == ComponentId.Daylight)
                    {
                        if (this.daylightRules.ContainsKey(year))
                        {
                            ExTraceGlobals.ICalTracer.TraceError <ushort>(0L, "VTimeZone::ProcessSubComponent:ComponentId.Daylight. Ignoring the repeated year timezone definition. Year: {0}", year);
                        }
                        else
                        {
                            this.daylightRules.Add(year, timeZoneRule);
                        }
                    }
                }
                else if (this.standardRules.ContainsKey(year))
                {
                    ExTraceGlobals.ICalTracer.TraceError <ushort>(0L, "VTimeZone::ProcessSubComponent:ComponentId.Standard. Ignoring the repeated year timezone definition. Year: {0}", year);
                }
                else
                {
                    this.standardRules.Add(year, timeZoneRule);
                }
            }
            return(result);
        }
Ejemplo n.º 5
0
 public override void Dispose()
 {
     _dataSourceId          = ComponentId.Empty;
     _orderExectionSourceId = ComponentId.Empty;
     _manager = null;
     base.Dispose();
 }
        /// <summary>
        /// Get source orderInfo, by aplying filter, since more than one source may be on same id, but always from different type.
        /// </summary>
        /// <returns></returns>
        public SourceInfo?GetSourceInfo(ComponentId sourceId, SourceTypeEnum?filter)
        {
            if (sourceId == _dataStoreSourceInfo.ComponentId)
            {
                return(_dataStoreSourceInfo);
            }

            if (sourceId == _backtestingExecutionSourceInfo.ComponentId)
            {
                return(_backtestingExecutionSourceInfo);
            }

            SourcesUpdateMessage responce = this.SendAndReceive <SourcesUpdateMessage>(
                new GetSourceInfoMessage(sourceId));

            if (responce == null || responce.OperationResult == false ||
                responce.Sources.Count < 1)
            {
                return(null);
            }

            List <SourceTypeEnum> types = new List <SourceTypeEnum>();

            foreach (SourceInfo info in responce.Sources)
            {
                if (filter.HasValue == false || (info.SourceType & filter.Value) != 0)
                {
                    return(info);
                }
            }

            return(null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// the helper function to combine the trace string.
        /// </summary>
        /// <param name="componentName">Calling component ID</param>
        /// <param name="message">message to write to event</param>
        /// <param name="parameters">any parameters to place into the message</param>
        /// <returns>the combined trace string.</returns>
        private static string CombineTraceString(ComponentId componentName, string message, params object[] parameters)
        {
            string traceString = String.Format(CultureInfo.CurrentCulture, message, parameters);

            switch (componentName)
            {
            case ComponentId.XllConnector:
                return("[HpcXllConnector]: " + traceString);

            case ComponentId.XllContainer:
                return("[HpcXllContainer]: " + traceString);

            case ComponentId.ExcelDriver:
                return("[HpcExcelDriver]: " + traceString);

            case ComponentId.ExcelService:
                return("[HpcExcelService]: " + traceString);

            case ComponentId.ExcelClient:
                return("[HpcExcelClient]: " + traceString);

            default:
                return(traceString);
            }
        }
        /// <summary>
        /// Register ISourceDataDelivery.
        /// </summary>
        protected bool AddElement(ComponentId id, ISourceDataDelivery delivery)
        {
            if (id.IsEmpty || delivery == null)
            {
                SystemMonitor.Warning("Invalid Id or data delivery instance.");
                return(false);
            }

            lock (this)
            {
                if (_dataDeliveries.ContainsKey(id))
                {
                    SystemMonitor.Warning("Failed to add data delivery, since already added with this Id.");
                    return(false);
                }

                foreach (ComponentId deliveryId in _dataDeliveries.Keys)
                {
                    SystemMonitor.CheckThrow(id.Name.ToLower() == id.Name.ToLower(), "Data Delivery with this name Id already present [" + id.Name + "].");
                }

                _dataDeliveries.Add(id, delivery);
            }

            return(true);
        }
        /// <summary>
        /// Register IDataTickHistoryProvider.
        /// </summary>
        protected bool AddElement(ComponentId id, Symbol symbol, IDataTickHistoryProvider provider)
        {
            if (id.IsEmpty || symbol.IsEmpty || provider == null)
            {
                SystemMonitor.Warning("Invalid Id, Symbol or quote provider instance.");
                return(false);
            }

            lock (this)
            {
                if (_dataTickProviders.ContainsKey(id) && _dataTickProviders[id].ContainsKey(symbol))
                {
                    SystemMonitor.Warning("Failed to add order execution provider, since already added with this Id.");
                    return(false);
                }

                if (_dataTickProviders.ContainsKey(id) == false)
                {
                    _dataTickProviders.Add(id, new Dictionary <Symbol, IDataTickHistoryProvider>());
                }

                _dataTickProviders[id].Add(symbol, provider);
            }

            return(true);
        }
Ejemplo n.º 10
0
        public RollerShutter(
            ComponentId id, 
            IRollerShutterEndpoint endpoint,
            ITimerService timerService,
            ISchedulerService schedulerService,
            ISettingsService settingsService)
            : base(id)
        {
            if (id == null) throw new ArgumentNullException(nameof(id));
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService));
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            _endpoint = endpoint;
            _schedulerService = schedulerService;

            settingsService.CreateSettingsMonitor<RollerShutterSettings>(Id, s => Settings = s);

            timerService.Tick += (s, e) => UpdatePosition(e);

            _startMoveUpAction = new Action(() => SetState(RollerShutterStateId.MovingUp));
            _turnOffAction = new Action(() => SetState(RollerShutterStateId.Off));
            _startMoveDownAction = new Action(() => SetState(RollerShutterStateId.MovingDown));

            endpoint.Stop(HardwareParameter.ForceUpdateState);
        }
        public LogicalBinaryStateActuator(ComponentId id, ITimerService timerService)
            : base(id)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));

            _timerService = timerService;
        }
Ejemplo n.º 12
0
        public void ComponentIdConstructorTest()
        {
            string      strComponentId = string.Empty; // TODO: 初始化为适当的值
            ComponentId target         = new ComponentId(strComponentId);

            Assert.Inconclusive("TODO: 实现用来验证目标的代码");
        }
Ejemplo n.º 13
0
 public override string ToString()
 {
     if (maxCapacity == 0)
     {
         return("0");
     }
     if (isReadOnly)
     {
         if (length == 0)
         {
             return(EMPTY.ToString());
         }
         StringBuilder sb  = new StringBuilder();
         ComponentId   cid = this.components[0];
         sb.Append(cid.ToString());
         for (int i = 1; i < length; i++)
         {
             cid = this.components[i];
             sb.Append(componentDelimeter);
             sb.Append(cid.ToString());
         }
         return(sb.ToString());
     }
     else
     {
         return(base.ToString());
     }
 }
        /// <summary>
        /// This method shows a few ways to perform calls.
        /// </summary>
        public void PerformCalls(ISuperPoolClient otherClient)
        {
            ISample otherSource = otherClient.Source as ISample;
            string  result;

            ComponentId recipientId = otherClient.Id;

            ComponentId[] recipientsIds = new ComponentId[] { otherClient.Id };

            AsyncCallResultDelegate asyncDelegate = delegate(ISuperPoolClient clientInstance, AsyncResultParams param)
            {
            };

            // Strongly Coupled Synchronous Invocation.
            // This is the typical, strong coupled way of communication, or invocation.
            result = otherSource.MyMethod(12);

            // Decoupled “DirectCall” Invocation (Very fast, Local only)
            // The closest invocation to the classical strongly coupled approach, this
            // method is very fast, synchronous, and loosely coupled.
            client.CallDirectLocal <ISample>(recipientId).MyMethod(12);

            // Decoupled Synchronous Invocation (Local and remote, Timeout configurable)
            client.CallSync <ISample>(recipientId).MyMethod(12);

            // Decoupled Asynchronous Invocation.
            client.Call <ISample>(recipientId).MyMethod(12);

            // Decoupled Asynchronous Invocation with Result.
            client.Call <ISample>(recipientId, asyncDelegate).MyMethod(12);

            // Decoupled Asynchronous Invocation to Multiple Receivers (Addressed or Non-addressed).
            client.Call <ISample>(recipientsIds).MyMethod(12); // Addressed
            client.CallAll <ISample>().MyMethod(12);           // Non-addressed
        }
Ejemplo n.º 15
0
 public static void BeforeClass(TestContext testContext)
 {
     componentId      = new ComponentId("Component1", 1, 0, 0, "none");
     componentContext = new DefaultComponentContext(componentId);
     icomponetFacet   = new IComponentServant(componentContext);
     icomponentType   = typeof(IComponent);
 }
Ejemplo n.º 16
0
        public void ComponentIdConstructorTest1()
        {
            long        lComponentId = 0; // TODO: 初始化为适当的值
            ComponentId target       = new ComponentId(lComponentId);

            Assert.Inconclusive("TODO: 实现用来验证目标的代码");
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Perform the actual call.
        /// </summary>
        protected TType DoCall <TType>(ComponentId receiverId, TimeSpan?requestConfirmTimeout,
                                       TimeSpan?timeout, AsyncCallResultDelegate asyncResultDelegate, object asyncResultState,
                                       TimeSpan?asyncResultTimeout, SuperPoolProxyCall.ModeEnum callMode, CallOutcome outcome)
            where TType : class
        {
            Matrix.Framework.SuperPool.Core.SuperPool pool = _superPool;
            if (pool == null)
            {
                return(null);
            }

            SuperPoolProxyCall proxyCall;
            TType result;

            if (pool.Call <TType>(this, receiverId, out result, out proxyCall) == false)
            {
                // Call failed.
                return(null);
            }

            proxyCall.AsyncResultDelegate = asyncResultDelegate;
            proxyCall.AsyncResultState    = asyncResultState;
            proxyCall.AsyncResultTimeout  = asyncResultTimeout;

            proxyCall.RequestConfirmTimeout = requestConfirmTimeout;
            proxyCall.Timeout = timeout;

            proxyCall.Mode    = callMode;
            proxyCall.Outcome = outcome;

            return(result);
        }
        public ComponentContext GetComponentContext(ComponentId componentId)
        {
            XmlNode componentContextNode =
                xmlComponent.GetElementsByTagName(COMPONENT_CONTEXT_ELEMENT)[0];

            if (componentContextNode == null)
            {
                return(null);
            }
            XmlNode context         = componentContextNode[COMPONENT_CONTEXT_TYPE];
            String  contextName     = context.InnerText;
            String  contextAssembly = context.Attributes[COMPONENT_CONTEXT_ASSEMBLY_ATTRIBUTE].InnerText;
            String  type            = contextName + ", " + contextAssembly;
            Type    contextType     = Type.GetType(type);

            if (contextType == null)
            {
                throw new SCSException(String.Format(
                                           "Não foi possível encontrar a classe '{0}'", type));
            }

            System.Reflection.ConstructorInfo constructor =
                contextType.GetConstructor(new Type[] { typeof(ComponentId) });
            if (constructor == null)
            {
                string errorMsg = "Implementação do componentContext deve possuir um" +
                                  "contrutor com um parametro do tipo 'ComponentId'";
                throw new SCSException(errorMsg);
            }
            return(constructor.Invoke(new Object[] { componentId }) as ComponentContext);
        }
        /// <summary>
        /// This method shows a few ways to perform calls.
        /// </summary>
        public void PerformCalls(ISuperPoolClient otherClient)
        {
            ISample otherSource = otherClient.Source as ISample;
            string result;

            ComponentId recipientId = otherClient.Id;
            ComponentId[] recipientsIds = new ComponentId[] { otherClient.Id };

            AsyncCallResultDelegate asyncDelegate = delegate(ISuperPoolClient clientInstance, AsyncResultParams param)
                                                        {
                                                        };

            // Strongly Coupled Synchronous Invocation.
            // This is the typical, strong coupled way of communication, or invocation.
            result = otherSource.MyMethod(12);

            // Decoupled “DirectCall” Invocation (Very fast, Local only)
            // The closest invocation to the classical strongly coupled approach, this
            // method is very fast, synchronous, and loosely coupled.
            client.CallDirectLocal<ISample>(recipientId).MyMethod(12);

            // Decoupled Synchronous Invocation (Local and remote, Timeout configurable)
            client.CallSync<ISample>(recipientId).MyMethod(12);

            // Decoupled Asynchronous Invocation.
            client.Call<ISample>(recipientId).MyMethod(12);

            // Decoupled Asynchronous Invocation with Result.
            client.Call<ISample>(recipientId, asyncDelegate).MyMethod(12);

            // Decoupled Asynchronous Invocation to Multiple Receivers (Addressed or Non-addressed).
            client.Call<ISample>(recipientsIds).MyMethod(12); // Addressed
            client.CallAll<ISample>().MyMethod(12); // Non-addressed
        }
        /// <summary>
        /// Get all sources that match the given criteria; multiple criteria can be combined in one sourceType
        /// using bitwise operators (for ex. operationResult = operationResult | SourceTypeEnum.Remote).
        /// </summary>
        /// <param name="sourceType"></param>
        /// <param name="partialMatch">Should we try to match filtering criteria fully or partially.</param>
        /// <returns></returns>
        public Dictionary <Symbol, TimeSpan[]> SearchSymbols(ComponentId sourceId, string symbolMatch)
        {
            if (IsLocalSource(sourceId))
            {
                ISourceDataDelivery delivery = ObtainDataDelivery(sourceId);
                return(delivery.SearchSymbols(symbolMatch));
            }

            List <ArbiterClientId?> sourcePath;

            if (GetSourcePath(sourceId, out sourcePath) == false)
            {
                SystemMonitor.OperationError("Failed to establish source path.");
                return(new Dictionary <Symbol, TimeSpan[]>());
            }

            RequestSymbolsMessage request = new RequestSymbolsMessage()
            {
                SymbolMatch = symbolMatch
            };
            ResponceMessage result = this.SendAndReceiveForwarding <ResponceMessage>(sourcePath, request);

            if (result != null && result.OperationResult)
            {
                return(((RequestSymbolsResponceMessage)result).SymbolsPeriods);
            }

            return(new Dictionary <Symbol, TimeSpan[]>());
        }
Ejemplo n.º 21
0
        private IComponent ParseStateMachine(XElement element)
        {
            var id = new ComponentId(element.GetMandatoryStringFromAttribute("id"));

            var stateMachine = new StateMachine(id);

            foreach (var stateElement in element.Element("States").Elements("State"))
            {
                var stateId = stateElement.GetMandatoryStringFromAttribute("id");
                var state   = stateMachine.AddState(new StatefulComponentState(stateId));

                foreach (var lowPortElement in stateElement.Element("LowPorts").Elements())
                {
                    state.WithOutput(Parser.ParseBinaryOutput(lowPortElement), BinaryState.Low);
                }

                foreach (var highPortElement in stateElement.Element("LowPorts").Elements())
                {
                    state.WithOutput(Parser.ParseBinaryOutput(highPortElement), BinaryState.High);
                }

                foreach (var actuatorElement in stateElement.Element("Actuators").Elements())
                {
                    var targetState = actuatorElement.GetMandatoryStringFromAttribute("targetState");
                    var actuatorId  = new ComponentId(actuatorElement.GetMandatoryStringFromAttribute("id"));
                    var actuator    = Controller.GetComponent <IStateMachine>(actuatorId);

                    state.WithActuator(actuator, new StatefulComponentState(targetState));
                }
            }

            return(stateMachine);
        }
Ejemplo n.º 22
0
            public override IDeepCopyable CopyTo(IDeepCopyable other)
            {
                var dest = other as ProductionSpecificationComponent;

                if (dest != null)
                {
                    base.CopyTo(dest);
                    if (SpecType != null)
                    {
                        dest.SpecType = (Hl7.Fhir.Model.CodeableConcept)SpecType.DeepCopy();
                    }
                    if (ComponentId != null)
                    {
                        dest.ComponentId = (Hl7.Fhir.Model.Identifier)ComponentId.DeepCopy();
                    }
                    if (ProductionSpecElement != null)
                    {
                        dest.ProductionSpecElement = (Hl7.Fhir.Model.FhirString)ProductionSpecElement.DeepCopy();
                    }
                    return(dest);
                }
                else
                {
                    throw new ArgumentException("Can only copy to an object of the same type", "other");
                }
            }
Ejemplo n.º 23
0
 public void ValueTest()
 {
     ComponentId target = new ComponentId(); // TODO: 初始化为适当的值
     long actual;
     actual = target.Value;
     Assert.Inconclusive( "验证此测试方法的正确性。" );
 }
Ejemplo n.º 24
0
 /// <summary>
 ///
 /// </summary>
 public virtual void Dispose()
 {
     _manager           = null;
     _executionProvider = null;
     _quoteProvider     = null;
     _dataSourceId      = ComponentId.Empty;
 }
        public TestHumiditySensor(ComponentId id, ISettingsService settingsService, TestNumericValueSensorEndpoint endpoint)
            : base(id, settingsService, endpoint)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));

            Endpoint = endpoint;
        }
Ejemplo n.º 26
0
        public TestRollerShutter(ComponentId id, TestRollerShutterEndpoint endpoint, ITimerService timerService, ISchedulerService schedulerService, ISettingsService settingsService)
            : base(id, endpoint, timerService, schedulerService, settingsService)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));

            Endpoint = endpoint;
        }
Ejemplo n.º 27
0
        public Window(ComponentId id, ISettingsService settingsService)
            : base(id)
        {
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            settingsService.CreateSettingsMonitor<ComponentSettings>(Id, s => Settings = s);
        }
Ejemplo n.º 28
0
        protected virtual void client_OperationalStateChangedEvent(IOperational operational, OperationalStateEnum previousOperationState)
        {
            lock (this)
            {
                if (this.client != null && !this.SessionCheckBox.Enabled)
                {
                    if (this.client.IsOperational)
                    {
                        this.ConnectCheckBox.Invoke(new SetControlBoolValue(this.SetControlChecked), this.ConnectCheckBox, true);

                        TransportInfo ti = this.client.ProxyTransportInfo;

                        if (this.platform.RegisterSource(
                                new SourceInfo(
                                    SourceTypeEnum.HighPriorityLiveFullProvider,
                                    ti)
                                ))
                        {
                            this.Message = "Client Proxy connected";

                            this.clientID = ti.OriginalSenderId.Value.Id;
                            this.client.OperationalStateChangedEvent -= new OperationalStateChangedDelegate(client_OperationalStateChangedEvent);

                            this.Invoke(new SetControlBoolValue(this.SetControlEnable), this.URLTextBox, false);
                            this.Invoke(new SetControlBoolValue(this.SetControlEnable), this.ExpertNameTextBox, false);
                            this.Invoke(new SetControlBoolValue(this.SetControlEnable), this.SessionCheckBox, true);
                        }
                    }
                }
            }
        }
        public void buildTest1()
        {
            ComponentId      componetId = new ComponentId("Test1", 1, 0, 0, ".Net FrameWork 3.5");
            ComponentContext expected   = new DefaultComponentContext(componetId);

            String             name          = "IComponent_1";
            String             interfaceName = "IDL:scs/core/IComponent:1.0";
            MarshalByRefObject servant       = new IComponentServant(expected);

            expected.AddFacet(name, interfaceName, servant);
            name          = "IComponent_2";
            interfaceName = "IDL:scs/core/IComponent:1.0";
            servant       = new IComponentServant(expected);
            expected.AddFacet(name, interfaceName, servant);
            name          = "IMetaInterface_3";
            interfaceName = "IDL:scs/core/IMetaInterface:1.0";
            servant       = new IMetaInterfaceServant(expected);
            expected.AddFacet(name, interfaceName, servant);

            String              componentModel       = Resources.Component1;
            TextReader          file                 = new StringReader(componentModel);
            XmlTextReader       componentInformation = new XmlTextReader(file);
            XmlComponentBuilder target               = new XmlComponentBuilder(componentInformation);
            ComponentContext    actual               = target.build();

            Assert.IsTrue(expected.Equals(actual));
        }
Ejemplo n.º 30
0
 public virtual int CompareTo(ComponentId that)
 {
     if (this.ValueType.Equals(that.ValueType) || this.ValueType.IsEquivalentTo(that.ValueType))
     {
         if (this.IdValue.Equals(that.IdValue))
         {
             return(0);
         }
         else
         {
             return(this.GetHashCode() - that.GetHashCode());
         }
     }
     else if (this.IdValue is IComparable)
     {
         return((this.IdValue as IComparable).CompareTo(that.IdValue));
     }
     else if (that.IdValue is IComparable)
     {
         return(-1 * (that.IdValue as IComparable).CompareTo(this.IdValue));
     }
     else
     {
         return(this.ValueType.GetHashCode() - that.ValueType.GetHashCode());
     }
 }
Ejemplo n.º 31
0
 public int CompareTo(Id that)
 {
     if (this.length > that.length)
     {
         return(1);
     }
     else if (this.length < that.length)
     {
         return(-1);
     }
     else
     {
         int compare = 0;
         for (int i = 0; i < length; i++)
         {
             ComponentId thisCid = this.components[i];
             ComponentId thatCid = that.components[i];
             compare = thisCid.CompareTo(thatCid);
             if (compare > 0)
             {
                 return(1);
             }
             else if (compare < 0)
             {
                 return(-1);
             }
         }
         return(compare);
     }
 }
        /// <summary>
        /// Faz um dump do component
        /// </summary>
        /// <param name="component"></param>
        private void DumpComponent(ComponentContext component)
        {
            ComponentId   componentId = component.GetComponentId();
            StringBuilder builder     = new StringBuilder();

            builder.AppendFormat("Componente {0}:{1}.{2}.{3} criado com sucesso.\n", componentId.name,
                                 componentId.major_version, componentId.minor_version, componentId.patch_version);

            IDictionary <String, Facet>      facets      = component.GetFacets();
            IDictionary <String, Receptacle> receptacles = component.GetReceptacles();

            if (facets.Count > 0)
            {
                builder.AppendLine("Facetas:");
            }
            foreach (Facet facet in facets.Values)
            {
                builder.AppendFormat("  {0} : {1}\n", facet.Name, facet.InterfaceName);
            }

            if (receptacles.Count > 0)
            {
                builder.AppendLine("Receptáculos:");
            }
            foreach (Receptacle receptacle in receptacles.Values)
            {
                builder.AppendFormat("  {0} : {1}\n", receptacle.Name, receptacle.InterfaceName);
            }
            logger.Info(builder.Remove(builder.Length - 1, 1));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Register IDataBarHistoryProvider.
        /// </summary>
        protected bool AddElement(ComponentId id, Symbol symbol, TimeSpan period, IDataBarHistoryProvider provider)
        {
            if (id.IsEmpty || provider == null || symbol.IsEmpty)
            {
                SystemMonitor.Warning("Invalid Id, symbol or quote provider instance.");
                return(false);
            }

            lock (_syncRoot)
            {
                if (_dataBarProviders.ContainsKey(id) && _dataBarProviders[id].ContainsKey(symbol) &&
                    _dataBarProviders[id][symbol].ContainsKey(period))
                {
                    SystemMonitor.Warning("Failed to add order execution provider, since already added with this Id.");
                    return(false);
                }

                if (_dataBarProviders.ContainsKey(id) == false)
                {
                    _dataBarProviders.Add(id, new Dictionary <Symbol, Dictionary <TimeSpan, IDataBarHistoryProvider> >());
                }

                if (_dataBarProviders[id].ContainsKey(symbol) == false)
                {
                    _dataBarProviders[id].Add(symbol, new Dictionary <TimeSpan, IDataBarHistoryProvider>());
                }

                _dataBarProviders[id][symbol].Add(period, provider);
            }

            return(true);
        }
Ejemplo n.º 34
0
        public RollerShutter(
            ComponentId id,
            IRollerShutterEndpoint endpoint,
            IHomeAutomationTimer timer,
            ISchedulerService schedulerService)
            : base(id)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (schedulerService == null)
            {
                throw new ArgumentNullException(nameof(schedulerService));
            }

            _endpoint         = endpoint;
            _timer            = timer;
            _schedulerService = schedulerService;

            timer.Tick += (s, e) => UpdatePosition(e);
            _settings   = new RollerShutterSettingsWrapper(Settings);

            _startMoveUpAction   = new Action(() => SetState(RollerShutterStateId.MovingUp));
            _turnOffAction       = new Action(() => SetState(RollerShutterStateId.Off));
            _startMoveDownAction = new Action(() => SetState(RollerShutterStateId.MovingDown));

            endpoint.Stop(HardwareParameter.ForceUpdateState);
        }
        /// <summary>
        /// Helper.
        /// </summary>
        protected bool GetSourcePath(ComponentId sourceId, out List <ArbiterClientId?> sourcePath)
        {
            SystemMonitor.CheckError(sourceId != _dataStoreSourceInfo.ComponentId, "Data store source has no path.");
            SystemMonitor.CheckError(sourceId != _backtestingExecutionSourceInfo.ComponentId, "Local execution source has no path.");

            sourcePath = null;
            SourcesUpdateMessage responce = this.SendAndReceive <SourcesUpdateMessage>(new GetSourceInfoMessage(sourceId));

            if (responce == null || responce.OperationResult == false)
            {
                return(false);
            }

            if (responce.Sources.Count > 0)
            {
                if (responce.Sources[0].TransportInfo != null)
                {
                    sourcePath = responce.Sources[0].TransportInfo.CreateRespondingClientList();
                }
                else
                {
                    sourcePath = null;
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 36
0
        public MotionDetector(ComponentId id, IMotionDetectorEndpoint endpoint, ISchedulerService schedulerService)
            : base(id)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (schedulerService == null)
            {
                throw new ArgumentNullException(nameof(schedulerService));
            }

            _schedulerService = schedulerService;

            SetState(MotionDetectorStateId.Idle);

            endpoint.MotionDetected     += (s, e) => UpdateState(MotionDetectorStateId.MotionDetected);
            endpoint.DetectionCompleted += (s, e) => UpdateState(MotionDetectorStateId.Idle);

            Settings.ValueChanged += (s, e) =>
            {
                if (e.SettingName == "IsEnabled")
                {
                    HandleIsEnabledStateChanged();
                }
            };
        }
Ejemplo n.º 37
0
        public TemperatureSensor(ComponentId id, ISettingsService settingsService, INumericValueSensorEndpoint endpoint)
            : base(id)
        {
            if (settingsService == null)
            {
                throw new ArgumentNullException(nameof(settingsService));
            }
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            settingsService.CreateSettingsMonitor <SingleValueSensorSettings>(Id, s => Settings = s);

            SetState(new ComponentState(0));

            endpoint.ValueChanged += (s, e) =>
            {
                // TODO: Create base class.
                if (!GetDifferenceIsLargeEnough(e.NewValue))
                {
                    return;
                }

                SetState(new ComponentState(e.NewValue));
            };
        }
        protected BinaryStateActuator(ComponentId id, IBinaryStateEndpoint endpoint)
            : base(id)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));

            AddState(new StateMachineState(BinaryStateId.Off).WithAction(endpoint.TurnOff));
            AddState(new StateMachineState(BinaryStateId.On).WithAction(endpoint.TurnOn));
        }
Ejemplo n.º 39
0
 /// <summary>
 /// 
 /// </summary>
 public PassiveOrder(ISourceManager manager, ComponentId dataSourceId, ComponentId orderExecutionSourceId)
 {
     SystemMonitor.CheckError(dataSourceId.IsEmpty == false && orderExecutionSourceId.IsEmpty == false, "Source Id not available to order.");
     _manager = manager;
     _dataSourceId = dataSourceId;
     _orderExectionSourceId = orderExecutionSourceId;
     _executionProvider = manager.ObtainOrderExecutionProvider(orderExecutionSourceId, dataSourceId);
 }
        public TestMotionDetector(ComponentId id, TestMotionDetectorEndpoint endpoint, ISchedulerService schedulerService, ISettingsService settingsService)
            : base(id, endpoint, schedulerService, settingsService)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService));

            Endpoint = endpoint;
        }
Ejemplo n.º 41
0
 public void ToStringTest()
 {
     ComponentId target = new ComponentId(); // TODO: 初始化为适当的值
     string expected = string.Empty; // TODO: 初始化为适当的值
     string actual;
     actual = target.ToString();
     Assert.AreEqual( expected, actual );
     Assert.Inconclusive( "验证此测试方法的正确性。" );
 }
        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        public PlatformSourceOrderExecutionProvider(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _tradeEntities = (TradeEntityKeeper)info.GetValue("tradeEntities", typeof(TradeEntityKeeper));
            _manager = (TradePlatformComponent)info.GetValue("manager", typeof(TradePlatformComponent));
            _dataSourced = (ComponentId)info.GetValue("dataSourceId", typeof(ComponentId));

            this.OperationalStateChangedEvent += new OperationalStateChangedDelegate(PlatformSourceOrderExecutionProvider_OperationalStateChangedEvent);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public BackTestOrderExecutionProvider(ComponentId sourceId)
        {
            _sourceId = sourceId;
            _sourceId.IdentifiedComponentType = typeof(BackTestOrderExecutionProvider);

            _account = new BackTestAccount(new AccountInfo(Guid.NewGuid(), _runningAccountBalance, 0,
                string.Empty, new Symbol("USD"), _runningAccountBalance, _runningAccountBalance, 100, _runningAccountBalance, "Simulation Account", string.Empty, 0, string.Empty));

            ChangeOperationalState(OperationalStateEnum.Constructed);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Constructor, allows direct order initialization.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param>
        public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider,
            ComponentId dataSourceId, bool initialize)
            : base(manager, executionProvider, dataSourceId)
        {
            State = OrderStateEnum.UnInitialized;

            if (initialize)
            {
                SystemMonitor.CheckThrow(Initialize());
            }
        }
 /// <summary>
 /// 
 /// </summary>
 public PositionExecutionInfo(string executionId, ComponentId dataSourceId, ComponentId executionSourceId,
     Symbol symbol, OrderTypeEnum orderType, decimal? price, int volumeRequest, int volumeExecuted, DateTime? time, ExecutionResultEnum result)
 {
     _executionId = executionId;
     _orderType = orderType;
     _dataSourceId = dataSourceId;
     _executionSourceId = executionSourceId;
     _symbol = symbol;
     _result = result;
     _executedPrice = price;
     _volumeRequested = volumeRequest;
     _volumeExecuted = volumeExecuted;
     _executionTime = time;
 }
 /// <summary>
 /// 
 /// </summary>
 public OrderExecutionSourceClientStub(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     ChangeOperationalState(OperationalStateEnum.Constructed);
     StatusSynchronizationEnabled = true;
     _sourceId = (ComponentId)info.GetValue("sourceId", typeof(ComponentId));
     try
     {
         _slippageMultiplicator = info.GetDecimal("slippageMultiplicator");
     }
     catch (SerializationException)
     {
         _slippageMultiplicator = 1;
     }
 }
Ejemplo n.º 47
0
        public Button(ComponentId id, IButtonEndpoint endpoint, ITimerService timerService, ISettingsService settingsService)
            : base(id)
        {
            if (id == null) throw new ArgumentNullException(nameof(id));
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            settingsService.CreateSettingsMonitor<ButtonSettings>(Id, s => Settings = s);

            SetState(ButtonStateId.Released);

            timerService.Tick += CheckForTimeout;

            endpoint.Pressed += (s, e) => HandleInputStateChanged(ButtonStateId.Pressed);
            endpoint.Released += (s, e) => HandleInputStateChanged(ButtonStateId.Released);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Constructor, allows direct order initialization.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param>
        public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider,
            IQuoteProvider quoteProvider, ComponentId dataSourceId, Symbol symbol, bool initialize)
        {
            _manager = manager;
            _symbol = symbol;

            _dataSourceId = dataSourceId;

            _executionProvider = executionProvider;
            _quoteProvider = quoteProvider;

            State = OrderStateEnum.UnInitialized;

            if (initialize)
            {
                SystemMonitor.CheckThrow(Initialize());
            }
        }
Ejemplo n.º 49
0
        public HumiditySensor(ComponentId id, ISettingsService settingsService, INumericValueSensorEndpoint endpoint)
            : base(id)
        {
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));

            settingsService.CreateSettingsMonitor<SingleValueSensorSettings>(Id, s => Settings = s);

            SetState(new ComponentState(0));

            endpoint.ValueChanged += (s, e) =>
            {
                if (!GetDifferenceIsLargeEnough(e.NewValue))
                {
                    return;
                }

                SetState(new ComponentState(e.NewValue));
            };
        }
Ejemplo n.º 50
0
        public MotionDetector(ComponentId id, IMotionDetectorEndpoint endpoint, ISchedulerService schedulerService, ISettingsService settingsService)
            : base(id)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService));
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            _schedulerService = schedulerService;

            settingsService.CreateSettingsMonitor<MotionDetectorSettings>(Id, s => Settings = s);

            SetState(MotionDetectorStateId.Idle);

            endpoint.MotionDetected += (s, e) => UpdateState(MotionDetectorStateId.MotionDetected);
            endpoint.DetectionCompleted += (s, e) => UpdateState(MotionDetectorStateId.Idle);

            Settings.ValueChanged += (s, e) =>
            {
                if (e.SettingName == nameof(Settings.IsEnabled))
                {
                    HandleIsEnabledStateChanged();
                }
            };
        }
        public bool SetInitialParameters(ISourceManager manager, ComponentId sourceSourceId, ExpertSession session)
        {
            _manager = manager;

            _sessionInfo = session.Info;

            _sourceDataDelivery = manager.ObtainDataDelivery(sourceSourceId);
            //_sourceDataDelivery.OperationalStateChangedEvent += new OperationalStateChangedDelegate(_sourceDataDelivery_OperationalStateChangedEvent);

            StatusSynchronizationSource = _sourceDataDelivery;

            return true;
        }
        int OrderExecutionSourceStub.IImplementation.IsDataSourceSymbolCompatible(ComponentId dataSourceId, Symbol symbol)
        {
            if (_adapter != null && _adapter.DataSourceId.HasValue)
            {
                if (_adapter.DataSourceId.Value.Id == dataSourceId)
                {
                    return int.MaxValue;
                }
            }

            return 0;
        }
Ejemplo n.º 53
0
 protected SensorBase(ComponentId id)
     : base(id)
 {
 }
        public bool AddSymbol(ComponentId dataSourceId, Symbol symbol, out string operationResultMessage)
        {
            if (_dataSourceId.HasValue && _dataSourceId.Value != dataSourceId)
            {
                operationResultMessage = "One source per watch component currently supported.";
                SystemMonitor.Error(operationResultMessage);
                return false;
            }

            _dataSourceId = dataSourceId;
            if (_delivery == null)
            {
                _delivery = base.ObtainDataDelivery(_dataSourceId.Value);
            }

            RuntimeDataSessionInformation info = _delivery.GetSymbolRuntimeSessionInformation(symbol);
            if (info == null)
            {
                operationResultMessage = "Failed to obtain symbol runtime session information.";
                return false;
            }

            _delivery.SubscribeToData(info.Info, true, new DataSubscriptionInfo(true, false, null));
            _delivery.QuoteUpdateEvent += new QuoteUpdateDelegate(delivery_QuoteUpdateEvent);

            operationResultMessage = string.Empty;
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        public bool SetInitialParameters(ComponentId sourceId, TransportInfo sourceTransportInfo)
        {
            if (SourceTransportInfo != null)
            {
                SystemMonitor.OperationError("Already initialized.");
                return false;
            }

            SystemMonitor.CheckWarning(sourceId == sourceTransportInfo.OriginalSenderId.Value.Id, "Possible source mis match.");

            _sourceId = sourceId;

            if (base.SetRemoteStatusSynchronizationSource(sourceTransportInfo) == false)
            {
                return false;
            }

            return true;
        }
Ejemplo n.º 56
0
 public Socket(ComponentId id, IBinaryStateEndpoint endpoint)
     : base(id, endpoint)
 {
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Obtain component reference from its arbiter client subscription Id.
        /// </summary>
        /// <param name="componentId"></param>
        /// <param name="provideUnInitializedComponents">Provide normal + uninitialized components.</param>
        /// <returns></returns>
        public PlatformComponent GetComponentByIdentification(ComponentId componentId, bool provideUnInitializedComponents)
        {
            PlatformComponent component = null;

            lock (this)
            {
                if (_components.ContainsKey(componentId) == false)
                {
                    return null;
                }

                component = _components[componentId];
            }

            if (provideUnInitializedComponents || component.IsArbiterInitialized)
            {
                return component;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Get the current operational state of a component.
        /// </summary>
        /// <param name="componentId"></param>
        /// <returns></returns>
        public OperationalStateEnum? GetComponentOperationalState(ComponentId id)
        {
            lock (this)
            {
                if (_components.ContainsKey(id))
                {
                    return _components[id].OperationalState;
                }
            }

            return null;
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Helper. Allows the un registering of component from the platform, without direct referencing.
        /// </summary>
        public bool UnInitializeComponentByIdentification(ComponentId componentId)
        {
            // For un init, only check the components initialized.
            PlatformComponent component = GetComponentByIdentification(componentId, false);
            if (component == null)
            {
                SystemMonitor.Warning("Component not found.");
                return false;
            }

            this.UnInitializeComponent(component);
            return true;
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Helper. Allows the un registering of component from the platform, without direct referencing.
        /// </summary>
        public bool UnRegisterComponentByIdentification(ComponentId componentId)
        {
            // For unregistration look into all components, not only initialized.
            PlatformComponent component = GetComponentByIdentification(componentId, true);
            if (component == null)
            {
                //SystemMonitor.Warning("Component not found.");
                return false;
            }

            return this.UnRegisterComponent(component);
        }