public ComponentMetadata DisableComponent(int componentId)
        {
            ComponentMetadata rc = null;

            _logger.Log(string.Format("Attempting to disable component with id \"{0}\".", componentId));

            var type = GetComponentType(componentId);

            if (type.Key != null)
            {
                rc = type.Value;

                if (type.Value.UserActions.HasFlag(ComponentUserActions.Disable))
                {
                    if (!type.Value.IsDisabled)
                    {
                        StopRunnable(GetIRunnable(type.Key));
                        type.Value.IsDisabled = true;

                        _logger.Log(string.Format("Component with id \"{0}\" has been disabled.", type.Value.FriendlyName));
                    }
                    else
                    {
                        _logger.Log(string.Format("Component with id \"{0}\" has already been disabled.", type.Value.FriendlyName), LogMessageSeverity.Warning);
                    }
                }
                else
                {
                    _logger.Log(string.Format("Cannot disable component \"{0}\".", type.Value.FriendlyName), LogMessageSeverity.Warning);
                }
            }

            return(rc);
        }
Example #2
0
        /// <summary>
        /// Validates if all components exist in the library, and their mapping format.
        /// </summary>
        /// <param name="vertices">The vertices.</param>
        /// <returns>true if all components are in the library, false otherwise</returns>
        private static bool ValidComponents(List <ExperimentNode> vertices)
        {
            bool noErrors = true;

            //validate if all components are in the library
            foreach (ExperimentNode node in vertices)
            {
                ComponentMetadata componentMetadata = node.Data.Metadata as ComponentMetadata;
                if (componentMetadata != null)
                {
                    if (componentMetadata.ComponentMetadataDefinition == null)
                    {
                        noErrors = false;
                        string errorMessage = String.Format(System.Globalization.CultureInfo.CurrentCulture, "Component library does not contain any Component of the given ID {0}", componentMetadata.ComponentMetadataDefinitionID);
                        NLog.LogManager.GetCurrentClassLogger().Error(errorMessage);
                        node.SetError(errorMessage);
                    }
                    else
                    {
                        //if component exist check also output mapping formats
                        string errorMessage;
                        if (CheckOutputMappingFormat(componentMetadata, out errorMessage) == false)
                        {
                            noErrors = false;
                            NLog.LogManager.GetCurrentClassLogger().Error(errorMessage);
                            node.SetError(errorMessage);
                        }
                    }
                }
            }

            return(noErrors);
        }
Example #3
0
        public RunnableNode CreateNode(string id, Metadata metadata, System.Threading.ManualResetEvent terminateExperimentExecutionResetEvent)
        {
            StartNodeMetadata startNodeMetadata = metadata as StartNodeMetadata;
            EndNodeMetadata   endNodeMetadata   = metadata as EndNodeMetadata;
            ComponentMetadata componentMetadata = metadata as ComponentMetadata;

            if (startNodeMetadata != null)
            {
                return(new RunnableStartNode(id));
            }
            else if (endNodeMetadata != null)
            {
                return(new RunnableEndNode(id, endNodeMetadata.WaitsForAllPredecessors));
            }
            else if (componentMetadata != null)
            {
                //mock failure
                if (componentMetadata.Label.Equals("Broken Component"))
                {
                    throw new ArgumentException("Failed");
                }

                //otherwise create a mock node and keep reference
                MockNode mockNode = new MockNode(id);
                CreatedNodes.Add(mockNode);

                return(mockNode);
            }
            else
            {
                throw new ArgumentException("Could not identify node type.");
            }
        }
        public ComponentMetadata RestartComponent(int componentId)
        {
            ComponentMetadata rc = null;

            _logger.Log(string.Format("Attempting to restart component with id \"{0}\".", componentId));

            var type = GetComponentType(componentId);

            if (type.Key != null)
            {
                rc = type.Value;

                if (type.Value.UserActions.HasFlag(ComponentUserActions.Restart))
                {
                    StopRunnable(GetIRunnable(type.Key));
                    StartRunnable(GetIRunnable(type.Key));
                }
                else
                {
                    _logger.Log(string.Format("Cannot restart component \"{0}\".  This component is not restartable", type.Value.FriendlyName), LogMessageSeverity.Warning);
                }
            }

            return(rc);
        }
        private ComponentMetadata GetMetadata(Type type)
        {
            ComponentMetadata info = null;

            if (type != null)
            {
                IEnumerable <KeyValuePair <Type, Type> > query;

                if (type.IsInterface)
                {
                    query = _container.GetRegisteredTypes().Where(k => k.Key == type);
                }
                else
                {
                    query = _container.GetRegisteredTypes().Where(k => k.Value == type);
                }

                if (query.Any())
                {
                    info = GetMetadata(query.First());
                }
            }

            return(info);
        }
Example #6
0
        /// <summary>
        /// Creates the Runnable node with a specific id based on the given metadata.
        /// Uses Composite Component Metadata config values to override Components config values in subgraph.
        /// </summary>
        /// <param name="id">The id of the node.</param>
        /// <param name="metadata">The component metadata.</param>
        /// <param name="loggerNameRoot">The logger name root - needed so that the logs are specific per experiment and experiment window.</param>
        /// <param name="library">The library of components.</param>
        /// <param name="componentsAppDomain">The components app domain is the app domain which components assemblies are going to be loaded into.</param>
        /// <param name="terminateExperimentExecutionResetEvent">The event that allows signalling termination of the experiment;
        /// Needed for the composite components sublevel experiments, so that they hold the referance to the same termination event as top level experiment</param>
        /// <returns>
        /// Created node
        /// </returns>
        public override RunnableNode CreateNode(String id, Metadata metadata, LoggerNameRoot loggerNameRoot, ComponentsLibrary library,
                                                AppDomain componentsAppDomain, System.Threading.ManualResetEvent terminateExperimentExecutionResetEvent)
        {
            RunnableNode retNode;

            ComponentMetadata          originalComponentMetadata  = metadata as ComponentMetadata;
            CompositeComponentMetadata compositeComponentMetadata = metadata as CompositeComponentMetadata;

            if (originalComponentMetadata != null)
            {
                ComponentMetadata overrideComponentMetadata = (ComponentMetadata)originalComponentMetadata.Clone();
                OverrideConfigValues(id, overrideComponentMetadata);
                retNode = base.CreateNode(id, overrideComponentMetadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }
            else if (compositeComponentMetadata != null)
            {
                OverrideConfigValues(id, compositeComponentMetadata);
                retNode = base.CreateCompositeComponentNode(id, compositeComponentMetadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }
            else
            {
                retNode = base.CreateNode(id, metadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }

            return(retNode);
        }
Example #7
0
            public ComponentDirectiveVisitor(string filePath, IReadOnlyList <TagHelperDescriptor> tagHelpers, string currentNamespace)
            {
                _filePath = filePath;

                // We don't want to consider non-component tag helpers in a component document.
                _tagHelpers = tagHelpers.Where(t => ComponentMetadata.IsComponentTagHelperKind(t.Kind) && !IsTagHelperFromMangledClass(t)).ToList();

                for (var i = 0; i < _tagHelpers.Count; i++)
                {
                    var tagHelper = _tagHelpers[i];
                    if (tagHelper.IsComponentFullyQualifiedNameMatch())
                    {
                        // If the component descriptor matches for a fully qualified name, using directives shouldn't matter.
                        Matches.Add(tagHelper);
                        continue;
                    }

                    var typeName = tagHelper.GetTypeName();
                    if (tagHelper.IsChildContentTagHelper())
                    {
                        // If this is a child content tag helper, we want to add it if it's original type is in scope.
                        // E.g, if the type name is `Test.MyComponent.ChildContent`, we want to add it if `Test.MyComponent` is in scope.
                        TrySplitNamespaceAndType(typeName, out typeName, out var _);
                    }

                    if (currentNamespace != null && IsTypeInScope(typeName, currentNamespace))
                    {
                        // Also, if the type is already in scope of the document's namespace, using isn't necessary.
                        Matches.Add(tagHelper);
                    }
                }
            }
		/// <summary>
		///     Initializes a new instance.
		/// </summary>
		/// <param name="component">The metadata of the component that was found in multiple locations of a component hierarchy.</param>
		internal InvalidHierarchyStructureException(ComponentMetadata component)
			: base("A component has been found in multiple locations of the component hierarchy; " +
				   "the 'Component' property contains the metadata of the component that violated the hierarchy constraint.")
		{
			Requires.NotNull(component, () => component);
			Component = component;
		}
Example #9
0
 private void UpdateAllUsers(ComponentMetadata data)
 {
     if (data != null)
     {
         Broadcast((IComponentServiceCallback c) => c.ComponentUpdated(data));
     }
 }
Example #10
0
        /// <summary>
        /// Creates the Runnable node with a specific id based on the given metadata.
        /// </summary>
        /// <param name="nodeId">The node id.</param>
        /// <param name="metadata">The component metadata.</param>
        /// <param name="loggerNameRoot">The logger name root - needed so that the logs are specific per experiment and experiment window.</param>
        /// <param name="library">The library of components.</param>
        /// <param name="componentsAppDomain">The components app domain is the app domain which components assemblies are going to be loaded into.</param>
        /// <param name="terminateExperimentExecutionResetEvent">The event that allows signalling termination of the experiment;
        /// Needed for the composite components sublevel experiments, so that they hold the referance to the same termination event as top level experiment.</param>
        /// <returns>
        /// Created node
        /// </returns>
        public virtual RunnableNode CreateNode(String nodeId, Metadata metadata, LoggerNameRoot loggerNameRoot,
                                               ComponentsLibrary library, AppDomain componentsAppDomain, System.Threading.ManualResetEvent terminateExperimentExecutionResetEvent)
        {
            RunnableNode retNode;

            ComponentMetadata          componentMetadata          = metadata as ComponentMetadata;
            DecisionMetadata           decisionMetadata           = metadata as DecisionMetadata;
            StartNodeMetadata          startNodeMetadata          = metadata as StartNodeMetadata;
            EndNodeMetadata            endNodeMetadata            = metadata as EndNodeMetadata;
            ScopeBaseMetadata          scopeMetadata              = metadata as ScopeBaseMetadata;
            LoopScopeMetadata          loopMetadata               = metadata as LoopScopeMetadata;
            CompositeComponentMetadata compositeComponentMetadata = metadata as CompositeComponentMetadata;
            ExitDecisionMetadata       exitDecisionMetadata       = metadata as ExitDecisionMetadata;

            if (componentMetadata != null)
            {
                TraceLabSDK.ComponentLogger logger = TraceLab.Core.Components.LoggerFactory.CreateLogger(loggerNameRoot, nodeId, componentMetadata);
                IComponent component = library.LoadComponent(componentMetadata, Workspace, logger, componentsAppDomain);
                retNode = new RunnableComponentNode(nodeId, componentMetadata.Label, component, logger, library, componentMetadata.WaitsForAllPredecessors);
            }
            else if (decisionMetadata != null)
            {
                IDecisionModule decisionModule = DecisionModuleFactory.LoadDecisionModule(decisionMetadata, Workspace, componentsAppDomain);
                retNode = new RunnableDecisionNode(nodeId, decisionMetadata.Label, decisionModule, library, decisionMetadata.WaitsForAllPredecessors);
            }
            else if (startNodeMetadata != null)
            {
                retNode = new RunnableStartNode(nodeId);
            }
            else if (endNodeMetadata != null)
            {
                retNode = new RunnableEndNode(nodeId, endNodeMetadata.WaitsForAllPredecessors);
            }
            else if (loopMetadata != null)
            {
                retNode = CreateLoopNode(nodeId, loopMetadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }
            else if (scopeMetadata != null)
            {
                retNode = CreateScopeCompositeComponentNode(nodeId, scopeMetadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }
            else if (compositeComponentMetadata != null)
            {
                retNode = CreateCompositeComponentNode(nodeId, compositeComponentMetadata, loggerNameRoot, library, componentsAppDomain, terminateExperimentExecutionResetEvent);
            }
            else if (exitDecisionMetadata != null)
            {
                retNode = new RunnablePrimitiveNode(nodeId, exitDecisionMetadata.WaitsForAllPredecessors);
            }
            else
            {
                throw new Exceptions.InconsistentTemplateException("Could not identify node type.");
            }

            return(retNode);
        }
Example #11
0
		/// <summary>
		///     Serializes the <paramref name="metadata" />.
		/// </summary>
		/// <param name="metadata">The metadata of the component that should be serialized.</param>
		public string Serialize(ComponentMetadata metadata)
		{
			_writer.Clear();

			_writer.AppendLine("using System;");
			_writer.AppendLine("using SafetySharp.Modeling;");
			_writer.AppendLine("using SafetySharp.Modeling.Faults;");
			_writer.NewLine();

			return SerializeRecursive(metadata);
		}
Example #12
0
        public void LoadAssemblyNotInCurrentDomain()
        {
            // Ensure that the assembly is not already loaded
            foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.GetAssemblies())
            {
                //Dynamic libraries generated dynamically in the process cannot access location - it would throw NotSupportedException
                //for example runtime assemblies Microsoft.GeneratedCode of xml serializers
                if (assm.IsDynamic == false)
                {
                    Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                }
            }
            // We don't even want it in the reflection-only context
            foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies())
            {
                Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
            }

            string id        = "MockComponent";
            string classname = "MockComponents.MockComponent"; //class exists and should be loaded
            ComponentMetadataDefinition compMetaDef  = new ComponentMetadataDefinition(id, AssemblyPath, classname);
            ComponentMetadata           compMetadata = new ComponentMetadata(compMetaDef, AppContext.BaseTestDirectory);

            Library.Add(compMetaDef);

            AppDomain testComponentsAppDomain = (new TraceLab.Core.Components.LibraryHelper(AppContext.WorkspaceInstance.TypeDirectories)).CreateDomain(id, true);

            try
            {
                Library.LoadComponent(compMetadata, CreateWorkspaceWrapper(compMetadata), null, testComponentsAppDomain);

                // Ensure that the assembly did not get loaded into the current application domain.
                foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //Dynamic libraries generated dynamically in the process cannot access location - it would throw NotSupportedException
                    //for example runtime assemblies Microsoft.GeneratedCode of xml serializers
                    if (assm.IsDynamic == false)
                    {
                        Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                    }
                }
                // We don't even want it in the reflection-only context
                foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies())
                {
                    Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                }
            }
            finally
            {
                LibraryHelper.DestroyDomain(testComponentsAppDomain);
            }
        }
        private void SetStatus(ComponentMetadata info, ComponentStatus status)
        {
            if (info != null)
            {
                info.Status = status;

                _logger.Log(string.Format("Set component \"{0}\" status to \"{1}\".", info.FriendlyName, info.Status));
            }
            else
            {
                _logger.Log("Unable to set status, Null argument provided.", LogMessageSeverity.Error);
            }
        }
Example #14
0
        public ComponentNode(string id, SerializedVertexData data) : base(id, data)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            ID = id;
            ComponentMetadata metadata = data.Metadata as ComponentMetadata;
        }
Example #15
0
		/// <summary>
		///     Checks whether <paramref name="component" /> is direct or indirect subcomponent of <paramref name="parentComponent" />.
		/// </summary>
		/// <param name="component">The component that should be checked.</param>
		/// <param name="parentComponent">The parent component that should be checked.</param>
		private static bool IsSubcomponent(ComponentMetadata component, ComponentMetadata parentComponent)
		{
			var root = parentComponent.RootComponent;
			while (true)
			{
				if (component == parentComponent)
					return true;

				if (component == root)
					return false;

				component = component.ParentComponent;
			}
		}
Example #16
0
        // We need to filter out the duplicate tag helper descriptors that come from the
        // open file in the editor. We mangle the class name for its generated code, so using that here to filter these out.
        internal static bool IsTagHelperFromMangledClass(TagHelperDescriptor tagHelper)
        {
            StringSegment className;

            if (tagHelper.IsChildContentTagHelper())
            {
                // If this is a child content tag helper, we want to look at it's original type.
                // E.g, if the type name is `Test.__generated__MyComponent.ChildContent`, we want to look at `Test.__generated__MyComponent`.
                TrySplitNamespaceAndType(tagHelper, out var typeNamespace);
                return(TrySplitNamespaceAndType(typeNamespace, out var _, out className) &&
                       ComponentMetadata.IsMangledClass(className));
            }

            return(TrySplitNamespaceAndType(tagHelper, out var _, out className) &&
                   ComponentMetadata.IsMangledClass(className));
        }
		/// <summary>
		///   Transforms the <paramref name="component" /> to a <see cref="Ssm.Comp" /> instance.
		/// </summary>
		private static Ssm.Comp Transform(ComponentMetadata component)
		{
			var fields = (IEnumerable<FieldMetadata>)component.Fields;
			var methods = component.ProvidedPorts.Cast<MethodMetadata>().Concat(component.RequiredPorts).Concat(new[] { component.StepMethod });

			if (component.StateMachine != null)
			{
				var transitions = component.StateMachine.Transitions;
				methods = methods.Concat(transitions.Where(transition => transition.Guard != null).Select(transition => transition.Guard).Distinct());
				methods = methods.Concat(transitions.Where(transition => transition.Action != null).Select(transition => transition.Action).Distinct());

				fields = fields.Concat(new[] { component.StateMachine.StateField });
			}

			return Ssm.CreateComponent(GetComponentPath(component), fields.Select(Transform), methods.Select(Transform),
				component.Subcomponents.Select(Transform), component.Faults.Select(Transform), component.Bindings.Select(Transform));
		}
            // We need to filter out the duplicate tag helper descriptors that come from the
            // open file in the editor. We mangle the class name for its generated code, so using that here to filter these out.
            internal static bool IsTagHelperFromMangledClass(TagHelperDescriptor tagHelper)
            {
                var typeName = tagHelper.GetTypeName();

                if (tagHelper.IsChildContentTagHelper())
                {
                    // If this is a child content tag helper, we want to look at it's original type.
                    // E.g, if the type name is `Test.__generated__MyComponent.ChildContent`, we want to look at `Test.__generated__MyComponent`.
                    TrySplitNamespaceAndType(typeName, out var namespaceTextSpan, out var _);
                    typeName = GetTextSpanContent(namespaceTextSpan, typeName);
                }
                if (!TrySplitNamespaceAndType(typeName, out var _, out var classNameTextSpan))
                {
                    return(false);
                }
                var className = GetTextSpanContent(classNameTextSpan, typeName);

                return(ComponentMetadata.IsMangledClass(className));
            }
Example #19
0
        public void LoadComponentClassLoaded()
        {
            string id        = "MockComponent";
            string classname = "MockComponents.MockComponent"; //class exists and should be loaded
            ComponentMetadataDefinition compMetaDef  = new ComponentMetadataDefinition(id, AssemblyPath, classname);
            ComponentMetadata           compMetadata = new ComponentMetadata(compMetaDef, AppContext.BaseTestDirectory);

            Library.Add(compMetaDef);

            AppDomain testComponentsAppDomain = (new TraceLab.Core.Components.LibraryHelper(AppContext.WorkspaceInstance.TypeDirectories)).CreateDomain(id, true);

            try
            {
                Library.LoadComponent(compMetadata, CreateWorkspaceWrapper(compMetadata), null, testComponentsAppDomain);
            }
            finally
            {
                LibraryHelper.DestroyDomain(testComponentsAppDomain);
            }
        }
Example #20
0
        /// <summary>
        /// Checks the output mappings format for illegal characters.
        /// In particular it assures that mappings do not contain Workspace Namespace_Delimiter character.
        /// </summary>
        /// <param name="componentMetadata">The component metadata.</param>
        /// <param name="errorMessage">The error message, if method returns false</param>
        /// <returns>true, if there are no errors, otherwise false.</returns>
        private static bool CheckOutputMappingFormat(ComponentMetadata componentMetadata, out string errorMessage)
        {
            bool noErrors = true;

            StringBuilder error = new StringBuilder();

            //validate also if mappings do not contain illegal characters (in particular workspace namespace delimiter)
            foreach (IOItem item in componentMetadata.IOSpec.Output.Values)
            {
                if (item.MappedTo.Contains(TraceLab.Core.Workspaces.Workspace.NAMESPACE_DELIMITER))
                {
                    noErrors = false;
                    error.AppendLine(String.Format("Output mapping '{0}' cannot contain character '{1}'", item.MappedTo, TraceLab.Core.Workspaces.Workspace.NAMESPACE_DELIMITER));
                }
            }

            errorMessage = error.ToString();

            return(noErrors);
        }
Example #21
0
        public Component(Dataflow pipeline, string moniker)
        {
            if (pipeline == null)
            {
                throw new ArgumentNullException(nameof(pipeline));
            }

            if (string.IsNullOrWhiteSpace(moniker))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(moniker));
            }



            Pipeline          = pipeline.Pipeline;
            ComponentMetadata = (IDTSComponentMetaData130)Pipeline.ComponentMetaDataCollection.New();
            ComponentMetadata.ComponentClassID = moniker;
            ManagedComponentWrapper            = ComponentMetadata.Instantiate();
            ManagedComponentWrapper.ProvideComponentProperties();
            Connections = pipeline.Connections;
        }
Example #22
0
        public void ComponentUpdated(ComponentMetadata component)
        {
            this.BeginInvoke(() =>
            {
                var oldComponent = Components.Where(c => c.OriginalObject.ComponentId == component.ComponentId).FirstOrDefault();

                if (oldComponent != null)
                {
                    oldComponent.UpdateFrom(component);
                }
                else
                {
                    ComponentMetadataModel model = new ComponentMetadataModel();
                    model.UpdateFrom(component);
                    model.StopCommand.ParameterizedExecuteCallback    += ExecuteStopCommand;
                    model.StartCommand.ParameterizedExecuteCallback   += ExecuteStartCommand;
                    model.RestartCommand.ParameterizedExecuteCallback += ExecuteRestartCommand;
                    model.DisableCommand.ParameterizedExecuteCallback += ExecuteDisableCommand;
                    Components.Add(model);
                }
            });
        }
        private ComponentMetadata GetMetadata(KeyValuePair <Type, Type> type)
        {
            ComponentMetadata info;

            if (!_metadataCache.TryGetValue(type.Key, out info))
            {
                info = new ComponentMetadata();
                info.InterfaceTypeName = type.Key.Name;
                info.ConcreteTypeName  = type.Value.Name;

                var metaAtty = type.Value.GetAttribute <ComponentMetadataAttribute>();

                if (metaAtty != null)
                {
                    info.Description  = metaAtty.Description;
                    info.FriendlyName = metaAtty.FriendlyName;
                    info.UserActions  = metaAtty.AllowedActions;
                }

                var regAtty = type.Value.GetAttribute <ComponentRegistrationAttribute>();

                if (regAtty != null)
                {
                    info.Type = regAtty.Type;
                }

                //TODO: use configuration system to get the real data
                //info.IsDisabled = _config.GetConfig<bool>(GetType().Name,string.Format(type.Value.Name));
                info.IsDisabled = false;

                info.Dependencies = GetDependencies(type.Value).ToArray();

                info.ComponentId = info.GetHashCode();

                _metadataCache.Add(type.Key, info);
            }

            return(info);
        }
Example #24
0
        private void AttachListenerToIOSpecHighlights(ExperimentNode node)
        {
            // HERZUM SPRINT 4: TLAB-238
            ComponentMetadata meta = ExperimentNode.Data.Metadata as ComponentMetadata;

            if (meta != null)
            {
                TraceLab.Core.Components.ConfigWrapper configWrapper = meta.ConfigWrapper as TraceLab.Core.Components.ConfigWrapper;
                if (configWrapper != null)
                {
                    TraceLab.Core.Components.ConfigPropertyObject value = new TraceLab.Core.Components.ConfigPropertyObject();
                    // HERZUM SPRINT 4.3: TLAB-238 TLAB-243
                    // ADD configWrapper.ConfigValues.TryGetValue ("ConfigurationFile", out value)
                    if (configWrapper.ConfigValues.TryGetValue("Directory", out value) || configWrapper.ConfigValues.TryGetValue("ConfigurationFile", out value))
                    {
                        if (value != null)
                        {
                            value.SetExperimentLocationRoot(System.IO.Path.GetDirectoryName(m_applicationContext.Application.Experiment.ExperimentInfo.FilePath), true);
                        }
                    }
                    // END HERZUM SPRINT 4.2: TLAB-202
                }
            }
            // HERZUM SPRINT 4: TLAB-238

            //set convenience metadata field
            m_componentMetadata = node.Data.Metadata as IConfigurableAndIOSpecifiable;
            if (m_componentMetadata != null)
            {
                m_componentMetadata.IOSpec.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
                {
                    if (e.PropertyName.Equals("IsInputHighlighted") || e.PropertyName.Equals("IsOutputHighlighted"))
                    {
                        //redraw component
                        Invalidate();
                    }
                };
            }
        }
Example #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private void addOwnedEntitiesFor(org.terasology.entitySystem.Component comp, org.terasology.entitySystem.metadata.ComponentMetadata<?> componentMetadata, java.util.Collection<org.terasology.entitySystem.entity.EntityRef> outEntityList)
        private void addOwnedEntitiesFor <T1>(Component comp, ComponentMetadata <T1> componentMetadata, ICollection <EntityRef> outEntityList)
        {
            foreach (ComponentFieldMetadata field in componentMetadata.Fields)
            {
                if (field.OwnedReference)
                {
                    object value = field.getValue(comp);
                    if (value is ICollection)
                    {
                        foreach (EntityRef @ref in ((ICollection <EntityRef>)value))
                        {
                            if (@ref.exists())
                            {
                                outEntityList.Add(@ref);
                            }
                        }
                    }
                    else if (value is IDictionary)
                    {
                        foreach (EntityRef @ref in ((IDictionary <object, EntityRef>)value).Values)
                        {
                            if (@ref.exists())
                            {
                                outEntityList.Add(@ref);
                            }
                        }
                    }
                    else if (value is EntityRef)
                    {
                        EntityRef @ref = (EntityRef)value;
                        if (@ref.exists())
                        {
                            outEntityList.Add(@ref);
                        }
                    }
                }
            }
        }
Example #26
0
 private IWorkspaceInternal CreateWorkspaceWrapper(ComponentMetadata metadata)
 {
     return(WorkspaceWrapperFactory.CreateWorkspaceWrapper(metadata, WorkspaceManager.WorkspaceInternalInstance));
 }
Example #27
0
 /// <summary>
 /// Creates the workspace wrapper, which ensures that loading and storing of workspace items has been declared by the component.
 /// </summary>
 /// <param name="originalComponentMetadata">The component metadata.</param>
 /// <param name="workspaceInstance">The workspace instance.</param>
 /// <returns>created workspace wrapper</returns>
 public static WorkspaceWrapper CreateWorkspaceWrapper(ComponentMetadata componentMetadata, IWorkspaceInternal workspaceInstance)
 {
     return(new WorkspaceWrapper(componentMetadata.IOSpec, workspaceInstance));
 }
 public void ComponentUpdated(ComponentMetadata component)
 {
     _logger.Log(string.Format("Component \"{0}\" status is now \"{1}\"", component.FriendlyName, component.Status));
 }
Example #29
0
			public StatementWriter(CodeWriter writer, ComponentMetadata metadata = null)
			{
				_metadata = metadata;
				_writer = writer;
			}
Example #30
0
 public TagHelperDirectiveVisitor(IReadOnlyList <TagHelperDescriptor> tagHelpers)
 {
     // We don't want to consider components in a view document.
     _tagHelpers = tagHelpers.Where(t => !ComponentMetadata.IsComponentTagHelperKind(t.Kind)).ToList();
 }
        /// <summary>
        /// Extracts the components/types assemblies from the given vertex.
        /// </summary>
        /// <param name="pVertex">Vertex from the experiment graph.</param>
        private void ExtractFilesFromNode(ExperimentNode pVertex)
        {
            if (pVertex is ComponentNode) // Regular component
            {
                ComponentMetadata metaData = (ComponentMetadata)pVertex.Data.Metadata;
                if (metaData != null)
                {
                    ComponentMetadataDefinition metaDataDef = metaData.ComponentMetadataDefinition;
                    if (metaDataDef != null)
                    {
                        bool include;
                        if (m_config.IncludeOtherPackagesAssemblies)
                        {
                            include = true;
                        }
                        else
                        {
                            //determine if component is independent or is coming from another package
                            include = !IsAssemblyInAnotherPackage(metaDataDef.Assembly);
                        }

                        if (include)
                        {
                            // Component assembly
                            this.m_componentAssemblies.Add(Path.GetFullPath(metaDataDef.Assembly));

                            // Extracting types from IOSpec
                            ExtractTypesFromIOSpec(metaDataDef.IOSpecDefinition);
                        }
                    }

                    ConfigWrapper config = metaData.ConfigWrapper;
                    if (config != null)
                    {
                        // Extracting paths for files/directories from components' configuration
                        foreach (ConfigPropertyObject configValue in config.ConfigValues.Values)
                        {
                            // Files
                            if (configValue.Type == "TraceLabSDK.Component.Config.FilePath" && configValue.Value != null)
                            {
                                // Independent files
                                if (configValue.Value is TraceLab.Core.Components.TraceLabFilePath == false)
                                {
                                    if (this.m_config.IncludeIndependentFilesDirs)
                                    {
                                        var filePath = (TraceLabSDK.Component.Config.FilePath)configValue.Value;
                                        if (File.Exists(filePath.Absolute))
                                        {
                                            PackageFileInfo packageFileInfo = new PackageFileInfo(filePath);
                                            m_files.Add(packageFileInfo);

                                            //Change config value relative path -> this path is saved within experiment (note, we operate on the experiment clone)
                                            //so that relative path is in the subfolder of Experiment folder
                                            filePath.Relative = packageFileInfo.RelativeLocation;
                                        }
                                    }
                                }
                                // Files contained in a package
                                else
                                {
                                    if (this.m_config.IncludeOtherPackagesFilesDirs)
                                    {
                                        //TraceLabFilePath represents the file reference located in the package
                                        var packageFilePath = (TraceLabFilePath)configValue.Value;
                                        if (File.Exists(packageFilePath.Absolute))
                                        {
                                            PackageFileInfo packageFileInfo = new PackageFileInfo(packageFilePath);
                                            m_files.Add(packageFileInfo);

                                            //change the configValue to basic FilePath, (not TraceLabFilePath in the package), with updated Relative Path
                                            //so that relative path is in the subfolder of Experiment folder
                                            TraceLabSDK.Component.Config.FilePath basicFilePath = new TraceLabSDK.Component.Config.FilePath();
                                            basicFilePath.Init(packageFilePath.Absolute, packageFilePath.DataRoot);
                                            basicFilePath.Relative = packageFileInfo.RelativeLocation;
                                            configValue.Value      = basicFilePath;
                                        }
                                    }
                                }
                            }
                            // Directories
                            else if (configValue.Type == "TraceLabSDK.Component.Config.DirectoryPath" && configValue.Value != null)
                            {
                                // Independent directories
                                if (configValue.Value is TraceLab.Core.Components.TraceLabDirectoryPath == false)
                                {
                                    if (this.m_config.IncludeIndependentFilesDirs)
                                    {
                                        var dirPath = (TraceLabSDK.Component.Config.DirectoryPath)configValue.Value;
                                        if (Directory.Exists(dirPath.Absolute))
                                        {
                                            PackageFileInfo packageDirectoryInfo = new PackageFileInfo(dirPath);
                                            m_directories.Add(packageDirectoryInfo);

                                            //Change config value relative path -> this path is saved within experiment (note, we operate on the experiment clone)
                                            //so that relative path is in the subfolder of Experiment folder
                                            dirPath.Relative = packageDirectoryInfo.RelativeLocation;
                                        }
                                    }
                                }
                                // Directories contained in a package
                                else
                                {
                                    if (this.m_config.IncludeOtherPackagesFilesDirs)
                                    {
                                        var packageDirPath = (TraceLabDirectoryPath)configValue.Value;
                                        if (Directory.Exists(packageDirPath.Absolute))
                                        {
                                            PackageFileInfo packageDirInfo = new PackageFileInfo(packageDirPath);
                                            m_directories.Add(packageDirInfo);

                                            //change the configValue to basic FilePath, (not TraceLabFilePath in the package), with updated Relative Path
                                            //so that relative path is in the subfolder of Experiment folder
                                            TraceLabSDK.Component.Config.DirectoryPath basicFilePath = new TraceLabSDK.Component.Config.DirectoryPath();
                                            basicFilePath.Init(packageDirPath.Absolute, packageDirPath.DataRoot);
                                            basicFilePath.Relative = packageDirInfo.RelativeLocation;
                                            configValue.Value      = basicFilePath;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (pVertex is CompositeComponentNode) // Composite Components, Loops & Scopes
            {
                CompositeComponentBaseMetadata metaData = (CompositeComponentBaseMetadata)pVertex.Data.Metadata;
                if (metaData != null)
                {
                    foreach (var vertex in metaData.ComponentGraph.Vertices)
                    {
                        ExtractFilesFromNode(vertex);
                    }

                    // Only composite components have MetadataDefinition
                    if (pVertex.Data.Metadata is CompositeComponentMetadata)
                    {
                        CompositeComponentMetadataDefinition metaDataDefinition = ((CompositeComponentMetadata)pVertex.Data.Metadata).ComponentMetadataDefinition;

                        this.m_componentAssemblies.Add(Path.GetFullPath(metaDataDefinition.Assembly));

                        // Extracting types from IOSpec
                        ExtractTypesFromIOSpec(metaDataDefinition.IOSpecDefinition);
                    }
                }
            }
        }
		/// <summary>
		///   Returns a string representation of a component path leading to <paramref name="component" />.
		/// </summary>
		private static string GetComponentPath(ComponentMetadata component)
		{
			return String.Join(".", component.GetPath());
		}
Example #33
0
			private void WriteMemberAccess(ComponentMetadata component)
			{
				if (component == _metadata)
					_writer.Append("this.");
				else
				{
					WriteMemberAccess(component.ParentComponent);
					_writer.Append("_{0}.", component.Name);
				}
			}
    /// <inheritdoc />
    protected override void OnDocumentStructureCreated(
        RazorCodeDocument codeDocument,
        NamespaceDeclarationIntermediateNode @namespace,
        ClassDeclarationIntermediateNode @class,
        MethodDeclarationIntermediateNode method)
    {
        if (!codeDocument.TryComputeNamespace(fallbackToRootNamespace: true, out var computedNamespace) ||
            !TryComputeClassName(codeDocument, out var computedClass))
        {
            // If we can't compute a nice namespace (no relative path) then just generate something
            // mangled.
            computedNamespace = FallbackRootNamespace;
            var checksum = Checksum.BytesToString(codeDocument.Source.GetChecksum());
            computedClass = $"AspNetCore_{checksum}";
        }

        var documentNode = codeDocument.GetDocumentIntermediateNode();

        if (char.IsLower(computedClass, 0))
        {
            // We don't allow component names to start with a lowercase character.
            documentNode.Diagnostics.Add(
                ComponentDiagnosticFactory.Create_ComponentNamesCannotStartWithLowerCase(computedClass, documentNode.Source));
        }

        if (MangleClassNames)
        {
            computedClass = ComponentMetadata.MangleClassName(computedClass);
        }

        @namespace.Content = computedNamespace;
        @class.ClassName   = computedClass;
        @class.Modifiers.Clear();
        @class.Modifiers.Add("public");
        @class.Modifiers.Add("partial");

        if (FileKinds.IsComponentImport(codeDocument.GetFileKind()))
        {
            // We don't want component imports to be considered as real component.
            // But we still want to generate code for it so we can get diagnostics.
            @class.BaseType = typeof(object).FullName;

            method.ReturnType = "void";
            method.MethodName = "Execute";
            method.Modifiers.Clear();
            method.Modifiers.Add("protected");

            method.Parameters.Clear();
        }
        else
        {
            @class.BaseType = ComponentsApi.ComponentBase.FullTypeName;

            // Constrained type parameters are only supported in Razor language versions v6.0
            var razorLanguageVersion = codeDocument.GetParserOptions()?.Version ?? RazorLanguageVersion.Latest;
            var directiveType        = razorLanguageVersion.CompareTo(RazorLanguageVersion.Version_6_0) >= 0
                ? ComponentConstrainedTypeParamDirective.Directive
                : ComponentTypeParamDirective.Directive;
            var typeParamReferences = documentNode.FindDirectiveReferences(directiveType);
            for (var i = 0; i < typeParamReferences.Count; i++)
            {
                var typeParamNode = (DirectiveIntermediateNode)typeParamReferences[i].Node;
                if (typeParamNode.HasDiagnostics)
                {
                    continue;
                }

                @class.TypeParameters.Add(new TypeParameter()
                {
                    ParameterName = typeParamNode.Tokens.First().Content,
                    Constraints   = typeParamNode.Tokens.Skip(1).FirstOrDefault()?.Content
                });
            }

            method.ReturnType = "void";
            method.MethodName = ComponentsApi.ComponentBase.BuildRenderTree;
            method.Modifiers.Clear();
            method.Modifiers.Add("protected");
            method.Modifiers.Add("override");

            method.Parameters.Clear();
            method.Parameters.Add(new MethodParameter()
            {
                ParameterName = ComponentsApi.RenderTreeBuilder.BuilderParameter,
                TypeName      = ComponentsApi.RenderTreeBuilder.FullTypeName,
            });
        }
    }
Example #35
0
		/// <summary>
		///     Serializes the <paramref name="metadata" />.
		/// </summary>
		/// <param name="metadata">The metadata of the component that should be serialized.</param>
		private string SerializeRecursive(ComponentMetadata metadata)
		{
			_writer.AppendLine("public class {0} : Component", metadata.Name ?? "C");
			_writer.AppendBlockStatement(() =>
			{
				var statementWriter = new StatementWriter(_writer, metadata);

				foreach (var field in metadata.Fields)
					_writer.AppendLine("public {0} {1};", field.Type.FullName, field.Name);

				foreach (var port in metadata.RequiredPorts)
				{
					_writer.AppendLine("public extern {0} {1}({2});", ReturnType(port.MethodInfo.ReturnType), port.Name,
						String.Join(", ", port.MethodInfo.GetParameters().Select(Parameter)));
				}

				foreach (var port in metadata.ProvidedPorts)
				{
					_writer.AppendLine("public {0} {1}({2})", ReturnType(port.MethodInfo.ReturnType), port.Name,
						String.Join(", ", port.MethodInfo.GetParameters().Select(Parameter)));
					statementWriter.Visit(port.MethodBody);
				}

				_writer.AppendLine("public override void Update()");
				statementWriter.Visit(metadata.StepMethod.MethodBody);

				foreach (var subcomponent in metadata.Subcomponents)
				{
					SerializeRecursive(subcomponent);
					_writer.AppendLine("public {0} _{0} = new {0}();", subcomponent.Name);
				}

				_writer.AppendLine("public {0}()", metadata.Name ?? "C");
				_writer.AppendBlockStatement(() =>
				{
					foreach (var binding in metadata.Bindings)
						_writer.AppendLine("Bind(RequiredPorts.{0} = ProvidedPorts.{1});", binding.RequiredPort.Name, binding.ProvidedPort.Name);

					foreach (var field in metadata.Fields)
					{
						string values = null;

						if (field.Type == typeof(int))
							values = String.Join(", ", field.InitialValues);

						if (field.Type == typeof(bool))
							values = String.Join(", ", field.InitialValues.Select(v => v.ToString().ToLower()));

						if (field.Type == typeof(double))
							values = String.Join(", ", field.InitialValues.Select(v => ((double)v).ToString(CultureInfo.InvariantCulture)));

						if (field.Type.IsEnum)
							values = String.Join(", ", field.InitialValues.Select(v =>
								String.Format("{0}.{1}", field.Type.Name, Enum.GetValues(field.Type).Cast<object>().First())));

						_writer.AppendLine("SetInitialValues({0}, {1});", field.Name, values);
					}
				});

				foreach (var enumeration in statementWriter.Enums.Union(metadata.Fields.Where(f => f.Type.IsEnum).Select(f => f.Type)))
				{
					var values = String.Join(", ", Enum.GetValues(enumeration).Cast<object>().Select(v => v.ToString()));
					_writer.AppendLine("public enum {0} {{ {1} }}", enumeration.Name, values);
				}
			});

			return _writer.ToString();
		}
 private IWorkspaceInternal CreateWorkspaceWrapper(ComponentMetadata metadata)
 {
     return WorkspaceWrapperFactory.CreateWorkspaceWrapper(metadata, WorkspaceManager.WorkspaceInternalInstance);
 }
        public void LoadComponentClassLoaded()
        {
            string id = "MockComponent";
            string classname = "MockComponents.MockComponent"; //class exists and should be loaded
            ComponentMetadataDefinition compMetaDef = new ComponentMetadataDefinition(id, AssemblyPath, classname);
            ComponentMetadata compMetadata = new ComponentMetadata(compMetaDef, AppContext.BaseTestDirectory);

            Library.Add(compMetaDef);

            AppDomain testComponentsAppDomain = (new TraceLab.Core.Components.LibraryHelper(AppContext.WorkspaceInstance.TypeDirectories)).CreateDomain(id, true);
            try
            {
                Library.LoadComponent(compMetadata, CreateWorkspaceWrapper(compMetadata), null, testComponentsAppDomain);
            }
            finally
            {
                LibraryHelper.DestroyDomain(testComponentsAppDomain);
            }
        }
        public void LoadAssemblyNotInCurrentDomain()
        {
            // Ensure that the assembly is not already loaded
            foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.GetAssemblies())
            {
                //Dynamic libraries generated dynamically in the process cannot access location - it would throw NotSupportedException
                //for example runtime assemblies Microsoft.GeneratedCode of xml serializers
                if (assm.IsDynamic == false)
                {
                    Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                }
            }
            // We don't even want it in the reflection-only context
            foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies())
            {
                Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
            }

            string id = "MockComponent";
            string classname = "MockComponents.MockComponent"; //class exists and should be loaded
            ComponentMetadataDefinition compMetaDef = new ComponentMetadataDefinition(id, AssemblyPath, classname);
            ComponentMetadata compMetadata = new ComponentMetadata(compMetaDef, AppContext.BaseTestDirectory);

            Library.Add(compMetaDef);

            AppDomain testComponentsAppDomain = (new TraceLab.Core.Components.LibraryHelper(AppContext.WorkspaceInstance.TypeDirectories)).CreateDomain(id, true);
            try
            {
                Library.LoadComponent(compMetadata, CreateWorkspaceWrapper(compMetadata), null, testComponentsAppDomain);

                // Ensure that the assembly did not get loaded into the current application domain.
                foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //Dynamic libraries generated dynamically in the process cannot access location - it would throw NotSupportedException
                    //for example runtime assemblies Microsoft.GeneratedCode of xml serializers
                    if (assm.IsDynamic == false)
                    {
                        Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                    }
                }
                // We don't even want it in the reflection-only context
                foreach (System.Reflection.Assembly assm in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies())
                {
                    Assert.IsFalse(assm.Location.Equals(AssemblyPath, StringComparison.CurrentCultureIgnoreCase));
                }
            }
            finally
            {
                LibraryHelper.DestroyDomain(testComponentsAppDomain);
            }
        }