Example #1
0
        internal void RegisterComponents()
        {
            ComponentDefinition animationComponent = new ComponentDefinition("animation");

            animationComponent.AddAttribute <string>("animationKeyframes");
            ComponentRegistry.Instance.Register(animationComponent);
        }
Example #2
0
        public void Initialize()
        {
            ComponentDefinition avatar = new ComponentDefinition("avatar");

            avatar.AddAttribute <string>("userLogin", null);
            ComponentRegistry.Instance.Register(avatar);

            ClientManager.Instance.RegisterClientService("avatar", true, new Dictionary <string, Delegate> {
                { "getAvatarEntityGuid", (Func <Connection, string>)GetAvatarEntityGuid },
                { "changeAppearance", (Action <Connection, string, Vector>)ChangeAppearance },
                { "startAvatarMotionInDirection", (Action <Connection, Vector>)StartAvatarMotionInDirection },
                { "setAvatarForwardBackwardMotion", (Action <Connection, float>)SetForwardBackwardMotion },
                { "setAvatarLeftRightMotion", (Action <Connection, float>)SetLeftRightMotion },
                { "setAvatarSpinAroundAxis", (Action <Connection, Vector, float>)SetAvatarSpinAroundAxis }
            });

            ClientManager.Instance.NotifyWhenAnyClientAuthenticated(delegate(Connection connection) {
                Activate(connection);
                connection.Closed += (sender, e) => Deactivate(connection);
            });

            World.Instance.AddedEntity += HandleAddedEntity;

            foreach (var entity in World.Instance)
            {
                CheckAndRegisterAvatarEntity(entity);
            }
        }
Example #3
0
        //////////////////////////////////////////////////////////////////////////////////////////////
        //
        //
        //////////////////////////////////////////////////////////////////////////////////////////////
        void InsertAsSurfaceGraphics(Matrix transfo)
        {
            Inventor.Application InvApp = AdnInventorUtilities.InvApplication;

            Document document = InvApp.ActiveDocument;

            ComponentDefinition compDef =
                AdnInventorUtilities.GetCompDefinition(document);

            _clientGraphicsMng.SetGraphicsSource(InvApp.ActiveDocument);

            Dictionary <SurfaceBody, SurfaceBody> surfaceBodies =
                AdnInventorUtilities.GetTransientBodies(
                    AdnInventorUtilities.GetCompDefinition(_componentDocument));

            foreach (KeyValuePair <SurfaceBody, SurfaceBody> pair in surfaceBodies)
            {
                SurfaceGraphics surfGraph = _clientGraphicsMng.DrawSurface(pair.Value);

                GraphicsNode node = surfGraph.Parent;

                node.Transformation = transfo;
                node.Selectable     = true;

                StyleSourceTypeEnum styleSourceType;
                node.RenderStyle = pair.Key.GetRenderStyle(out styleSourceType);
            }
        }
Example #4
0
        public void InstantiateArrayPlacementRule()
        {
            Name = nameof(InstantiateArrayPlacementRule);
            var red_cube = new Mass(
                new Profile(Polygon.Rectangle(1, 1)),
                1,
                new Material("Red", new Color(1, 0, 0, 1)),
                new Transform()
                );
            var green_cube = new Mass(
                new Profile(Polygon.Rectangle(1, 1)),
                7,
                new Material("Green", new Color(0, 1, 0, 1)),
                new Transform()
                );
            var blue_cube = new Mass(
                new Profile(Polygon.Rectangle(1, 1)),
                7,
                new Material("Blue", new Color(0, 0, 1, 1)),
                new Transform()
                );
            var refPath1 = new Polyline(new[] { new Vector3(1, 1), new Vector3(1, 19) });
            var refPath2 = new Polyline(new[] { new Vector3(2, 18), new Vector3(18, 2) });
            var refPath3 = new Polyline(new[] { new Vector3(19, 1), new Vector3(19, 19) });
            var rule1    = ArrayPlacementRule.FromClosestPoints(red_cube, refPath1, new SpacingConfiguration(SpacingMode.ByCount, 5), TestReferencePointsA, "By Count Array");
            var rule2    = ArrayPlacementRule.FromClosestPoints(green_cube, refPath2, new SpacingConfiguration(SpacingMode.ByApproximateLength, 4), TestReferencePointsA, "By Approx Length Array");
            var rule3    = ArrayPlacementRule.FromClosestPoints(blue_cube, refPath3, new SpacingConfiguration(SpacingMode.ByLength, 2), TestReferencePointsA, "By Length Array");
            // create a polyline rule, to visualize the boundary:
            var boundaryRule = PolylinePlacementRule.FromClosestPoints(Polygon.Rectangle(new Vector3(0, 0, 0), new Vector3(20, 20)), TestReferencePointsA, "Boundary");

            var definition = new ComponentDefinition(new IComponentPlacementRule[] { rule1, rule2, rule3, boundaryRule }, TestReferencePointsA);

            ArrayResults(definition, TestTargetBoundariesA);
        }
Example #5
0
        public void ReorderComponent(ComponentDefinition toMove, ComponentDefinition target, bool insertAtEnd, out int oldIndex, out int newIndex)
        {
            oldIndex = -1;
            newIndex = -1;
            int targetIndex = -1;

            for (int i = 0; i < RootGroup.ComponentCount; i++)
            {
                var component = Components[RootGroup.GroupStartIndex + i];
                if (component.Component == toMove)
                {
                    oldIndex = i;
                }
                else if (component.Component == target)
                {
                    targetIndex = i;
                }
                if (oldIndex != -1 && targetIndex != -1)
                {
                    break;
                }
            }

            if (oldIndex == -1 || targetIndex == -1)
            {
                var issue = oldIndex == -1 ? "" : "target";
                Debug.LogError($"Could not find the {issue} component while reordering");
                return;
            }

            newIndex = targetIndex + (insertAtEnd ? 1 : 0);

            Components.Insert(newIndex, Components[oldIndex]);
            Components.RemoveAt(oldIndex + (targetIndex < oldIndex ? 1 : 0));
        }
Example #6
0
        public void InstantiateSizeBasedPlacementRule()
        {
            Name = nameof(InstantiateSizeBasedPlacementRule);
            var sizes          = new[] { 18, 15, 13, 10, 4 };
            var elementConfigs = new List <(GeometricElement, Polygon)>();
            var innerBoundary  = Polygon.Rectangle(new Vector3(1, 1), new Vector3(19, 19));

            foreach (var size in sizes)
            {
                var color     = new Color(size / 18.0, 0, 1.0, 1.0);
                var mat       = new Material(size.ToString(), color);
                var clearance = Polygon.Rectangle(new Vector3(0, 0), new Vector3(size, size));
                var mass      = new Mass(new Profile(clearance, clearance.Offset(-1), Guid.NewGuid(), null), 1, mat);
                elementConfigs.Add((mass, clearance));
            }
            var rule = SizeBasedPlacementRule.FromClosestPoints(elementConfigs, innerBoundary, TestReferencePointsA, "Size rule");
            // create a polyline rule, to visualize the boundary:
            var boundaryRule1 = PolylinePlacementRule.FromClosestPoints(Polygon.Rectangle(new Vector3(0, 0, 0), new Vector3(20, 20)), TestReferencePointsA, "Boundary");

            var boundaryRule2 = PolylinePlacementRule.FromClosestPoints(innerBoundary, TestReferencePointsA, "Boundary 2");

            var definition = new ComponentDefinition(new IComponentPlacementRule[] { rule, boundaryRule1, boundaryRule2 }, TestReferencePointsA);

            ArrayResults(definition, TestTargetBoundariesA);
        }
Example #7
0
        public QueryComponent Find(ComponentDefinition componentDefinition, out QueryGroup owner)
        {
            owner = null;
            var found = Components?.FirstOrDefault(x => x.Component == componentDefinition);

            if (found != null)
            {
                QueryGroup FindGroup(QueryGroup targetGroup, QueryComponent component)
                {
                    if (GetComponentsInQuery(targetGroup).Contains(component))
                    {
                        return(targetGroup);
                    }

                    foreach (var subGroup in GetSubGroups(targetGroup))
                    {
                        var inChildren = FindGroup(subGroup, component);
                        if (inChildren != null)
                        {
                            return(inChildren);
                        }
                    }

                    return(null);
                }

                owner = FindGroup(RootGroup, found);
            }
            return(found);
        }
Example #8
0
        public void GetBomRowProperties(BOMRowsEnumerator rows, JArray bomRows)
        {
            const string TRACKING = "Design Tracking Properties";

            foreach (BOMRow row in rows)
            {
                ComponentDefinition componentDef = row.ComponentDefinitions[1];

                // Assumes not virtual component (if so add conditional for that here)
                Property partNum  = componentDef.Document.PropertySets[TRACKING]["Part Number"];
                Property descr    = componentDef.Document.PropertySets[TRACKING]["Description"];
                Property material = componentDef.Document.PropertySets[TRACKING]["Material"];

                JObject bomRow = new JObject(
                    new JProperty("row_number", row.ItemNumber),
                    new JProperty("part_number", partNum.Value),
                    new JProperty("quantity", row.ItemQuantity),
                    new JProperty("description", descr.Value),
                    new JProperty("material", material.Value)
                    );

                // LogTrace("Add BOM Row #" + row.ItemNumber);
                bomRows.Add(bomRow);

                // iterate through child rows
                if (row.ChildRows != null)
                {
                    GetBomRowProperties(row.ChildRows, bomRows);
                }
            }
        }
Example #9
0
        public override string GetOrDeclareComponentArray(
            RoslynEcsTranslator.IterationContext ctx,
            ComponentDefinition componentDefinition,
            out LocalDeclarationStatementSyntax arrayInitialization,
            out StatementSyntax arrayDisposal)
        {
            Type resolvedType = componentDefinition.TypeHandle.Resolve(m_Stencil);
            var  arrayName    = ctx.GetComponentDataArrayName(resolvedType);

            Type arrayType = typeof(NativeArray <>).MakeGenericType(resolvedType);

            arrayInitialization = RoslynBuilder.DeclareLocalVariable(
                arrayType, arrayName,
                MakeInitComponentDataArrayExpression(ctx, resolvedType),
                RoslynBuilder.VariableDeclarationType.InferredType);

            arrayDisposal = ExpressionStatement(
                InvocationExpression(
                    MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        IdentifierName(arrayName),
                        IdentifierName(nameof(IDisposable.Dispose)))))
                            .NormalizeWhitespace();

            return(arrayName);
        }
Example #10
0
        void DoDemo()
        {
            Inventor.Application InvApp = AdnInventorUtilities.InvApplication;

            _compDef = AdnInventorUtilities.GetCompDefinition(InvApp.ActiveDocument);

            _surfaceBodies = AdnInventorUtilities.GetTransientBodies(_compDef);

            _interactionManager = new AdnInteractionManager(InvApp);

            _interactionManager.Initialize();

            _interactionManager.OnTerminateEvent +=
               new AdnInteractionManager.OnTerminateHandler(OnTerminateEvent);

            _clientGraphicsMng = new AdnClientGraphicsManager(
               InvApp,
               AdnInventorUtilities.AddInGuid);

            _clientGraphicsMng.SetGraphicsSource(_interactionManager.InteractionEvents);

     
            _interactionManager.SelectEvents.SingleSelectEnabled = true;

            _interactionManager.AddSelectionFilter(SelectionFilterEnum.kPartFacePlanarFilter);
            _interactionManager.AddSelectionFilter(SelectionFilterEnum.kWorkPlaneFilter);
                
            _interactionManager.SelectEvents.OnSelect += 
                new SelectEventsSink_OnSelectEventHandler(SelectEvents_OnSelect);

            _interactionManager.Start("Select planar face or workplane: ");
        }
Example #11
0
        private static ComponentInstance InstantiateLayout(SpaceConfiguration configs, double width, double length, Polygon rectangle, Transform xform)
        {
            ContentConfiguration selectedConfig = null;
            var orderedKeys = configs.OrderByDescending(kvp => kvp.Value.CellBoundary.Depth * kvp.Value.CellBoundary.Width).Select(kvp => kvp.Key);

            foreach (var key in orderedKeys)
            {
                var config = configs[key];
                if (config.CellBoundary.Width < width && config.CellBoundary.Depth < length)
                {
                    selectedConfig = config;
                    break;
                }
            }
            if (selectedConfig == null)
            {
                return(null);
            }
            var baseRectangle = Polygon.Rectangle(selectedConfig.CellBoundary.Min, selectedConfig.CellBoundary.Max);
            var rules         = selectedConfig.Rules();

            var componentDefinition = new ComponentDefinition(rules, selectedConfig.Anchors());
            var instance            = componentDefinition.Instantiate(ContentConfiguration.AnchorsFromRect(rectangle.TransformedPolygon(xform)));
            var allPlacedInstances  = instance.Instances;

            foreach (var item in allPlacedInstances)
            {
                if (item is ElementInstance ei && !rectangle.Contains(ei.Transform.Origin))
                {
                }
            }
            return(instance);
        }
Example #12
0
        public void ShouldStoreAndRetrieveComponent()
        {
            ComponentDefinition myComponent = new ComponentDefinition("myComponent");

            myComponent.AddAttribute <int>("IntAttribute");
            myComponent.AddAttribute <string>("StringAttribute");
            componentRegistry.Register(myComponent);

            if (plugin == null)
            {
                plugin = new PersistencePlugin();
                plugin.Initialize();
            }

            Entity entity = new Entity();

            World.Instance.Add(entity);
            entity["myComponent"]["IntAttribute"]    = 42;
            entity["myComponent"]["StringAttribute"] = "Hello World!";

            // De-Activate on-remove event handler, as for tests, we only want to remove the entity from the local registry, not from the
            // persistence storage
            World.Instance.RemovedEntity -= plugin.OnEntityRemoved;
            World.Instance.Remove(entity);

            plugin.RetrieveEntitiesFromDatabase();

            Entity storedEntity = World.Instance.FindEntity(entity.Guid.ToString());

            Assert.AreEqual(42, storedEntity["myComponent"]["IntAttribute"]);
            Assert.AreEqual("Hello World!", storedEntity["myComponent"]["StringAttribute"]);
        }
		public void Setup() {
			_c = new Container();
			c1n = new ComponentDefinition<ITestService1, TestService1>(name: "test");
			c1n2 = new ComponentDefinition<ITestService1, TestService1>(name: "test2");
			c2nn = new ComponentDefinition<ITestService2, TestService2>(priority: 10);
			c2n = new ComponentDefinition<ITestService2, TestService2>(name: "test");
		}
        void RegisterComponent()
        {
            ComponentDefinition avatar = new ComponentDefinition("avatar");

            avatar.AddAttribute <string>("userLogin", null);
            ComponentRegistry.Instance.Register(avatar);
        }
Example #15
0
        public SheetParameters AddSheetParameters(ComponentDefinition cdef)
        {
            var parameters = SheetParameters.CreateViewsAuto(cdef, DrawDoc);

            SheetsParameters.Add(parameters);
            return(parameters);
        }
Example #16
0
        public override string GetOrDeclareComponentArray(RoslynEcsTranslator.IterationContext ctx,
                                                          ComponentDefinition componentDefinition, out LocalDeclarationStatementSyntax arrayInitialization,
                                                          out StatementSyntax arrayDisposal)
        {
            var declaration = Parent.GetOrDeclareComponentArray(
                ctx,
                componentDefinition,
                out arrayInitialization,
                out arrayDisposal);
            var parameter = declaration.ToCamelCase();

            if (!(Parent is JobContext) || m_DeclaredComponentArray.Contains(componentDefinition))
            {
                return(parameter);
            }

            var componentType = componentDefinition.TypeHandle.Resolve(ctx.Stencil);
            var arrayType     = typeof(NativeArray <>).MakeGenericType(componentType);

            m_Parameters.Add(
                Argument(IdentifierName(declaration)),
                Parameter(Identifier(parameter))
                .WithType(TypeSystem.BuildTypeSyntax(arrayType)));
            m_DeclaredComponentArray.Add(componentDefinition);

            return(parameter);
        }
 void DefineComponents()
 {
     ComponentDefinition location = new ComponentDefinition("location");
     location.AddAttribute<Vector>("position", new Vector(0, 0, 0));
     location.AddAttribute<Quat>("orientation", new Quat(0, 0, 0, 1));
     ComponentRegistry.Instance.Register(location);
 }
Example #18
0
 public SheetParameters(ComponentDefinition cdef, DrawingDocument drawDoc)
 {
     Model       = cdef.Document as _Document;
     DrawDoc     = drawDoc;
     TitleBlocks = DrawDoc.TitleBlockDefinitions;
     TitleBlock  = null;
 }
        public static void RegisterComponent <TModel>(this ComponentRegistry componentRegistry)
            where TModel : ComponentBase, new()
        {
            var type     = typeof(TModel);
            var instance = new TModel();

            // TODO: this is gross
            TypeDefinition GetProperties()
            {
                var method = type.GetMethod("GetModelAsync");

                if (method != null)
                {
                    // return type is Task<TModel>
                    var modelType = method.ReturnType.GenericTypeArguments.FirstOrDefault();

                    var builder = new TypeDefinitionBuilder(modelType, componentRegistry.PropertyMapper);

                    return(builder.Build());
                }

                return(null);
            }

            var definition = new ComponentDefinition
            {
                Alias        = instance.Alias,
                Control      = type,
                Placeholders = instance.Placeholders,
                Properties   = GetProperties()
            };

            componentRegistry.RegisterComponent(definition);
        }
        public void MockGlobalObjects()
        {
            handlers             = new Mock <IHandlers>();
            remoteConnectionMock = new Mock <Connection>();
            remoteConnectionMock.Setup(rc => rc.GenerateClientFunction("serverSync", "registerComponentDefinition"))
            .Returns((ClientFunction)handlers.Object.RegisterComponentDefinition);

            var remoteServerMock = new Mock <IRemoteServer>();

            remoteServerMock.Setup(rs => rs.Connection).Returns(remoteConnectionMock.Object);

            localServiceMock = new Mock <ServiceImplementation>();
            var localServerMock = new Mock <ILocalServer>();

            localServerMock.SetupGet(ls => ls.Service).Returns(localServiceMock.Object);

            var serverSyncMock = new Mock <IServerSync>();

            serverSyncMock.Setup(ss => ss.RemoteServers).Returns(new List <IRemoteServer> {
                remoteServerMock.Object
            });
            serverSyncMock.Setup(ss => ss.LocalServer).Returns(localServerMock.Object);

            componentRegistryMock = new Mock <IComponentRegistry>();
            componentRegistryMock.SetupGet(cr => cr.RegisteredComponents).Returns(
                new ReadOnlyCollection <ReadOnlyComponentDefinition>(new List <ReadOnlyComponentDefinition>()));

            ServerSync.Instance        = serverSyncMock.Object;
            ComponentRegistry.Instance = componentRegistryMock.Object;

            testComponentDefinition = new ComponentDefinition("test");
            testComponentDefinition.AddAttribute <float>("f", 3.14f);
            testComponentDefinition.AddAttribute <int>("i", 42);
        }
Example #21
0
        /// <summary>
        /// Registers gravity component that carries the attribute for the groundlevel
        /// </summary>
        internal void RegisterComponents()
        {
            ComponentDefinition gravityDefinition = new ComponentDefinition("avatarCollision");

            gravityDefinition.AddAttribute <float>("groundLevel");
            ComponentRegistry.Instance.Register(gravityDefinition);
        }
 void DefineComponents()
 {
     ComponentDefinition skeleton = new ComponentDefinition("skeleton");
     skeleton.AddAttribute<List<Vector>>("translations", new List<Vector>());
     skeleton.AddAttribute<List<Quat>>("rotations", new List<Quat>());
     ComponentRegistry.Instance.Register(skeleton);
 }
Example #23
0
        public void BomAccess()
        {
            AssemblyDocument            oDoc = (AssemblyDocument)_InvApplication.ActiveDocument;
            AssemblyComponentDefinition oDef = oDoc.ComponentDefinition;

            BOM oBOM = default(BOM);

            oBOM = oDef.BOM;

            oBOM.StructuredViewEnabled = true;

            BOMView oBomView = oBOM.BOMViews["Structured"];

            int rowIdx = 0;

            for (rowIdx = 1; rowIdx <= oBomView.BOMRows.Count; rowIdx++)
            {
                BOMRow oRow = oBomView.BOMRows[rowIdx];

                Debug.Print("ItemNumber: " + oRow.ItemNumber + " TotalQuantity = " + oRow.TotalQuantity);

                ComponentDefinition oCompDef = oRow.ComponentDefinitions[1];

                PropertySet oDesignPropSet = default(PropertySet);
                oDesignPropSet = oCompDef.Document.PropertySets("Design Tracking Properties");
            }
        }
 /// <summary>
 /// Register component that carries information about which model is used and what deviation
 /// map should be displayed in the synchronized views
 /// </summary>
 private void RegisterComponent()
 {
     ComponentDefinition deviationMapComponent = new ComponentDefinition("deviationmap");
     deviationMapComponent.AddAttribute<int>("selectedvector", 1);
     deviationMapComponent.AddAttribute<float>("threshold", 1.5f);
     ComponentRegistry.Instance.Register(deviationMapComponent);
 }
Example #25
0
        private void GetBomRowProperties(BOMRowsEnumerator bomRowsEnumerator, List <object[]> rows)
        {
            foreach (BOMRow row in bomRowsEnumerator)
            {
                ComponentDefinition componentDef = row.ComponentDefinitions[1];
                var trackingSet = componentDef.Document.PropertySets[TrackingProperties];

                // Assumes not virtual component (if so add conditional for that here)
                Property partNum     = trackingSet["Part Number"];
                Property description = trackingSet["Description"];
                Property material    = trackingSet["Material"];

                object[] data =   // order is important. a place to improve
                {
                    row.ItemNumber,
                    partNum.Value,
                    row.ItemQuantity,
                    description.Value,
                    material.Value
                };

                rows.Add(data);

                // iterate through child rows
                if (row.ChildRows != null)
                {
                    GetBomRowProperties(row.ChildRows, rows);
                }
            }
        }
        void DoDemo()
        {
            Inventor.Application InvApp = AdnInventorUtilities.InvApplication;

            _compDef = AdnInventorUtilities.GetCompDefinition(InvApp.ActiveDocument);

            _surfaceBodies = AdnInventorUtilities.GetTransientBodies(_compDef);

            _interactionManager = new AdnInteractionManager(InvApp);

            _interactionManager.Initialize();

            _interactionManager.OnTerminateEvent +=
                new AdnInteractionManager.OnTerminateHandler(OnTerminateEvent);

            _clientGraphicsMng = new AdnClientGraphicsManager(
                InvApp,
                AdnInventorUtilities.AddInGuid);

            _clientGraphicsMng.SetGraphicsSource(_interactionManager.InteractionEvents);


            _interactionManager.SelectEvents.SingleSelectEnabled = true;

            _interactionManager.AddSelectionFilter(SelectionFilterEnum.kPartFacePlanarFilter);
            _interactionManager.AddSelectionFilter(SelectionFilterEnum.kWorkPlaneFilter);

            _interactionManager.SelectEvents.OnSelect +=
                new SelectEventsSink_OnSelectEventHandler(SelectEvents_OnSelect);

            _interactionManager.Start("Select planar face or workplane: ");
        }
        private void ChooseComponent(object sender, RoutedEventArgs e)
        {
            SelectedComponent = (ComponentDefinition)((Button)sender).DataContext;
            var flyout = this.GetParent <Flyout>();

            flyout.IsOpen = false;
        }
Example #28
0
        private static ComponentInstance InstantiateLayout(SpaceConfiguration configs, double width, double length, Polygon rectangle, Transform xform)
        {
            ContentConfiguration selectedConfig = null;
            var orderedKeys = configs.OrderBy(k => rand.NextDouble()).Select(k => k.Key);

            foreach (var key in orderedKeys)
            {
                var config = configs[key];
                if (config.CellBoundary.Width < width && config.CellBoundary.Depth < length)
                {
                    selectedConfig = config;
                    break;
                }
            }
            if (selectedConfig == null)
            {
                return(null);
            }
            var baseRectangle = Polygon.Rectangle(selectedConfig.CellBoundary.Min, selectedConfig.CellBoundary.Max);
            var rules         = selectedConfig.Rules();

            var componentDefinition = new ComponentDefinition(rules, selectedConfig.Anchors());
            var instance            = componentDefinition.Instantiate(ContentConfiguration.AnchorsFromRect(rectangle.TransformedPolygon(xform)));

            return(instance);
        }
        //////////////////////////////////////////////////////////////////////////////////////////////
        // Deletes all graphics (valid for parts and assembly documents only, and which doesn't
        // contain ClientFeatures with graphics elements)
        //
        //////////////////////////////////////////////////////////////////////////////////////////////
        public static void DeleteAllGraphics()
        {
            Inventor.Application InvApp = AdnInventorUtilities.InvApplication;

            Document document = InvApp.ActiveDocument;

            ClientGraphicsCollection   cgCol       = null;
            GraphicsDataSetsCollection dataSetsCol = null;

            switch (document.DocumentType)
            {
            case DocumentTypeEnum.kAssemblyDocumentObject:
            case DocumentTypeEnum.kPartDocumentObject:

                ComponentDefinition compDef =
                    AdnInventorUtilities.GetCompDefinition(document);

                //Not a Part or Assembly, return
                if (compDef == null)
                {
                    return;
                }

                cgCol       = compDef.ClientGraphicsCollection;
                dataSetsCol = document.GraphicsDataSetsCollection;

                break;

            case DocumentTypeEnum.kDrawingDocumentObject:

                DrawingDocument drawing = document as DrawingDocument;

                cgCol       = drawing.ActiveSheet.ClientGraphicsCollection;
                dataSetsCol = drawing.ActiveSheet.GraphicsDataSetsCollection;

                break;

            default:
                return;
            }

            if (cgCol.Count != 0)
            {
                foreach (ClientGraphics cg in cgCol)
                {
                    cg.Delete();
                }
            }

            if (dataSetsCol.Count != 0)
            {
                foreach (GraphicsDataSets dataSets in dataSetsCol)
                {
                    dataSets.Delete();
                }
            }

            InvApp.ActiveView.Update();
        }
Example #30
0
        public ViewDefinition(ComponentDefinition component, string slot)
        {
            if (slot == null)
                slot = string.Empty;

            _component = component;
            _slot = slot.ToLower();
        }
        void DefineComponents()
        {
            ComponentDefinition skeleton = new ComponentDefinition("skeleton");

            skeleton.AddAttribute <List <Vector> >("translations", new List <Vector>());
            skeleton.AddAttribute <List <Quat> >("rotations", new List <Quat>());
            ComponentRegistry.Instance.Register(skeleton);
        }
 private void Action(ComponentDefinition cdef, int level)
 {
     if (!cdef.IsProjectPart())
     {
         return;
     }
     Writer.AddModel(cdef);
 }
        public bool TryGet(string name, out ComponentDefinition component)
        {
            component = _components.Value.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.InvariantCultureIgnoreCase));
            if (component == null)
                return false;

            return true;
        }
 private void DefineComponents()
 {
     ComponentDefinition mesh = new ComponentDefinition("mesh");
     mesh.AddAttribute<string>("uri");
     mesh.AddAttribute<bool>("visible", true);
     mesh.AddAttribute<Vector>("scale", new Vector(1, 1, 1));
     ComponentRegistry.Instance.Register(mesh);
 }
 private void registerLightComponent()
 {
     ComponentDefinition lightComponent = new ComponentDefinition("light");
     lightComponent.AddAttribute<LightType>("type");
     lightComponent.AddAttribute<Vector>("intensity");
     lightComponent.AddAttribute<Vector>("attenuation");
     ComponentRegistry.Instance.Register(lightComponent);
 }
 public void Setup()
 {
     _c   = new Container();
     c1n  = new ComponentDefinition <ITestService1, TestService1>(name: "test");
     c1n2 = new ComponentDefinition <ITestService1, TestService1>(name: "test2");
     c2nn = new ComponentDefinition <ITestService2, TestService2>(priority: 10);
     c2n  = new ComponentDefinition <ITestService2, TestService2>(name: "test");
 }
        void DefineComponents()
        {
            ComponentDefinition location = new ComponentDefinition("location");

            location.AddAttribute <Vector>("position", new Vector(0, 0, 0));
            location.AddAttribute <Quat>("orientation", new Quat(0, 0, 0, 1));
            ComponentRegistry.Instance.Register(location);
        }
Example #38
0
        private void RegisterNGSIComponent()
        {
            ComponentDefinition ngsi = new ComponentDefinition("ngsi");

            ngsi.AddAttribute <string>("id");
            ngsi.AddAttribute <string>("type");
            ComponentRegistry.Instance.Register(ngsi);
        }
        internal void DefineComponents()
        {
            ComponentDefinition motion = new ComponentDefinition("motion");

            motion.AddAttribute <Vector>("velocity", new Vector(0, 0, 0));
            motion.AddAttribute <AxisAngle>("rotVelocity", new AxisAngle(0, 1, 0, 0));
            ComponentRegistry.Instance.Register(motion);
        }
Example #40
0
        public ModuleDefinition(string name, ComponentDefinition component)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name");
            if (component == null)
                throw new ArgumentNullException("component");

            Name = name;
            Component = component;
        }
Example #41
0
        private static void AddProperty(ComponentDefinition viewComponentDefinition, ViewDefinition view, string propertyName, object propertyValue)
        {
            var viewProperty = viewComponentDefinition.Type.GetProperty(propertyName);
            if (viewProperty == null)
                throw new XrcException(string.Format("Property '{0}' for type '{1}' not found.", propertyName, viewComponentDefinition.Type.FullName));

            var propertyXValue = new XValue(viewProperty.PropertyType, propertyValue);

            view.Properties.Add(new XProperty(viewProperty, propertyXValue));
        }
        /// <summary>
        /// Initializes the plugin. This method will be called by the plugin manager when all dependency plugins have
        /// been loaded.
        /// </summary>
        public void Initialize()
        {
            // Register 'scripting' component.
            ComponentDefinition scripting = new ComponentDefinition("scripting");
            scripting.AddAttribute<string>("ownerScript");
            scripting.AddAttribute<string>("serverScript");
            scripting.AddAttribute<string>("clientScript");
            ComponentRegistry.Instance.Register(scripting);

            Scripting.Instance = new Scripting();
        }
 internal void RegisterPersistedComponents()
 {
     foreach (KeyValuePair<string, ReadOnlyComponentDefinition> definitionPair in this.OwnerRegisteredComponents)
     {
         ReadOnlyComponentDefinition roDefinition = definitionPair.Value;
         ComponentDefinition definition = new ComponentDefinition(roDefinition.Name);
         foreach (ReadOnlyAttributeDefinition attrDef in definition.AttributeDefinitions)
             definition.AddAttribute(attrDef.Name, attrDef.Type, attrDef.DefaultValue);
         Registry.Register (definition);
     }
 }
Example #44
0
        public void Init()
        {
            // Set up definition.
            definition = new ComponentDefinition("test-component");
            definition.AddAttribute<string>("a", "a_value");
            definition.AddAttribute<float>("b", 3.14f);

            // Set up containing entity.
            containingEntity = new Entity();

            // Create component.
            component = new Component(definition, containingEntity);
        }
        public void Init()
        {
            // TODO: mock ComponentDefinition
            ComponentDefinition test = new ComponentDefinition("test");
            test.AddAttribute<int>("a", 42);
            test.AddAttribute<int?>("n", 5);

            mockComponentRegistry = new Mock<IComponentRegistry>();
            mockComponentRegistry.Setup(r => r.FindComponentDefinition("test")).Returns(test);

            entity = new Entity();
            entity.componentRegistry = mockComponentRegistry.Object;

            mockHandlers = new Mock<IMockHandlers>();
        }
Example #46
0
 public void It_should_position_http_headers()
 {
     var operation = new RemoraOperation {IncomingUri = new Uri(@"http://tempuri.org")};
     var componentDefinition = new ComponentDefinition
                                   {
                                       Properties =
                                           {
                                               {"name", "foo"},
                                               {"value", "bar"}
                                           }
                                   };
     _setHttpHeader.BeginAsyncProcess(operation, componentDefinition, b =>
                                                                          {
                                                                              Assert.That(b);
                                                                              Assert.That(!operation.OnError);
                                                                              Assert.That(
                                                                                  operation.Request.HttpHeaders[
                                                                                      "foo"], Is.EqualTo("bar"));
                                                                          });
 }
Example #47
0
        public void It_should_throw_an_exception_if_name_or_value_not_in_component_definition()
        {
            var operation = new RemoraOperation {IncomingUri = new Uri(@"http://tempuri.org")};
            var componentDefinition = new ComponentDefinition();

            Assert.That(() => _setHttpHeader.BeginAsyncProcess(operation, componentDefinition, b => { }),
                        Throws.Exception.TypeOf<SetHttpHeaderException>()
                            .With.Message.Contains("name"));

            componentDefinition.Properties["name"] = "foo";

            Assert.That(() => _setHttpHeader.BeginAsyncProcess(operation, componentDefinition, b => { }),
                        Throws.Exception.TypeOf<SetHttpHeaderException>()
                            .With.Message.Contains("value"));

            componentDefinition.Properties["name"] = "foo";
            componentDefinition.Properties["value"] = "bar";

            Assert.That(() => _setHttpHeader.BeginAsyncProcess(operation, componentDefinition, b => { }),
                        Throws.Nothing);
        }
        public void ShouldConvertCompatibleDefaultValues()
        {
            ComponentDefinition def = new ComponentDefinition("defTypeTest");

            def.AddAttribute<double>("c", 42.0);
            def.AddAttribute<int?>("e", null);
            def.AddAttribute<int?>("f", 34);

            Assert.Catch<AttributeDefinitionException>(delegate {
                def.AddAttribute<double>("d", 42);
            });

            Assert.Catch<AttributeDefinitionException>(delegate {
                def.AddAttribute<double>("a", 42);
            });

            Assert.Catch<AttributeDefinitionException>(delegate {
                def.AddAttribute<double>("b", 42f);
            });

            Assert.Catch<AttributeDefinitionException>(delegate {
                def.AddAttribute<int>("g", 3.14);
            });
        }
        public void MockGlobalObjects()
        {
            handlers = new Mock<IHandlers>();
            remoteConnectionMock = new Mock<Connection>();
            remoteConnectionMock.Setup(rc => rc.GenerateClientFunction("serverSync", "registerComponentDefinition"))
                .Returns((ClientFunction)handlers.Object.RegisterComponentDefinition);

            var remoteServerMock = new Mock<IRemoteServer>();
            remoteServerMock.Setup(rs => rs.Connection).Returns(remoteConnectionMock.Object);

            localServiceMock = new Mock<ServiceImplementation>();
            var localServerMock = new Mock<ILocalServer>();
            localServerMock.SetupGet(ls => ls.Service).Returns(localServiceMock.Object);

            var serverSyncMock = new Mock<IServerSync>();
            serverSyncMock.Setup(ss => ss.RemoteServers).Returns(new List<IRemoteServer> { remoteServerMock.Object });
            serverSyncMock.Setup(ss => ss.LocalServer).Returns(localServerMock.Object);

            componentRegistryMock = new Mock<IComponentRegistry>();
            componentRegistryMock.SetupGet(cr => cr.RegisteredComponents).Returns(
                new ReadOnlyCollection<ReadOnlyComponentDefinition>(new List<ReadOnlyComponentDefinition>()));

            ServerSync.Instance = serverSyncMock.Object;
            ComponentRegistry.Instance = componentRegistryMock.Object;

            testComponentDefinition = new ComponentDefinition("test");
            testComponentDefinition.AddAttribute<float>("f", 3.14f);
            testComponentDefinition.AddAttribute<int>("i", 42);
        }
 public RegisteredComponentEventArgs(ComponentDefinition definition)
 {
     ComponentDefinition = definition;
 }
Example #51
0
        static void GetComponentsFromInputForRemove(ComAdminAppInfo appInfo, IList<ComponentDefinition<string>> inComps, out IList<ComponentDefinition<Guid>> outComps)
        {
            outComps = new List<ComponentDefinition<Guid>>();

            foreach (ComponentDefinition<string> inComp in inComps)
            {
                ComponentDefinition<Guid> outComp = null;

                ComAdminClassInfo classInfo = appInfo.FindClass(inComp.Component);

                if (classInfo == null)
                {
                    ToolConsole.WriteWarning(SR.GetString(SR.CannotFindComponentInApplicationSkipping, inComp.Component, Tool.Options.ShowGuids ? appInfo.ID.ToString("B") : appInfo.Name));
                    continue;
                }


                // Find existing componentDef if it was referenced in an earlier iteration
                foreach (ComponentDefinition<Guid> cd in outComps)
                {
                    if (cd.Component == classInfo.Clsid)
                    {
                        outComp = cd;
                    }
                }

                if (outComp == null)
                {
                    outComp = new ComponentDefinition<Guid>(classInfo.Clsid);
                }

                if (inComp.AllInterfaces)
                {
                    foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces)
                        outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo, false));
                    outComp.AddInterface(typeof(IMetadataExchange).GUID, null);


                }
                else
                {
                    foreach (InterfaceDefination<string> comInterface in inComp.Interfaces)
                    {
                        string itfName = comInterface.Interface;
                        if (itfName == typeof(IMetadataExchange).GUID.ToString("B"))
                        {
                            outComp.AddInterface(typeof(IMetadataExchange).GUID, null);
                        }
                        else
                        {
                            ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(itfName);
                            if (interfaceInfo == null)
                            {
                                ToolConsole.WriteWarning(SR.GetString(SR.CannotFindInterfaceInCatalogForComponentSkipping, itfName, inComp.Component));
                                continue;
                            }
                            if (comInterface.AllMethods)
                            {
                                outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo));
                            }
                            else
                            {

                                outComp.AddInterface(interfaceInfo.Iid, (List<string>)comInterface.Methods);
                            }

                        }
                    }
                }
                if (outComp.Interfaces != null)
                    outComps.Add(outComp);
                else
                {
                    ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheSpecifiedInterfacesForComponentWereFoundSkipping, inComp.Component));
                }
            }
        }
Example #52
0
 public void Init()
 {
     definition = new ComponentDefinition("test-name");
 }
Example #53
0
 void RegisterComponent()
 {
     ComponentDefinition avatar = new ComponentDefinition("avatar");
     avatar.AddAttribute<string>("userLogin", null);
     ComponentRegistry.Instance.Register(avatar);
 }
 public void Init()
 {
     registry = new ComponentRegistry();
     definition = new ComponentDefinition("test2");
     definition.AddAttribute<int>("a", 42);
 }
 //////////////////////////////////////////////////////////////////////////////////////
 // Use: Draws a ComponentGraphics primitive
 //
 //////////////////////////////////////////////////////////////////////////////////////
 public ComponentGraphics DrawComponent(
    ComponentDefinition compDef)
 {
     return DrawComponent(compDef, null);
 }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Use: Returns a collection of transient bodies transformed in the context of the assembly 
        //      (if compDef is an assembly CompDef).
        //      The Key of the dictionary is the original body, the value is the transformed transient body
        //
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public static Dictionary<SurfaceBody, SurfaceBody> GetTransientBodies(ComponentDefinition compDef)
        {
            Dictionary<SurfaceBody, SurfaceBody> bodies = new Dictionary<SurfaceBody, SurfaceBody>();

            if (compDef.Type == ObjectTypeEnum.kAssemblyComponentDefinitionObject)
            {
                foreach (ComponentOccurrence occurrence in compDef.Occurrences)
                {
                    if (occurrence.DefinitionDocumentType == DocumentTypeEnum.kAssemblyDocumentObject)
                    {
                        Dictionary<SurfaceBody, SurfaceBody> bodiesRec =
                            GetTransientBodies(occurrence.Definition);

                        foreach (SurfaceBody key in bodiesRec.Keys)
                        {
                            SurfaceBody bodyCpy = AdnInventorUtilities.InvApplication.TransientBRep.Copy(bodiesRec[key]);

                            AdnInventorUtilities.InvApplication.TransientBRep.Transform(
                                bodyCpy,
                                occurrence.Transformation);

                            bodies.Add(key, bodyCpy);
                        }
                    }
                    else
                    {
                        foreach (SurfaceBody body in occurrence.SurfaceBodies)
                        {
                            SurfaceBody bodyCpy = AdnInventorUtilities.InvApplication.TransientBRep.Copy(body);

                            AdnInventorUtilities.InvApplication.TransientBRep.Transform(
                                bodyCpy,
                                occurrence.Transformation);

                            bodies.Add(body, bodyCpy);
                        }
                    }
                }
            }
            else
            {
                foreach (SurfaceBody body in compDef.SurfaceBodies)
                {
                    SurfaceBody bodyCpy =
                        AdnInventorUtilities.InvApplication.TransientBRep.Copy(body);

                    bodies.Add(body, bodyCpy);
                }
            }

            return bodies;
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Use: Create a new derived PartDocument from a ComponentDefinition (asm or part)
        //
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public static PartDocument DeriveComponent(ComponentDefinition compDef)
        {
            Inventor.Application InvApp = AdnInventorUtilities.InvApplication;

            PartDocument derivedDoc = InvApp.Documents.Add(
                    DocumentTypeEnum.kPartDocumentObject,
                    InvApp.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject,
                       SystemOfMeasureEnum.kDefaultSystemOfMeasure,
                       DraftingStandardEnum.kDefault_DraftingStandard,
                       null),
                   false) as PartDocument;

            if (compDef.Type == ObjectTypeEnum.kAssemblyComponentDefinitionObject)
            {
                DerivedAssemblyComponents derAsmComps =
                    derivedDoc.ComponentDefinition.ReferenceComponents.DerivedAssemblyComponents;

                DerivedAssemblyDefinition derAsmDef = derAsmComps.CreateDefinition(
                        (compDef.Document as Document).FullFileName);

                derAsmDef.InclusionOption = DerivedComponentOptionEnum.kDerivedIncludeAll;

                derAsmComps.Add(derAsmDef);

                return derivedDoc;
            }

            if (compDef.Type == ObjectTypeEnum.kPartComponentDefinitionObject)
            {
                DerivedPartComponents derPartComps =
                    derivedDoc.ComponentDefinition.ReferenceComponents.DerivedPartComponents;

                DerivedPartUniformScaleDef derPartDef = derPartComps.CreateDefinition(
                       (compDef.Document as Document).FullFileName);

                derPartDef.IncludeAll();

                derPartComps.Add(derPartDef as DerivedPartDefinition);

                return derivedDoc;
            }

            derivedDoc.Close(true);

            return null;
        }
Example #58
0
        // returns strongly typed, verified components, from loosely-typed (string) user inputs
        static void GetComponentsFromInputForAdd(ComAdminAppInfo appInfo, IList<ComponentDefinition<string>> inComps, bool mex, bool priorEndpointsExist, out IList<ComponentDefinition<Guid>> outComps)
        {
            string missingInterface = String.Empty;
            outComps = new List<ComponentDefinition<Guid>>();

            foreach (ComponentDefinition<string> inComp in inComps)
            {
                ComponentDefinition<Guid> outComp = null;

                ComAdminClassInfo classInfo = appInfo.FindClass(inComp.Component);

                if (classInfo == null)
                {
                    ToolConsole.WriteWarning(SR.GetString(SR.CannotFindComponentInApplicationSkipping, inComp.Component, Tool.Options.ShowGuids ? appInfo.ID.ToString("B") : appInfo.Name));
                    continue;
                }

                if (!ValidateClass(classInfo))
                    continue;

                // Find existing componentDef if it was referenced in an earlier iteration
                foreach (ComponentDefinition<Guid> cd in outComps)
                {
                    if (cd.Component == classInfo.Clsid)
                    {
                        outComp = cd;
                    }
                }

                if (outComp == null)
                {
                    outComp = new ComponentDefinition<Guid>(classInfo.Clsid);
                }

                if (inComp.AllInterfaces)
                {
                    foreach (ComAdminInterfaceInfo interfaceInfo in classInfo.Interfaces)
                    {
                        if (ComPlusTypeValidator.VerifyInterface(interfaceInfo, options.AllowReferences, classInfo.Clsid))
                            outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo));

                    }
                    if ((outComp.Interfaces != null) && mex)
                        outComp.AddInterface(typeof(IMetadataExchange).GUID, null);


                }
                else
                {
                    foreach (InterfaceDefination<string> comInterface in inComp.Interfaces)
                    {
                        string itfName = comInterface.Interface;
                        if (itfName == typeof(IMetadataExchange).GUID.ToString("B"))
                        {
                            if (!mex)
                                outComp.AddInterface(typeof(IMetadataExchange).GUID, null);
                        }
                        else
                        {
                            ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(itfName);
                            if (interfaceInfo == null)
                            {
                                ToolConsole.WriteWarning(SR.GetString(SR.CannotFindInterfaceInCatalogForComponentSkipping, itfName, inComp.Component));
                                missingInterface = itfName;
                                continue;
                            }
                            if (comInterface.AllMethods)
                            {
                                if (ComPlusTypeValidator.VerifyInterface(interfaceInfo, options.AllowReferences, classInfo.Clsid, true))
                                    outComp.AddInterface(interfaceInfo.Iid, ComPlusTypeValidator.FetchAllMethodsForInterface(interfaceInfo));
                                else
                                    throw CreateException(SR.GetString(SR.InvalidInterface), null);
                            }
                            else
                            {
                                if (ComPlusTypeValidator.VerifyInterfaceMethods(interfaceInfo, comInterface.Methods, options.AllowReferences, true))
                                    outComp.AddInterface(interfaceInfo.Iid, (List<string>)comInterface.Methods);
                                else
                                    throw CreateException(SR.GetString(SR.InvalidMethod), null);
                            }

                        }
                    }

                    if ((outComp.Interfaces != null) || priorEndpointsExist)
                    {
                        if (mex)
                            outComp.AddInterface(typeof(IMetadataExchange).GUID, null);
                    }

                }
                if (outComp.Interfaces != null)
                    outComps.Add(outComp);
                else
                    ToolConsole.WriteWarning(SR.GetString(SR.NoneOfTheSpecifiedInterfacesForComponentWereFoundSkipping, inComp.Component));
            }

            if (outComps.Count == 0 && (!String.IsNullOrEmpty(missingInterface)))
                throw Tool.CreateException(SR.GetString(SR.NoComponentContainsInterface, missingInterface), null);
        }
        public ComponentGraphics DrawComponent(
            ComponentDefinition compDef,
            GraphicsNode node)
        {
            try
            {
                AdnGraphics graphicsData = WorkingGraphics;

                if (node == null)
                {
                    node = graphicsData.ClientGraphics.AddNode(
                        graphicsData.GetGraphicNodeFreeId());
                }

                ComponentGraphics graphic = node.AddComponentGraphics(compDef);

                return graphic;
            }
            catch
            {
                return null;
            }
        }
Example #60
0
 public object Get(ComponentDefinition component, IContext context = null)
 {
     return _windsorKernel.Resolve(component.Type, new { context = context });
 }