Exemplo n.º 1
0
        public void CtorTest()
        {
            var target = new AttributeDefinition<DisplayAttribute>();

            target.Attributes.Should()
                  .HaveCount( 0 );
        }
Exemplo n.º 2
0
        public void AttributesTest()
        {
            var target = new AttributeDefinition<DisplayAttribute>();
            var expected = new List<DisplayAttribute>();
            target.Attributes = expected;

            target.Attributes.Should()
                  .BeSameAs( expected );
        }
Exemplo n.º 3
0
        public void PropertyTest()
        {
            var target = new AttributeDefinition<DisplayAttribute>();
            var expected = typeof (DisplayAttribute).GetProperties()
                                                    .First();
            target.Property = expected;

            target.Property.Should()
                  .BeSameAs( expected );
        }
        public void SetUp()
        {
            var assemblies = new[]
            {
                typeof(Umbraco.Tests.Extensions.TestDynamicExtensions).Assembly
            };
            var supportedDynamicTypes = new[]
            {
                typeof(Content),
                typeof(BendyObject)
            };
            var supportedDynamicFieldTypes = new[]
            {
                typeof(Content),
                typeof(TypedAttribute),
                typeof(BendyObject)
            };
            var bendyMethods = DynamicExtensionsHelper.GetExtensions(assemblies, supportedDynamicTypes);
            var subBendyMethods = DynamicExtensionsHelper.GetExtensions<DynamicFieldExtensionAttribute>(assemblies, supportedDynamicFieldTypes);

            var bendy = new BendyObject();

            BendyObjectExtensionsHelper.ApplyDynamicExtensions<Content>(bendy, bendyMethods);

            var content = new Content();

            _bendy = bendy;
            _bendy["__OriginalItem"] = content;

            var attrType1 = new AttributeType {RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId};
            var attrDef1 = new AttributeDefinition {AttributeType = attrType1};
            var attr1 = new TypedAttribute(attrDef1);

            var subBendy1 = new BendyObject();
            subBendy1["__OriginalItem"] = attr1;
            subBendy1.AddLazy("__Parent", () => bendy);
            subBendy1["__ParentKey"] = "Test";

            BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.FileUploadPropertyEditorId, subBendy1, subBendyMethods);

            _bendy["Test"] = subBendy1;

            var attrType2 = new AttributeType { RenderTypeProvider = CorePluginConstants.TreeNodePickerPropertyEditorId };
            var attrDef2 = new AttributeDefinition { AttributeType = attrType2 };
            var attr2 = new TypedAttribute(attrDef2);

            var subBendy2 = new BendyObject();
            subBendy2["__OriginalItem"] = attr2;
            subBendy2.AddLazy("__Parent", () => bendy);
            subBendy2["__ParentKey"] = "Test2";

            BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.TreeNodePickerPropertyEditorId, subBendy2, subBendyMethods);

            _bendy["Test2"] = subBendy2;
        }
        public InheritedAttributeDefinition(AttributeDefinition attributeDefinition, EntitySchema schema)
            : base(attributeDefinition.Alias, attributeDefinition.Name)
        {
            Id = attributeDefinition.Id;
            Description = attributeDefinition.Description;
            AttributeType = attributeDefinition.AttributeType;
            Ordinal = attributeDefinition.Ordinal;
            RenderTypeProviderConfigOverride = attributeDefinition.RenderTypeProviderConfigOverride;
            AttributeGroup = attributeDefinition.AttributeGroup != null ? new InheritedAttributeGroup(attributeDefinition.AttributeGroup, schema) : null;
            UtcCreated = attributeDefinition.UtcCreated;
            UtcModified = attributeDefinition.UtcModified;
            UtcStatusChanged = attributeDefinition.UtcStatusChanged;

            Schema = schema;
        }
Exemplo n.º 6
0
 public AttributeValue GetValueFor(AttributeDefinition attribute)
 {
     // no attributes
     return(null);
 }
Exemplo n.º 7
0
 public override IDisposable WriteAttribute(AttributeDefinition attributeDefinition)
 {
     if (attributeDefinition != null)
         WriteLine(GetAttribute(attributeDefinition));
     return null;
 }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StatAttributeDefinition" /> class.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 /// <param name="baseValue">The base value.</param>
 /// <param name="increasableByPlayer">if set to <c>true</c> it is increasable by the player.</param>
 public StatAttributeDefinition(AttributeDefinition attribute, float baseValue, bool increasableByPlayer)
 {
     this.attribute           = attribute;
     this.BaseValue           = baseValue;
     this.IncreasableByPlayer = increasableByPlayer;
 }
Exemplo n.º 9
0
        private void LoadTableInfo()
        {
            ClearTableData();

            var              tableInfoCache = SdkCache.GetCache <string, TableDescription>(DDBClient, TableInfoCacheIdentifier, StringComparer.Ordinal);
            bool             staleCacheData;
            TableDescription table = tableInfoCache.GetValue(TableName, this.DescribeTable, out staleCacheData);

            if (staleCacheData)
            {
                var logger = Logger.GetLogger(typeof(Table));
                logger.InfoFormat("Description for table [{0}] loaded from SDK Cache", TableName);
            }

            foreach (var key in table.KeySchema)
            {
                string keyName = key.AttributeName;
                AttributeDefinition attributeDefinition = table.AttributeDefinitions
                                                          .FirstOrDefault(a => string.Equals(a.AttributeName, keyName, StringComparison.Ordinal));
                if (attributeDefinition == null)
                {
                    throw new InvalidOperationException("No attribute definition found for key " + key.AttributeName);
                }
                KeyDescription keyDescription = new KeyDescription
                {
                    IsHash = string.Equals(key.KeyType, "HASH", StringComparison.OrdinalIgnoreCase),
                    Type   = GetType(attributeDefinition.AttributeType)
                };
                if (keyDescription.IsHash)
                {
                    HashKeys.Add(keyName);
                }
                else
                {
                    RangeKeys.Add(keyName);
                }
                Keys[keyName] = keyDescription;
            }

            if (table.LocalSecondaryIndexes != null)
            {
                foreach (var index in table.LocalSecondaryIndexes)
                {
                    LocalSecondaryIndexes[index.IndexName] = index;
                    LocalSecondaryIndexNames.Add(index.IndexName);
                }
            }

            if (table.GlobalSecondaryIndexes != null)
            {
                foreach (var index in table.GlobalSecondaryIndexes)
                {
                    GlobalSecondaryIndexes[index.IndexName] = index;
                    GlobalSecondaryIndexNames.Add(index.IndexName);
                }
            }

            foreach (var attribute in table.AttributeDefinitions)
            {
                Attributes.Add(attribute);
            }
        }
Exemplo n.º 10
0
 /// <inheritdoc/>
 public float this[AttributeDefinition attributeDefinition]
 {
     get => this.GetValueOfAttribute(attributeDefinition);
Exemplo n.º 11
0
        private ItemDefinition CreateJewelery(byte number, int slot, bool dropsFromMonsters, string name, byte level, byte durability, ItemOptionDefinition excellentOptionDefinition, AttributeDefinition optionTargetAttribute, AttributeDefinition resistanceAttribute)
        {
            var item = this.Context.CreateNew <ItemDefinition>();

            this.GameConfiguration.Items.Add(item);
            item.Group             = 13;
            item.Number            = number;
            item.ItemSlot          = this.GameConfiguration.ItemSlotTypes.FirstOrDefault(slotType => slotType.ItemSlots.Contains(slot));
            item.DropsFromMonsters = dropsFromMonsters;
            item.Name             = name;
            item.DropLevel        = level;
            item.MaximumItemLevel = 4;
            item.Width            = 1;
            item.Height           = 1;

            //// TODO: Requirement increases with item level
            this.CreateItemRequirementIfNeeded(item, Stats.Level, level);

            item.Durability = durability;
            if (excellentOptionDefinition != null)
            {
                item.PossibleItemOptions.Add(excellentOptionDefinition);
            }

            if (optionTargetAttribute == Stats.HealthRecoveryMultiplier)
            {
                item.PossibleItemOptions.Add(this.healthRecoverOptionDefinition);
            }
            else if (optionTargetAttribute != null)
            {
                // Then it's either maximum mana or ability increase by 1% for each option level
                var option = this.CreateOption("Jewellery option " + optionTargetAttribute.Designation, optionTargetAttribute, 1.01f, AggregateType.Multiplicate);

                item.PossibleItemOptions.Add(option);
            }
            else
            {
                // we add no option.
            }

            if (resistanceAttribute != null)
            {
                // TODO: Implement elemental attacks and resistancies.
                // Not sure how these resistancies work. If I remember correctly, it worked at the original server this way:
                //   - it only considers the maximum resistance of all equipped items
                //   - officially there were only rings/pendant up to level 4 and they worked pretty well
                //     -> one item level means about 20% less chance to get affected by the element (iced, poisoned etc.).
                //   - I'm not sure if they prevent hits or lower the damage. For example, you could miss an attack but still apply ice or poison to an opponent.
                var powerUp = this.Context.CreateNew <ItemBasePowerUpDefinition>();
                item.BasePowerUpAttributes.Add(powerUp);
                powerUp.BaseValue       = 0.2f;
                powerUp.TargetAttribute = resistanceAttribute.GetPersistent(this.GameConfiguration);
                for (int i = 1; i <= 4; i++)
                {
                    var levelBonus = this.Context.CreateNew <LevelBonus>();
                    levelBonus.Level           = i;
                    levelBonus.AdditionalValue = (1 + i) * 0.2f;
                    powerUp.BonusPerLevel.Add(levelBonus);
                }
            }

            foreach (var characterClass in this.GameConfiguration.CharacterClasses)
            {
                item.QualifiedCharacters.Add(characterClass);
            }

            return(item);
        }
Exemplo n.º 12
0
        public void WhenAddingNodeVersionToSession_ThenClearingAndResettingAttributesCollection_BeforeCommitting_AttributesCollectionIsCorrect()
        {
            var setup = new NhibernateTestSetupHelper();
            var node = new Node() { IsDisabled = false };

            using (var tran = setup.SessionForTest.BeginTransaction())
            {
                node = setup.SessionForTest.Merge(node) as Node;
                tran.Commit();
            }
            setup.SessionForTest.Clear();

            NodeVersion nodeVersion = null;

            using (var tran = setup.SessionForTest.BeginTransaction())
            {
                // Get the node from the cleared session to mimic what the NH revision repository is doing
                node = setup.SessionForTest.Get<Node>(node.Id);

                var currentNodeId = node.Id;
                Assert.That(currentNodeId, Is.Not.EqualTo(Guid.Empty));

                var schema = new AttributeSchemaDefinition { Alias = "tes1", SchemaType = "content" };
                var type = new AttributeType { Alias = "type1" };
                var def = new AttributeDefinition
                    { Alias = "def1", AttributeDefinitionGroup = new AttributeDefinitionGroup { Alias = "group1", AttributeSchemaDefinition = schema}, AttributeSchemaDefinition = schema, AttributeType = type};
                schema.AttributeDefinitions.Add(def);
                nodeVersion = new NodeVersion { DefaultName = "test", Node = node, AttributeSchemaDefinition = schema };
                nodeVersion.Attributes.Add(new Attribute { AttributeDefinition = def, NodeVersion = nodeVersion });
                nodeVersion.Node = node;

                // Merge the version into the session, which will add it to 1st-level cache but we haven't committed to db yet
                nodeVersion = setup.SessionForTest.Merge(nodeVersion) as NodeVersion;

                var persister = setup.SessionForTest.GetSessionImplementation().PersistenceContext;

                nodeVersion.Attributes.Clear();
                nodeVersion.Attributes.Add(new Attribute { AttributeDefinition = def, NodeVersion = nodeVersion });

                nodeVersion = setup.SessionForTest.Merge(nodeVersion) as NodeVersion;

                node.NodeVersions.Add(nodeVersion);

                setup.SessionForTest.Merge(node);

                tran.Commit();
            }
            setup.SessionForTest.Clear();

            using (var tran = setup.SessionForTest.BeginTransaction())
            {
                var reloadVersion = setup.SessionForTest.Get<NodeVersion>(nodeVersion.Id);
                reloadVersion.Attributes.Clear();
                setup.SessionForTest.Merge(reloadVersion);
                tran.Commit();
            }

            using (var tran = setup.SessionForTest.BeginTransaction())
            {
                var reloadVersion = setup.SessionForTest.Get<NodeVersion>(nodeVersion.Id);
                Assert.That(reloadVersion.Attributes.Count, Is.EqualTo(1));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AttributeDefinitionMap"/> class
 /// </summary>
 /// <param name="attributeDefinition">The <see cref="AttributeDefinition"/></param>
 /// <param name="mapKind">The <see cref="AttributeDefinitionMapKind"/> specifying the king of mapping of the <see cref="AttributeDefinition"/></param>
 public AttributeDefinitionMap(AttributeDefinition attributeDefinition, AttributeDefinitionMapKind mapKind)
 {
     this.AttributeDefinition = attributeDefinition;
     this.MapKind             = mapKind;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Regeneration" /> class.
 /// At regeneration the value of <paramref name="regenerationMultiplier" /> * <paramref name="maximumAttribute" /> is getting added to
 /// <paramref name="currentAttribute" />, until the value of <paramref name="maximumAttribute" /> is reached.
 /// </summary>
 /// <param name="regenerationMultiplier">The regeneration multiplier.</param>
 /// <param name="maximumAttribute">The maximum attribute.</param>
 /// <param name="currentAttribute">The current attribute.</param>
 /// <param name="absoluteAttribute">The constant regeneration.</param>
 public Regeneration(AttributeDefinition regenerationMultiplier, AttributeDefinition maximumAttribute, AttributeDefinition currentAttribute, AttributeDefinition absoluteAttribute)
 {
     this.RegenerationMultiplier = regenerationMultiplier;
     this.MaximumAttribute       = maximumAttribute;
     this.CurrentAttribute       = currentAttribute;
     this.AbsoluteAttribute      = absoluteAttribute;
 }
Exemplo n.º 15
0
        public static void DrawVolumesTableInBlock(decimal[] decVolumesArray/*, Point3d tablePosition */)
        {
            if (decVolumesArray == null)
            {
                AcVolShowForm();
                return;
            }

            string tableLayerName = "acVlm_Таблицы объемов";
            CreateLayer(tableLayerName, true, false);
            string tableAttributeLayerName = "acVlm_Invisible Layers";
            CreateLayer(tableAttributeLayerName, false, true);

            Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
            //Editor acDocEd = acDoc.Editor; // Editor текущего документа.
            Database acDocDb = acDoc.Database; // Database текущего документа.
            using (acDoc.LockDocument()) // блокировка документа
            {
                // начинаем транзакцию
                using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction())
                {

                    //***
                    // ШАГ 0 - запрос ПК поперечника и его распознание
                    //***
                    double doublePk = ParcePk(SelectPk("Укажите ПК поперечного профиля:"));
                    if (doublePk < 0)
                    {
                        MessageBox.Show("Пикет не распознан или выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.",
                            myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }


                    //***
                    //ШАГ 1 - создаем таблицу и заполняем ее
                    //***

                    Table objTable = new Table();
                    int tableColNumber = 3;
                    int tableRowNumber = _form.listBoxLayers.Items.Count + 1;// количество слоев +1 строка на заголовок таблицы
                    objTable.SetSize(tableRowNumber, tableColNumber);
                    Point3d tablePosition = GetUserPoint("Укажите точку вставки таблицы:");

                    if (tablePosition == new Point3d(2147483647, 2147483647, 2147483647))
                    {
                        acTrans.Abort();
                        AcVolShowForm();
                        return;
                    }
                    objTable.Position = tablePosition;

                    //создаем массив значений для таблицы включая заголовки.
                    string[,] strTableArray = new string[tableRowNumber, tableColNumber];
                    //Записываем в массив заголовки
                    strTableArray[0, 0] = "Наименование";
                    strTableArray[0, 1] = "Ед.Изм.";
                    strTableArray[0, 2] = "Значение";
                    //Записываем в массив Имя объема, Ед.Изм и значение объема и так для каждого объема из лист бокса
                    for (int rowNumber = 1; rowNumber < tableRowNumber; rowNumber++)
                    {
                        strTableArray[rowNumber, 0] = (string)_form.listBoxLayers.Items[rowNumber - 1];
                        strTableArray[rowNumber, 1] = (string)_form.listBoxLayersUnits.Items[rowNumber - 1];
                        strTableArray[rowNumber, 2] = Convert.ToString(Math.Round(decVolumesArray[rowNumber - 1], 2), CultureInfo.InvariantCulture);
                    }

                    // Заполняем таблицу значениями из массива String[,] strTableArray
                    for (int rowNumber = 0; rowNumber < tableRowNumber; rowNumber++)
                    {
                        for (int colNumber = 0; colNumber < tableColNumber; colNumber++)
                        {
                            objTable.Cells[rowNumber, colNumber].TextHeight = 2.5;
                            switch (colNumber)
                            {
                                case 0:
                                    objTable.Columns[colNumber].Width = 60;
                                    break;
                                case 1:
                                    objTable.Columns[colNumber].Width = 15;
                                    break;
                                case 2:
                                    objTable.Columns[colNumber].Width = 20;
                                    break;
                            }
                            objTable.Rows[rowNumber].Height = 8;
                            if (colNumber == 0 & rowNumber > 0)
                            {
                                objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleLeft;
                            }
                            else
                            {
                                objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleCenter;
                            }
                            objTable.Cells[rowNumber, colNumber].SetValue(strTableArray[rowNumber, colNumber], ParseOption.ParseOptionNone);
                        }
                    }

                    // задаем слой таблице
                    objTable.Layer = tableLayerName;

                    //***
                    //  если ПК распознан, то создаем блок, помещаем таблицу в блок и присваиваем атрибут "ПК"
                    //***

                    if (doublePk >= 0)
                    {
                        string pk = Convert.ToString(doublePk, CultureInfo.InvariantCulture);

                        // имя создаваемого блока
                        string objTableBlockName = "acVlm_" + Convert.ToString((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, CultureInfo.InvariantCulture);

                        // открываем таблицу блоков на чтение
                        BlockTable blockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead);

                        // вначале проверяем, нет ли в таблице блока с таким именем
                        // если есть - выводим сообщение об ошибке и заканчиваем выполнение команды
                        if (blockTable.Has(objTableBlockName))
                        {
                            MessageBox.Show("A block with the name \"" + objTableBlockName + "\" already exists.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // создаем новое определение блока, задаем ему имя
                        BlockTableRecord objBtr = new BlockTableRecord { Name = objTableBlockName };

                        blockTable.UpgradeOpen(); //переоткрываем blockTable на запись.

                        // добавляем созданное определение блока в таблицу блоков и в транзакцию,
                        // запоминаем ID созданного определения блока (оно пригодится чуть позже)
                        ObjectId objBtrId = blockTable.Add(objBtr);
                        acTrans.AddNewlyCreatedDBObject(objBtr, true);

                        //добавляем таблицу в блок и в транзацию
                        objBtr.AppendEntity(objTable);
                        acTrans.AddNewlyCreatedDBObject(objTable, true);

                        // создаем определение аттрибута
                        AttributeDefinition objAttribute = new AttributeDefinition
                        {
                            Position = new Point3d(0, 0, 0),
                            Tag = "ПК",
                            Layer = tableAttributeLayerName
                        };

                        // добавляем атрибут в блок и в транзакцию
                        objBtr.AppendEntity(objAttribute);
                        acTrans.AddNewlyCreatedDBObject(objAttribute, true);

                        //***
                        // добавляем вхождение созданного блока на чертеж
                        //***

                        var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        // создаем новое вхождение блока, используя ранее сохраненный ID определения блока
                        BlockReference objBlockReference = new BlockReference(Point3d.Origin, objBtrId)
                        {
                            Layer = tableLayerName
                        };


                        // добавляем созданное вхождение блока на пространство чертежа и в транзакцию
                        if (acBtr != null) acBtr.AppendEntity(objBlockReference);
                        acTrans.AddNewlyCreatedDBObject(objBlockReference, true);

                        // задаем значение аттрибута
                        AttributeReference objAttributeReference = new AttributeReference();
                        objAttributeReference.SetAttributeFromBlock(objAttribute, objBlockReference.BlockTransform);
                        objAttributeReference.TextString = pk;
                        objAttributeReference.Layer = tableAttributeLayerName;
                        objBlockReference.AttributeCollection.AppendAttribute(objAttributeReference);
                        acTrans.AddNewlyCreatedDBObject(objAttributeReference, true);

                    }
                    //***
                    //  если ПК _НЕ_распознан, то помещаем таблицу на чертеж без создания блока с выводом предупреждения
                    //***
                    else
                    {
                        
                        var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        if (acBtr != null) acBtr.AppendEntity(objTable);
                        acTrans.AddNewlyCreatedDBObject(objTable, true);
                    }

                    // фиксируем транзакцию
                    acTrans.Commit();

                    AcVolShowForm();
                }
            }
        }
        public async Task TestTags()
        {
            ViziVault vault = new ViziVault(new Uri(baseUrl)).WithApiKey(apiKey).WithDecryptionKey(decryptionKey).WithEncryptionKey(encryptionKey);

            AttributeDefinition attributeDef1 = new AttributeDefinition("TestAttribute1")
            {
                Tags = new List <string> {
                    "tag1"
                }
            };
            await vault.StoreAttributeDefinitionAsync(attributeDef1);

            User sentUser = new User("exampleUser")
            {
                Tags = new List <string> {
                    "tag2"
                }
            };

            try {
                AttributeValue attribute1 = new AttributeValue(attributeDef1.Name)
                {
                    Value = "exampleUser's first name",
                    Tags  = new List <string> {
                        "tag3"
                    },
                };
                sentUser.AddAttribute(attribute1);
                await vault.SaveAsync(sentUser);

                AttributeValue receivedAttribute = (await vault.FindByUserAsync("exampleUser")).GetAttribute(attributeDef1.Name);
                Assert.Collection(receivedAttribute.Tags,
                                  (tag) => Assert.Equal("tag1", tag),
                                  (tag) => Assert.Equal("tag2", tag),
                                  (tag) => Assert.Equal("tag3", tag)
                                  );

                Tag tag1 = await vault.GetTagAsync("tag1");

                await vault.StoreTagAsync(tag1);

                Tag tag4 = new Tag("tag4");
                await vault.StoreTagAsync(tag4);

                List <Tag> allTags = await vault.GetTagsAsync();

                Assert.Contains(allTags, (tag) => tag.Name.Equals("tag1"));
                Assert.Contains(allTags, (tag) => tag.Name.Equals("tag2"));
                Assert.Contains(allTags, (tag) => tag.Name.Equals("tag3"));
                Assert.Contains(allTags, (tag) => tag.Name.Equals("tag4"));

                await vault.DeleteTagAsync("tag1");

                await vault.DeleteTagAsync("tag2");

                await vault.DeleteTagAsync("tag3");

                await vault.DeleteTagAsync("tag4");

                //Assert.Throws<VaultResponseException>(() => vault.GetTagAsync("tag5").Result);
                Assert.False(await vault.DeleteTagAsync("tag5"));

                allTags = await vault.GetTagsAsync();

                Assert.DoesNotContain(allTags, (tag) => tag.Name.Equals("tag1"));
                Assert.DoesNotContain(allTags, (tag) => tag.Name.Equals("tag2"));
                Assert.DoesNotContain(allTags, (tag) => tag.Name.Equals("tag3"));
                Assert.DoesNotContain(allTags, (tag) => tag.Name.Equals("tag4"));
                Assert.DoesNotContain(allTags, (tag) => tag.Name.Equals("tag5"));
            } finally {
                await vault.PurgeAsync(sentUser.Id);
            }
        }
Exemplo n.º 17
0
        private void Create_opis21()
        {
            string blockName = "opis-21";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Circle ent1 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.2);
            ent1.Color = Color.FromColorIndex(ColorMethod.ByColor, 7);
            entityCollection.Add(ent1);

            List<AttributeDefinition> attDefCollection = new List<AttributeDefinition>();

            AttributeDefinition attDef1 = new AttributeDefinition();
            attDef1.Position = new Point3d(-0.117, -0.085, 0);
            attDef1.Tag = "NN";
            attDef1.Prompt = "numer_preta";
            attDef1.TextString = "nic";
            attDef1.Height = 0.17;
            attDef1.WidthFactor = 0.8;
            attDef1.Justify = AttachmentPoint.MiddleCenter;
            attDef1.Layer = "0";

            AttributeDefinition attDef2 = new AttributeDefinition();
            attDef2.Tag = "OPIS1";
            attDef2.Prompt = "opis_preta1";
            attDef2.TextString = "nic";
            attDef2.Height = 0.125;
            attDef2.WidthFactor = 1;
            attDef2.Justify = AttachmentPoint.MiddleLeft;
            attDef2.HorizontalMode = TextHorizontalMode.TextLeft;
            attDef2.Layer = "0";
            attDef2.AlignmentPoint = new Point3d(0.276, 0, 0);

            Transaction trans = db.TransactionManager.StartTransaction();
            using (trans)
            {
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;

                if (!tst.Has("SIMPLEX8"))
                {
                    System.Windows.Forms.MessageBox.Show("W pliku nie ma definicji stylu tekstu!", "Error",
                        System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    ObjectId textStyleId;
                    textStyleId = tst["SIMPLEX8"];
                    attDef1.TextStyleId = textStyleId;
                    attDef2.TextStyleId = textStyleId;
                }
            }

            attDefCollection.Add(attDef1);
            attDefCollection.Add(attDef2);
            TryInsertBlockRecord(blockName, entityCollection, attDefCollection);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Adds a new attribute value to the collection
 /// </summary>
 /// <param name="theDefinition">The definition.</param>
 /// <param name="theName">The name.</param>
 /// <param name="attributeValue">The attribute value.</param>
 public void AddAttributeValue(AttributeDefinition theDefinition, string theName, Value attributeValue)
 {
     m_AttributeValues.Add(new AttributeValue(theDefinition, theName, attributeValue, this));
 }
Exemplo n.º 19
0
 public OrderTerm(AttributeDefinition attributeDefinition, OrderTermDirection direction)
 {
     AttributeDefinition = attributeDefinition;
     Direction = direction;
 }
Exemplo n.º 20
0
 public static TypedAttribute CreateAttribute(AttributeDefinition def, object value)
 {
     return(new TypedAttribute(def, value));
 }
Exemplo n.º 21
0
        // This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock",
        // creating it if necessary.  The block contains three entities - circle, text
        // and ellipse.
        private ObjectId CreateEmployeeDefinition()
        {
            ObjectId newBtrId = new ObjectId(); //The return value for this function
            Database db = HostApplicationServices.WorkingDatabase; //save some space
            using (Transaction trans = db.TransactionManager.StartTransaction()) //begin the transaction
            {
                // Now, access the database and obtain a reference to the BlockTable
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                if ((bt.Has("EmployeeBlock")))
                {
                    newBtrId = bt["EmployeeBlock"];
                }
                else
                {
                    Point3d center = new Point3d(0, 0, 0);
                    // Declare and define the entities we want to add:
                    // Circle:
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2);

                    // Attribute Definition
                    AttributeDefinition text = new AttributeDefinition(center, "NoName", "Name:", "Enter Name", db.Textstyle);
                    text.ColorIndex = 2;

                    // Ellipse:
                    Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, 0);

                    // Next, create a layer with the helper function, and assign the layer to our entities.
                    ObjectId empId = CreateLayer();
                    text.LayerId = empId;
                    circle.LayerId = empId;
                    ellipse.LayerId = empId;
                    // Set the color for each entity irrespective of the layer's color.
                    text.ColorIndex = 2;
                    circle.ColorIndex = 1;
                    ellipse.ColorIndex = 3;

                    // Create a new block definition called EmployeeBlock
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "EmployeeBlock";
                    newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function
                    trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database!

                    newBtr.AppendEntity(circle); //Append our entities...
                    newBtr.AppendEntity(text);
                    newBtr.AppendEntity(ellipse);
                    trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities.
                    trans.AddNewlyCreatedDBObject(text, true);
                    trans.AddNewlyCreatedDBObject(ellipse, true);
                }

                trans.Commit(); //All done, no errors?  Go ahead and commit!
            }
            return newBtrId;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Creates a ring.
 /// </summary>
 /// <param name="number">The number.</param>
 /// <param name="name">The name.</param>
 /// <param name="level">The level.</param>
 /// <param name="durability">The durability.</param>
 /// <param name="optionTargetAttribute">The option target attribute.</param>
 /// <param name="resistanceAttribute">The resistance attribute.</param>
 /// <remarks>
 /// Rings always have defensive excellent options.
 /// </remarks>
 private void CreateRing(byte number, string name, byte level, byte durability, AttributeDefinition optionTargetAttribute, AttributeDefinition resistanceAttribute)
 {
     this.CreateJewelery(number, 10, true, name, level, durability, this.GameConfiguration.ExcellentDefenseOptions(), optionTargetAttribute, resistanceAttribute);
 }
Exemplo n.º 23
0
        //This function creates a new BlockReference to the "EmployeeBlock" object,
        //and adds it to ModelSpace.
        public static ObjectId CreateEmployee(String name, String division, Double salary, Point3d pos)
        {
            Database    db    = HostApplicationServices.WorkingDatabase;
            Transaction trans = db.TransactionManager.StartTransaction();

            try
            {
                BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                //Create the block reference...use the return from CreateEmployeeDefinition directly!
                BlockReference br = new BlockReference(pos, CreateEmployeeDefinition());
                // create a new attribute reference
                AttributeReference attRef = new AttributeReference();

                //Iterate the employee block and find the attribute definition
                BlockTableRecord empBtr = (BlockTableRecord)trans.GetObject(bt["EmployeeBlock"], OpenMode.ForRead);

                foreach (ObjectId id in empBtr)
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false);                          //Use it to open the current object!
                    if (ent.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.AttributeDefinition")) //We use .NET//s RTTI to establish type.
                    {
                        //Set the properties from the attribute definition on our attribute reference
                        AttributeDefinition attDef = (AttributeDefinition)ent;
                        attRef.SetPropertiesFrom(attDef);
                        attRef.Position = new Point3d(attDef.Position.X + br.Position.X,
                                                      attDef.Position.Y + br.Position.Y,
                                                      attDef.Position.Z + br.Position.Z);

                        attRef.Height     = attDef.Height;
                        attRef.Rotation   = attDef.Rotation;
                        attRef.Tag        = attDef.Tag;
                        attRef.TextString = name;
                    }
                }
                btr.AppendEntity(br);                 //Add the reference to ModelSpace

                //Add the attribute reference to the block reference
                br.AttributeCollection.AppendAttribute(attRef);

                //let the transaction know
                trans.AddNewlyCreatedDBObject(attRef, true);
                trans.AddNewlyCreatedDBObject(br, true);                 //Let the transaction know about it

                //Create the custom per-employee data
                Xrecord xRec = new Xrecord();
                //We want to add //Name//, //Salary// and //Division// information.  Here is how:
                xRec.Data = new ResultBuffer(
                    new TypedValue((int)DxfCode.Text, name),
                    new TypedValue((int)DxfCode.Real, salary),
                    new TypedValue((int)DxfCode.Text, division));

                //Next, we need to add this data to the //Extension Dictionary// of the employee.
                br.CreateExtensionDictionary();
                DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false);
                brExtDict.SetAt("EmployeeData", xRec);                 //Set our XRecord in the dictionary at //EmployeeData//.
                trans.AddNewlyCreatedDBObject(xRec, true);

                trans.Commit();

                //return the objectId of the employee block reference
                return(br.ObjectId);
            }
            finally
            {
                trans.Dispose();
            }
        }
Exemplo n.º 24
0
 public T GetAttributeValue <T>(AttributeDefinition attributeDefinition)
 {
     return((T)_attributeValues[attributeDefinition.Token]);
 }
 protected BaseAggregateAttributeDefinition(AttributeDefinition left, string suffix)
     : base(left.AssetType, left.Name + "." + suffix, false, null, false)
 {
     _left = left;
 }
Exemplo n.º 26
0
        public void TestAttributeSchemaFromClass()
        {
            AttributeDefinition def = new AttributeDefinition();

            def.SchemaFromClass(typeof(ClassForTestingSchemaGeneration));

            Assert.IsType <Dictionary <string, object> >(def.Schema);
            Dictionary <string, object> schemaDict = def.Schema as Dictionary <string, object>;

            Assert.Collection(schemaDict,
                              (pair) => {
                Assert.Equal("VeryLongString", pair.Key);
                Assert.Equal("file", pair.Value);
            },
                              (pair) => {
                Assert.Equal("ExampleInt", pair.Key);
                Assert.Equal("int", pair.Value);
            },
                              (pair) => {
                Assert.Equal("ExampleString", pair.Key);
                Assert.Equal("string", pair.Value);
            },
                              (pair) => {
                Assert.Equal("[ExampleIntArray]", pair.Key);
                Assert.Equal("int", pair.Value);
            },
                              (pair) => {
                Assert.Equal("[ExampleStringArray]", pair.Key);
                Assert.Equal("string", pair.Value);
            },
                              (pair) => {
                Assert.Equal("[ExampleIntList]", pair.Key);
                Assert.Equal("int", pair.Value);
            },
                              (pair) => {
                Assert.Equal("[ExampleStringList]", pair.Key);
                Assert.Equal("string", pair.Value);
            },
                              (pair) => {
                Assert.Equal("Nested", pair.Key);
                Assert.Collection(pair.Value as Dictionary <string, object>,
                                  (pair) => {
                    Assert.Equal("ExampleString", pair.Key);
                    Assert.Equal("string", pair.Value);
                },
                                  (pair) => {
                    Assert.Equal("[ExampleIntArray]", pair.Key);
                    Assert.Equal("int", pair.Value);
                }
                                  );
            },
                              (pair) => {
                Assert.Equal("[NestedList]", pair.Key);
                Assert.Collection(pair.Value as Dictionary <string, object>,
                                  (pair) => {
                    Assert.Equal("ExampleString", pair.Key);
                    Assert.Equal("string", pair.Value);
                },
                                  (pair) => {
                    Assert.Equal("[ExampleIntArray]", pair.Key);
                    Assert.Equal("int", pair.Value);
                }
                                  );
            }
                              );
        }
Exemplo n.º 27
0
 internal void LoadAttribute(AttributeDefinition attributeDefinition, object value)
 {
     _attributeValues.Add(attributeDefinition.Token, value);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of <c>AttributeDefinitionDictionaryEventArgs</c>.
 /// </summary>
 /// <param name="item">Item that is being added or removed from the dictionary.</param>
 public AttributeDefinitionDictionaryEventArgs(AttributeDefinition item)
 {
     this.item   = item;
     this.cancel = false;
 }
Exemplo n.º 29
0
 /// <inheritdoc />
 public IElement GetOrCreateAttribute(AttributeDefinition attributeDefinition)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 30
0
        //This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock",
        //creating it if necessary.  The block contains three entities - circle, text
        //and ellipse.
        public static ObjectId CreateEmployeeDefinition()
        {
            ObjectId    newBtrId = ObjectId.Null;                            //The return value for this function
            Database    db       = HostApplicationServices.WorkingDatabase;  //save some space
            Transaction trans    = db.TransactionManager.StartTransaction(); // begin the transaction

            try
            {
                //Now, drill into the database and obtain a reference to the BlockTable
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                if (bt.Has("EmployeeBlock"))
                {
                    newBtrId = bt["EmployeeBlock"];                     //Already there...no need to recreate it!
                }
                else
                {
                    Point3d center = new Point3d(0, 0, 0);                     //convenient declaration...

                    //Declare and define the entities we want to add:
                    //Circle:
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2.0);

                    //Attribute
                    AttributeDefinition attDef = new AttributeDefinition(center, "NoName", "Name:", "Enter Name", db.Textstyle);

                    //Ellipse:
                    Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0.0, 0.0);

                    //Next, create a layer with the helper function, and assign
                    //the layer to our entities.
                    ObjectId empId = CreateLayer();
                    circle.LayerId  = empId;
                    ellipse.LayerId = empId;
                    //Set the color for each entity irrespective of the layer//s color.
                    attDef.ColorIndex  = 2;
                    circle.ColorIndex  = 1;
                    ellipse.ColorIndex = 3;

                    //Create a new block definition called EmployeeBlock
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "EmployeeBlock";
                    newBtrId    = bt.Add(newBtr);                  //Add the block, and set the id as the return value of our function
                    trans.AddNewlyCreatedDBObject(newBtr, true);   //Let the transaction know about any object/entity you add to the database!

                    newBtr.AppendEntity(circle);                   //Append our entities...
                    newBtr.AppendEntity(attDef);
                    newBtr.AppendEntity(ellipse);
                    trans.AddNewlyCreatedDBObject(circle, true);                     //Again, let the transaction know about our newly added entities.
                    trans.AddNewlyCreatedDBObject(attDef, true);
                    trans.AddNewlyCreatedDBObject(ellipse, true);
                }
                trans.Commit();                 //All done, no errors?  Go ahead and commit!
            }
            catch
            {
                MessageBox.Show("Error Creating Employee Block");                 //Uh oh!
            }

            //CreateDivision() //Create the Employee Division dictionaries.
            return(newBtrId);
        }         // end of CreateEmployeeDefinition
        public void SetUp()
        {
            var assemblies = new[]
            {
                typeof(Rebel.Tests.Extensions.TestDynamicExtensions).Assembly
            };
            var supportedDynamicTypes = new[]
            {
                typeof(Content),
                typeof(BendyObject)
            };
            var supportedDynamicFieldTypes = new[]
            {
                typeof(Content),
                typeof(TypedAttribute),
                typeof(BendyObject)
            };
            var bendyMethods    = DynamicExtensionsHelper.GetExtensions(assemblies, supportedDynamicTypes);
            var subBendyMethods = DynamicExtensionsHelper.GetExtensions <DynamicFieldExtensionAttribute>(assemblies, supportedDynamicFieldTypes);

            var bendy = new BendyObject();

            BendyObjectExtensionsHelper.ApplyDynamicExtensions <Content>(bendy, bendyMethods);

            var content = new Content();

            _bendy = bendy;
            _bendy["__OriginalItem"] = content;

            var attrType1 = new AttributeType {
                RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId
            };
            var attrDef1 = new AttributeDefinition {
                AttributeType = attrType1
            };
            var attr1 = new TypedAttribute(attrDef1);

            var subBendy1 = new BendyObject();

            subBendy1["__OriginalItem"] = attr1;
            subBendy1.AddLazy("__Parent", () => bendy);
            subBendy1["__ParentKey"] = "Test";

            BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.FileUploadPropertyEditorId, subBendy1, subBendyMethods);

            _bendy["Test"] = subBendy1;

            var attrType2 = new AttributeType {
                RenderTypeProvider = CorePluginConstants.TreeNodePickerPropertyEditorId
            };
            var attrDef2 = new AttributeDefinition {
                AttributeType = attrType2
            };
            var attr2 = new TypedAttribute(attrDef2);

            var subBendy2 = new BendyObject();

            subBendy2["__OriginalItem"] = attr2;
            subBendy2.AddLazy("__Parent", () => bendy);
            subBendy2["__ParentKey"] = "Test2";

            BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.TreeNodePickerPropertyEditorId, subBendy2, subBendyMethods);

            _bendy["Test2"] = subBendy2;
        }
 public void Init(ParsingContext context, ParseTreeNode parseNode)
 {
     AttributeDefinition = new AttributeDefinition(((EdgeTypeNode)parseNode.ChildNodes[0].AstNode).DBTypeDefinition,
                                                     parseNode.ChildNodes[1].Token.ValueString,
                                                     ((AttrDefaultValueNode)(parseNode.ChildNodes[2].AstNode)).Value);
 }
Exemplo n.º 33
0
        /// <summary>
        /// Рекурсивное получение габаритного контейнера для выбранного примитива.
        /// </summary>
        /// <param name="en">Имя примитива</param>
        /// <param name="ext">Габаритный контейнер</param>
        /// <param name="mat">Матрица преобразования из системы координат блока в МСК.</param>
        void GetBlockExtents(Entity en, ref Extents3d ext, ref Matrix3d mat)
        {
            if (!IsLayerOn(en.LayerId))
            {
                return;
            }
            if (en is BlockReference)
            {
                BlockReference bref   = en as BlockReference;
                Matrix3d       matIns = mat * bref.BlockTransform;
                using (BlockTableRecord btr =
                           bref.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord)
                {
                    foreach (ObjectId id in btr)
                    {
                        using (DBObject obj = id.GetObject(OpenMode.ForRead) as DBObject)
                        {
                            Entity enCur = obj as Entity;
                            if (enCur == null || enCur.Visible != true)
                            {
                                continue;
                            }
                            // Пропускаем неконстантные и невидимые определения атрибутов
                            AttributeDefinition attDef = enCur as AttributeDefinition;
                            if (attDef != null && (!attDef.Constant || attDef.Invisible))
                            {
                                continue;
                            }
                            GetBlockExtents(enCur, ref ext, ref matIns);
                        }
                    }
                }

                // Отдельно обрабатываем атрибуты блока
                if (bref.AttributeCollection.Count > 0)
                {
                    foreach (ObjectId idAtt in bref.AttributeCollection)
                    {
                        using (AttributeReference attRef =
                                   idAtt.GetObject(OpenMode.ForRead) as AttributeReference)
                        {
                            if (!attRef.Invisible && attRef.Visible)
                            {
                                GetBlockExtents(attRef, ref ext, ref mat);
                            }
                        }
                    }
                }
            }
            else
            {
                if (mat.IsUniscaledOrtho())
                {
                    using (Entity enTr = en.GetTransformedCopy(mat))
                    {
                        if (enTr is Dimension)
                        {
                            (enTr as Dimension).RecomputeDimensionBlock(true);
                        }
                        if (enTr is Table)
                        {
                            (enTr as Table).RecomputeTableBlock(true);
                        }
                        if (IsEmptyExt(ref ext))
                        {
                            try
                            {
                                ext = enTr.GeometricExtents;
                            }
                            catch
                            {
                                // ignored
                            }
                        }
                        else
                        {
                            try
                            {
                                ext.AddExtents(enTr.GeometricExtents);
                            }
                            catch
                            {
                                // ignored
                            }
                        }

                        return;
                    }
                }
                else
                {
                    try
                    {
                        Extents3d curExt = en.GeometricExtents;
                        curExt.TransformBy(mat);
                        if (IsEmptyExt(ref ext))
                        {
                            ext = curExt;
                        }
                        else
                        {
                            ext.AddExtents(curExt);
                        }
                    }
                    catch
                    {
                    }

                    return;
                }
            }
        }
 public ParameterAttributeBuilder(AttributeDefinition attributeDefinition)
 {
     _attributeDefinition = attributeDefinition;
 }
Exemplo n.º 35
0
        internal bool RemoveEntity(EntityObject entity, bool isBlockEntity)
        {
            if (entity == null)
            {
                return(false);
            }

            if (entity.Reactor != null)
            {
                return(false);
            }

            if (!this.AddedObjects.ContainsKey(entity.Handle))
            {
                return(false);
            }

            // the entities that are part of a block do not belong to any of the entities lists but to the block definition
            // and they will not be removed from the drawing database
            bool removed;

            switch (entity.Type)
            {
            case EntityType.Arc:
                removed = this.arcs.Remove((Arc)entity);
                break;

            case EntityType.Circle:
                removed = this.circles.Remove((Circle)entity);
                break;

            case EntityType.Dimension:
                removed = this.dimensions.Remove((Dimension)entity);
                if (removed || isBlockEntity)
                {
                    this.dimStyles.References[((Dimension)entity).Style.Name].Remove(entity);
                    this.blocks.References[((Dimension)entity).Block.Name].Remove(entity);
                }
                break;

            case EntityType.Ellipse:
                removed = this.ellipses.Remove((Ellipse)entity);
                break;

            case EntityType.Face3D:
                removed = this.faces3d.Remove((Face3d)entity);
                break;

            case EntityType.Spline:
                removed = this.splines.Remove((Spline)entity);
                break;

            case EntityType.Hatch:
                removed = this.hatches.Remove((Hatch)entity);
                break;

            case EntityType.Insert:
                removed = this.inserts.Remove((Insert)entity);
                if (removed || isBlockEntity)
                {
                    this.blocks.References[((Insert)entity).Block.Name].Remove(entity);
                    foreach (Attribute att in ((Insert)entity).Attributes.Values)
                    {
                        this.layers.References[att.Layer.Name].Remove(att);
                        this.lineTypes.References[att.LineType.Name].Remove(att);
                        this.textStyles.References[att.Style.Name].Remove(att);
                    }
                }
                break;

            case EntityType.LightWeightPolyline:
                removed = this.lwPolylines.Remove((LwPolyline)entity);
                break;

            case EntityType.Line:
                removed = this.lines.Remove((Line)entity);
                break;

            case EntityType.Point:
                removed = this.points.Remove((Point)entity);
                break;

            case EntityType.PolyfaceMesh:
                removed = this.polyfaceMeshes.Remove((PolyfaceMesh)entity);
                break;

            case EntityType.Polyline:
                removed = this.polylines.Remove((Polyline)entity);
                break;

            case EntityType.Solid:
                removed = this.solids.Remove((Solid)entity);
                break;

            case EntityType.Mesh:
                removed = this.meshes.Remove((Mesh)entity);
                break;

            case EntityType.Text:
                Text text = (Text)entity;
                this.textStyles.References[text.Style.Name].Remove(entity);
                removed = this.texts.Remove(text);
                break;

            case EntityType.MText:
                MText mText = (MText)entity;
                this.textStyles.References[mText.Style.Name].Remove(entity);
                removed = this.mTexts.Remove(mText);
                break;

            case EntityType.Image:
                Image image = (Image)entity;
                removed = this.images.Remove(image);
                if (removed || isBlockEntity)
                {
                    this.imageDefs.References[image.Definition.Name].Remove(image);
                    image.Definition.Reactors.Remove(image.Handle);
                }
                break;

            case EntityType.MLine:
                removed = this.mLines.Remove((MLine)entity);
                if (removed || isBlockEntity)
                {
                    this.mlineStyles.References[((MLine)entity).Style.Name].Remove(entity);
                }
                break;

            case EntityType.Ray:
                removed = this.rays.Remove((Ray)entity);
                break;

            case EntityType.XLine:
                removed = this.xlines.Remove((XLine)entity);
                break;

            case EntityType.Viewport:
                Viewport viewport = (Viewport)entity;
                removed = this.viewports.Remove(viewport);
                // delete the viewport boundary entity in case there is one
                if (removed && viewport.ClippingBoundary != null)
                {
                    viewport.ClippingBoundary.Reactor = null;
                    RemoveEntity(viewport.ClippingBoundary);
                }
                break;

            case EntityType.AttributeDefinition:
                AttributeDefinition attDef = (AttributeDefinition)entity;
                this.textStyles.References[attDef.Style.Name].Remove(entity);
                removed = this.attributeDefinitions.Remove(attDef);
                break;

            case EntityType.Attribute:
                throw new ArgumentException("The entity " + entity.Type + " is only allowed as part of another entity", "entity");

            default:
                throw new ArgumentException("The entity " + entity.Type + " is not implemented or unknown");
            }

            if (removed || isBlockEntity)
            {
                this.layouts.References[entity.Owner.Record.Layout.Name].Remove(entity);
                this.layers.References[entity.Layer.Name].Remove(entity);
                this.lineTypes.References[entity.LineType.Name].Remove(entity);
                foreach (string appReg in entity.XData.Keys)
                {
                    this.appRegistries.References[appReg].Remove(entity);
                }
                this.AddedObjects.Remove(entity.Handle);

                entity.Owner = null;
            }

            return(removed);
        }
Exemplo n.º 36
0
        public static ObjectId Insert(string blockPath, string blockName, bool scaleBlock = false, Scale3d scaleFactor = default(Scale3d))
        {
            ObjectId id = new ObjectId();

            using (World.Docu.LockDocument()) {
                using (Database db = World.Docu.Database) {
                    using (Transaction tr = db.TransactionManager.StartTransaction()) {
                        using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) {
                            if (AcadIO.Insert.DB.AddBlock(blockPath + "\\" + blockName) == false)
                            {
                                return(id);
                            }

                            using (BlockReference br = new BlockReference(Point3d.Origin, bt[blockName])) {
                                PromptResult pr = World.Docu.Editor.Drag(new Jigs.InsertBlockJig(br));
                                if (pr.Status == PromptStatus.Cancel | pr.Status == PromptStatus.Error | pr.Status == PromptStatus.None)
                                {
                                    return(id);
                                }

                                pr = World.Docu.Editor.Drag(new Jigs.RotateBlockJig(br));
                                if (pr.Status == PromptStatus.Cancel | pr.Status == PromptStatus.Error | pr.Status == PromptStatus.None)
                                {
                                    return(id);
                                }

                                using (BlockTableRecord drawingSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) {
                                    if (scaleBlock == true)
                                    {
                                        //br.ScaleFactors = new Autodesk.AutoCAD.Geometry.Scale3d(World.UnitFactor);
                                        br.ScaleFactors = scaleFactor;
                                    }

                                    drawingSpace.AppendEntity(br);
                                    tr.AddNewlyCreatedDBObject(br, true);

                                    if (AcadIO.Layers.IsObjectLayerLocked(br.ObjectId))
                                    {
                                        World.Docu.Editor.WriteMessage(Environment.NewLine + "BCAD: Cannot insert on locked layer" + Environment.NewLine); return(id);
                                    }

                                    using (BlockTableRecord attributeBlockTableRecord = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForWrite)) {
                                        foreach (ObjectId attributeId in attributeBlockTableRecord)
                                        {
                                            if (attributeId.ObjectClass.Name == "AcDbAttributeDefinition")
                                            {
                                                using (AttributeDefinition attributedef = (AttributeDefinition)tr.GetObject(attributeId, OpenMode.ForWrite)) {
                                                    AttributeReference attributeref = new AttributeReference();
                                                    attributeref.SetAttributeFromBlock(attributedef, br.BlockTransform);
                                                    br.AttributeCollection.AppendAttribute(attributeref);
                                                    tr.AddNewlyCreatedDBObject(attributeref, true);
                                                }
                                            }
                                        }
                                    }

                                    id = br.ObjectId;
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }

            return(id);
        }
Exemplo n.º 37
0
        internal bool AddEntity(EntityObject entity, bool isBlockEntity, bool assignHandle)
        {
            // no null entities allowed
            if (entity == null)
            {
                return(false);
            }

            if (!string.IsNullOrEmpty(entity.Handle))
            {
                // check if the entity handle has been assigned
                if (this.AddedObjects.ContainsKey(entity.Handle))
                {
                    // if the handle is equal the entity might come from another document, check if it is exactly the same object
                    DxfObject existing = this.AddedObjects[entity.Handle];
                    // if the entity is already in the document return false, do not add it again
                    if (existing.Equals(entity))
                    {
                        return(false);
                    }
                }
            }

            if (assignHandle)
            {
                this.NumHandles = entity.AsignHandle(this.NumHandles);
            }

            // the entities that are part of a block do not belong to any of the entities lists but to the block definition.
            switch (entity.Type)
            {
            case EntityType.Arc:
                if (!isBlockEntity)
                {
                    this.arcs.Add((Arc)entity);
                }
                break;

            case EntityType.Circle:
                if (!isBlockEntity)
                {
                    this.circles.Add((Circle)entity);
                }
                break;

            case EntityType.Dimension:
                if (!isBlockEntity)
                {
                    this.dimensions.Add((Dimension)entity);
                }
                ((Dimension)entity).Style = this.dimStyles.Add(((Dimension)entity).Style);
                this.dimStyles.References[((Dimension)entity).Style.Name].Add(entity);

                // create the block that represent the dimension drawing
                Block dimBlock = ((Dimension)entity).Block;
                if (dimBlock == null)
                {
                    dimBlock = ((Dimension)entity).BuildBlock("*D" + ++this.DimensionBlocksGenerated);
                    if (this.blocks.Contains(dimBlock.Name))
                    {
                        throw new ArgumentException("The list already contains the block: " + dimBlock.Name + ". The block names that start with *D are reserverd for dimensions");
                    }
                    dimBlock.Flags = BlockTypeFlags.AnonymousBlock;
                }
                this.blocks.Add(dimBlock);
                this.blocks.References[dimBlock.Name].Add(entity);
                break;

            case EntityType.Ellipse:
                if (!isBlockEntity)
                {
                    this.ellipses.Add((Ellipse)entity);
                }
                break;

            case EntityType.Face3D:
                if (!isBlockEntity)
                {
                    this.faces3d.Add((Face3d)entity);
                }
                break;

            case EntityType.Spline:
                if (!isBlockEntity)
                {
                    this.splines.Add((Spline)entity);
                }
                break;

            case EntityType.Hatch:
                Hatch hatch = (Hatch)entity;
                hatch.AddPatternXData();
                if (!isBlockEntity)
                {
                    this.hatches.Add(hatch);
                }
                break;

            case EntityType.Insert:
                ((Insert)entity).Block = this.blocks.Add(((Insert)entity).Block);
                this.blocks.References[((Insert)entity).Block.Name].Add(entity);
                foreach (Attribute attribute in ((Insert)entity).Attributes.Values)
                {
                    attribute.Layer = this.layers.Add(attribute.Layer);
                    this.layers.References[attribute.Layer.Name].Add(attribute);

                    attribute.LineType = this.lineTypes.Add(attribute.LineType);
                    this.lineTypes.References[attribute.LineType.Name].Add(attribute);

                    attribute.Style = this.textStyles.Add(attribute.Style);
                    this.textStyles.References[attribute.Style.Name].Add(attribute);
                }
                if (!isBlockEntity)
                {
                    this.inserts.Add((Insert)entity);
                }
                break;

            case EntityType.LightWeightPolyline:
                if (!isBlockEntity)
                {
                    this.lwPolylines.Add((LwPolyline)entity);
                }
                break;

            case EntityType.Line:
                if (!isBlockEntity)
                {
                    this.lines.Add((Line)entity);
                }
                break;

            case EntityType.Point:
                if (!isBlockEntity)
                {
                    this.points.Add((Point)entity);
                }
                break;

            case EntityType.PolyfaceMesh:
                if (!isBlockEntity)
                {
                    this.polyfaceMeshes.Add((PolyfaceMesh)entity);
                }
                break;

            case EntityType.Polyline:
                if (!isBlockEntity)
                {
                    this.polylines.Add((Polyline)entity);
                }
                break;

            case EntityType.Solid:
                if (!isBlockEntity)
                {
                    this.solids.Add((Solid)entity);
                }
                break;

            case EntityType.Mesh:
                if (!isBlockEntity)
                {
                    this.meshes.Add((Mesh)entity);
                }
                break;

            case EntityType.Text:
                Text text = (Text)entity;
                text.Style = this.textStyles.Add(text.Style);
                this.textStyles.References[text.Style.Name].Add(entity);
                if (!isBlockEntity)
                {
                    this.texts.Add(text);
                }
                break;

            case EntityType.MText:
                MText mText = (MText)entity;
                mText.Style = this.textStyles.Add(mText.Style);
                this.textStyles.References[mText.Style.Name].Add(entity);
                if (!isBlockEntity)
                {
                    this.mTexts.Add(mText);
                }
                break;

            case EntityType.Image:
                Image image = (Image)entity;
                image.Definition = this.imageDefs.Add(image.Definition);
                this.imageDefs.References[image.Definition.Name].Add(image);
                if (!image.Definition.Reactors.ContainsKey(image.Handle))
                {
                    ImageDefReactor reactor = new ImageDefReactor(image.Handle);
                    this.NumHandles = reactor.AsignHandle(this.NumHandles);
                    image.Definition.Reactors.Add(image.Handle, reactor);
                }
                if (!isBlockEntity)
                {
                    this.images.Add(image);
                }
                break;

            case EntityType.MLine:
                ((MLine)entity).Style = this.mlineStyles.Add(((MLine)entity).Style);
                this.mlineStyles.References[((MLine)entity).Style.Name].Add(entity);
                if (!isBlockEntity)
                {
                    this.mLines.Add((MLine)entity);
                }
                break;

            case EntityType.Ray:
                if (!isBlockEntity)
                {
                    this.rays.Add((Ray)entity);
                }
                break;

            case EntityType.XLine:
                if (!isBlockEntity)
                {
                    this.xlines.Add((XLine)entity);
                }
                break;

            case EntityType.Viewport:
                Viewport viewport = (Viewport)entity;
                if (!isBlockEntity)
                {
                    this.viewports.Add(viewport);
                }
                this.AddEntity(viewport.ClippingBoundary, isBlockEntity, assignHandle);
                break;

            case EntityType.AttributeDefinition:
                AttributeDefinition attDef = (AttributeDefinition)entity;
                attDef.Style = this.textStyles.Add(attDef.Style);
                this.textStyles.References[attDef.Style.Name].Add(entity);
                if (!isBlockEntity)
                {
                    this.attributeDefinitions.Add(attDef);
                }
                break;

            case EntityType.Attribute:
                throw new ArgumentException("The entity " + entity.Type + " is only allowed as part of an insert entity.", "entity");

            default:
                throw new ArgumentException("The entity " + entity.Type + " is not implemented or unknown.");
            }

            foreach (string appReg in entity.XData.Keys)
            {
                entity.XData[appReg].ApplicationRegistry = this.appRegistries.Add(entity.XData[appReg].ApplicationRegistry);
                this.appRegistries.References[appReg].Add(entity);
            }

            if (!isBlockEntity && this.layouts != null)
            {
                entity.Owner = this.layouts[this.activeLayout].AssociatedBlock;
                this.layouts.References[this.activeLayout].Add(entity);
            }

            this.AddedObjects.Add(entity.Handle, entity);

            if (this.layers != null)
            {
                entity.Layer = this.layers.Add(entity.Layer);
                this.layers.References[entity.Layer.Name].Add(entity);
            }

            if (this.lineTypes != null)
            {
                entity.LineType = this.lineTypes.Add(entity.LineType);
                this.lineTypes.References[entity.LineType.Name].Add(entity);
            }

            /*if (!isBlockEntity)
             * {
             *  entity.Owner = this.layouts[this.activeLayout].AssociatedBlock;
             *  this.layouts.References[this.activeLayout].Add(entity);
             * }
             *
             * this.AddedObjects.Add(entity.Handle, entity);
             *
             * entity.Layer = this.layers.Add(entity.Layer);
             * this.layers.References[entity.Layer.Name].Add(entity);
             *
             * entity.LineType = this.lineTypes.Add(entity.LineType);
             * this.lineTypes.References[entity.LineType.Name].Add(entity);*/
            return(true);
        }
Exemplo n.º 38
0
        protected virtual string GetAttribute(AttributeDefinition attributeDefinition)
        {
            if (attributeDefinition.Members.Count == 0)
                return string.Format("[{0}]", attributeDefinition.Name);
            var attributeLineBuilder = new StringBuilder(1024);

            attributeLineBuilder.AppendFormat("[{0}(", attributeDefinition.Name);
            var members = new List<string>();
            foreach (var keyValue in attributeDefinition.Members)
                members.Add(string.Format("{0} = {1}", keyValue.Key, GetLiteralValue(keyValue.Value)));
            attributeLineBuilder.Append(string.Join(", ", members.ToArray()));
            attributeLineBuilder.Append(")]");

            return attributeLineBuilder.ToString();
        }
Exemplo n.º 39
0
        public override QueryOver <NodeVersion> VisitFieldPredicate(FieldPredicateExpression node)
        {
            var fieldName      = node.SelectorExpression.FieldName;
            var valueKey       = node.SelectorExpression.ValueKey;
            var fieldValue     = node.ValueExpression.Value;
            var fieldValueType = fieldValue != null?fieldValue.GetType() : typeof(string);

            switch (fieldName.ToLowerInvariant())
            {
            case "id":
                Guid idValue = GetIdValue(node);

                switch (node.ValueExpression.ClauseType)
                {
                case ValuePredicateType.Equal:
                    return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id == idValue).Select(x => x.Id));

                case ValuePredicateType.NotEqual:
                    return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id != idValue).Select(x => x.Id));;

                default:
                    throw new InvalidOperationException(
                              "Cannot query an item by id by any other operator than == or !=");
                }
            }

            // First look up the types of the main field
            AttributeDefinition defAlias  = null;
            AttributeType       typeAlias = null;
            var attributeType             = _activeSession.QueryOver <AttributeDefinition>(() => defAlias)
                                            .JoinAlias(() => defAlias.AttributeType, () => typeAlias)
                                            .Where(() => defAlias.Alias == fieldName)
                                            .Select(x => typeAlias.PersistenceTypeProvider)
                                            .List <string>();

            var typesAlreadyEstablished = new List <string>();
            var typesToQuery            = new List <DataSerializationTypes>();

            foreach (var type in attributeType)
            {
                var typeName = type;
                if (typesAlreadyEstablished.Contains(typeName))
                {
                    continue;
                }
                try
                {
                    typesAlreadyEstablished.Add(typeName);
                    var persisterType = Type.GetType(typeName, false);
                    if (persisterType != null)
                    {
                        var persisterInstance = Activator.CreateInstance(persisterType) as IAttributeSerializationDefinition;
                        if (persisterInstance != null)
                        {
                            typesToQuery.Add(persisterInstance.DataSerializationType);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            // U5-789
            // Workaround pending a better check of what data is actually saved
            // An issue arose because previous data had been saved in long-string,
            // but the datatype changed to be just string, therefore only string was
            // being queried despite all the data residing still in long-string
            if (typesToQuery.Contains(DataSerializationTypes.String) && !typesToQuery.Contains(DataSerializationTypes.LongString))
            {
                typesToQuery.Add(DataSerializationTypes.LongString);
            }

            NodeVersion              aliasNodeVersion         = null;
            Attribute                aliasAttribute           = null;
            AttributeDefinition      aliasAttributeDefinition = null;
            AttributeStringValue     aliasStringValue         = null;
            AttributeLongStringValue aliasLongStringValue     = null;
            AttributeIntegerValue    aliasIntegerValue        = null;
            AttributeDecimalValue    aliasDecimalValue        = null;
            NodeRelation             aliasNodeRelation        = null;
            AttributeDateValue       aliasDateValue           = null;

            QueryOver <NodeVersion, AttributeDefinition> queryExtender = QueryOver.Of <NodeVersion>(() => aliasNodeVersion)
                                                                         .JoinQueryOver <Attribute>(() => aliasNodeVersion.Attributes, () => aliasAttribute)
                                                                         .JoinQueryOver <AttributeDefinition>(() => aliasAttribute.AttributeDefinition, () => aliasAttributeDefinition);

            int numberOfMatchesEvaluated         = 0;
            AbstractCriterion restrictionBuilder = null;

            foreach (var dataSerializationTypese in typesToQuery.Distinct())
            {
                AbstractCriterion           restriction        = null;
                Expression <Func <object> > propertyExpression = null;
                Expression <Func <object> > subkeyExpression   = null;
                List <ValuePredicateType>   validClauseTypes   = null;
                var useLikeMatchForStrings = false;
                switch (dataSerializationTypese)
                {
                case DataSerializationTypes.SmallInt:
                case DataSerializationTypes.LargeInt:
                case DataSerializationTypes.Boolean:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeIntegerValues, () => aliasIntegerValue);
                    propertyExpression = () => aliasIntegerValue.Value;
                    subkeyExpression   = () => aliasIntegerValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual
                    };
                    break;

                case DataSerializationTypes.Decimal:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDecimalValues, () => aliasDecimalValue);
                    propertyExpression = () => aliasDecimalValue.Value;
                    subkeyExpression   = () => aliasDecimalValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual
                    };
                    break;

                case DataSerializationTypes.String:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeStringValues, () => aliasStringValue);
                    propertyExpression = () => aliasStringValue.Value;
                    subkeyExpression   = () => aliasStringValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Contains,
                        ValuePredicateType.StartsWith,
                        ValuePredicateType.EndsWith,
                        ValuePredicateType.MatchesWildcard
                    };
                    break;

                case DataSerializationTypes.LongString:
                    queryExtender          = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeLongStringValues, () => aliasLongStringValue);
                    propertyExpression     = () => aliasLongStringValue.Value;
                    subkeyExpression       = () => aliasLongStringValue.ValueKey;
                    useLikeMatchForStrings = true;
                    validClauseTypes       = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Contains,
                        ValuePredicateType.StartsWith,
                        ValuePredicateType.EndsWith,
                        ValuePredicateType.MatchesWildcard
                    };
                    break;

                case DataSerializationTypes.Date:
                    queryExtender      = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDateValues, () => aliasDateValue);
                    propertyExpression = () => aliasDateValue.Value;
                    subkeyExpression   = () => aliasDateValue.ValueKey;
                    validClauseTypes   = new List <ValuePredicateType>()
                    {
                        ValuePredicateType.Equal,
                        ValuePredicateType.GreaterThan,
                        ValuePredicateType.GreaterThanOrEqual,
                        ValuePredicateType.LessThan,
                        ValuePredicateType.LessThanOrEqual,
                        ValuePredicateType.NotEqual,
                        ValuePredicateType.Empty
                    };
                    break;
                }

                if (!validClauseTypes.Contains(node.ValueExpression.ClauseType))
                {
                    throw new InvalidOperationException("A field of type {0} cannot be queried with operator {1}".InvariantFormat(dataSerializationTypese.ToString(), node.ValueExpression.ClauseType.ToString()));
                }

                switch (node.ValueExpression.ClauseType)
                {
                case ValuePredicateType.Equal:
                    restriction = GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression, subkeyExpression, valueKey);
                    break;

                case ValuePredicateType.NotEqual:
                    restriction = !GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression);
                    break;

                case ValuePredicateType.LessThan:
                    restriction = GetRestrictionLt(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.LessThanOrEqual:
                    restriction = GetRestrictionLtEq(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.GreaterThan:
                    restriction = GetRestrictionGt(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.GreaterThanOrEqual:
                    restriction = GetRestrictionGtEq(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.Contains:
                    restriction = GetRestrictionContains(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.StartsWith:
                    restriction = GetRestrictionStarts(fieldValue, propertyExpression);
                    break;

                case ValuePredicateType.EndsWith:
                    restriction = GetRestrictionEnds(fieldValue, propertyExpression);
                    break;
                }

                if (restriction != null)
                {
                    if (numberOfMatchesEvaluated == 0)
                    {
                        restrictionBuilder = restriction;
                        numberOfMatchesEvaluated++;
                    }
                    else
                    {
                        restrictionBuilder = Restrictions.Or(restriction, restrictionBuilder);
                    }
                }
            }

            if (restrictionBuilder != null)
            {
                queryExtender = queryExtender.Where(restrictionBuilder);
            }

            queryExtender = queryExtender
                            .And(x => aliasAttributeDefinition.Alias == fieldName);

            return(queryExtender.Select(x => x.Id));
        }
Exemplo n.º 40
0
        /// <summary>
        /// Generates a attribute definition
        /// </summary>
        /// <param name="aAttribute">The attribute that is going to be transfered</param>
        /// <returns>A attribute predefinition</returns>
        private UnknownAttributePredefinition GenerateUnknownAttribute(AttributeDefinition myAttributeDefinition)
        {
            UnknownAttributePredefinition result = 
                new UnknownAttributePredefinition(myAttributeDefinition.AttributeName, 
                                                    myAttributeDefinition.AttributeType.Name);

            if (myAttributeDefinition.DefaultValue != null)
                result.SetDefaultValue(myAttributeDefinition.DefaultValue.ToString());

            switch (myAttributeDefinition.AttributeType.Type)
            {
                case SonesGQLGrammar.TERMINAL_SET:
                    result.SetMultiplicityAsSet();
                    break;

                case SonesGQLGrammar.TERMINAL_LIST:
                    result.SetMultiplicityAsList();
                    break;
            }

            return result;
        }
 public static AttributeDefinition CreateAttributeDefinition(string alias, string name, string description, AttributeType typeDef, AttributeGroup groupDef, bool assignId = false)
 {
     var definition = new AttributeDefinition();
     definition.Setup(alias, name);
     definition.AttributeType = typeDef;
     definition.Description = description;
     definition.AttributeGroup = groupDef;
     if (assignId)
         definition.Id = new HiveId(Guid.NewGuid());
     return definition;
 }
Exemplo n.º 42
0
 public void SetAttributeCallback(AttributeDefinition attributeDefinition, Action <AttributeValue> callback)
 {
     // no need for callbacks
 }
 public static TypedAttribute CreateAttribute(AttributeDefinition def, object value)
 {
     return new TypedAttribute(def, value);
 }
Exemplo n.º 44
0
        //returns a blockreference
        public static Extents3d InsertBlockRef(Point3d dblInsert, string strSourceBlockPath, double angle)
        {
            string strSourceBlockName = Path.GetFileName(strSourceBlockPath);

            BlockTable       bt;
            BlockTableRecord btr;
            BlockReference   br;
            //ObjectId id;

            Document doc = Acad.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btrSpace;

                //insert block
                bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite, true, true);

                //if block already exists in drawing retrieve it, if not create it from external drawing
                if (bt.Has(strSourceBlockName))
                {
                    br = new BlockReference(dblInsert, bt[strSourceBlockName]);
                    ObjectId id = bt[strSourceBlockName];
                    btr = (BlockTableRecord)trans.GetObject(id, OpenMode.ForRead, true, true);
                }
                else
                {
                    BlockTableRecord btrSource = GetBlock(strSourceBlockName, strSourceBlockPath);
                    btr = (BlockTableRecord)trans.GetObject(btrSource.ObjectId, OpenMode.ForRead, true, true);
                }
                //Get the current space
                btrSpace = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                //Get the Attributes from the block source and add references to them in the blockref's attribute collection
                AttributeCollection attColl;
                Entity ent;
                br = new BlockReference(dblInsert, btr.ObjectId);

                //get the extents BEFORE the block is rotated
                Extents3d ext = br.GeometricExtents;

                //rotates the block
                br.Rotation = angle;

                btrSpace.AppendEntity(br);
                trans.AddNewlyCreatedDBObject(br, true);
                attColl = br.AttributeCollection;

                foreach (ObjectId oid in btr)
                {
                    ent = (Entity)trans.GetObject(oid, OpenMode.ForRead, true, true);

                    if (ent.GetType() == typeof(AttributeDefinition))
                    {
                        AttributeDefinition attdef = (AttributeDefinition)ent;
                        AttributeReference  attref = new AttributeReference();
                        attref.SetAttributeFromBlock(attdef, br.BlockTransform);
                        attref.TextString = attdef.TextString;
                        attColl.AppendAttribute(attref);
                        trans.AddNewlyCreatedDBObject(attref, true);
                    }
                }
                trans.Commit();

                return(ext);
            }
        }
Exemplo n.º 45
0
        private void plotButton_Click(object sender, EventArgs e)
        {
            int      blockCount = 0;
            Document doc        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor   ed         = doc.Editor;
            Database db         = doc.Database;

            intervalPline = Convert.ToDouble(textBox2.Text);
            Database blockDB = new Database(true, true);
            ObjectId insertedBlockId;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    double     lengthToNextVertex = 0;
                    DBObject   obj      = tr.GetObject(prmtEnt.ObjectId, OpenMode.ForRead);
                    Polyline3d polyline = obj as Polyline3d;
                    if (polyline != null)
                    {
                        List <ObjectId> vertices = new List <ObjectId>();
                        foreach (ObjectId id in polyline)
                        {
                            vertices.Add(id);
                        }
                        for (int i = 0; i < vertices.Count - 1; i++)
                        {
                            PolylineVertex3d vertex     = tr.GetObject(vertices[i], OpenMode.ForRead) as PolylineVertex3d;
                            PolylineVertex3d nextVertex = tr.GetObject(vertices[i + 1], OpenMode.ForRead) as PolylineVertex3d;
                            BlockTable       blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                            Double           length     = vertex.Position.DistanceTo(nextVertex.Position);
                            lengthToNextVertex += length;
                            if (checkEveryVertext.CheckState != CheckState.Checked)
                            {
                                while (lengthToNextVertex >= intervalPline)
                                {
                                    Point3d pt = GetPt(vertex.Position, nextVertex.Position, intervalPline - (lengthToNextVertex - length));
                                    lengthToNextVertex -= intervalPline;
                                    if (blockTable.Has(blockName))
                                    {
                                        BlockTableRecord blockTableRecord = blockTable[blockName].GetObject(OpenMode.ForRead) as BlockTableRecord;
                                        if (blockTable != null)
                                        {
                                            using (BlockReference spotHeight = new BlockReference(pt, blockTableRecord.ObjectId))
                                            {
                                                blockCount++;
                                                using (DocumentLock doclock = doc.LockDocument())
                                                {
                                                    spotHeight.ScaleFactors = new Autodesk.AutoCAD.Geometry.Scale3d(blockScale, blockScale, blockScale);
                                                    BlockTableRecord blocktableRec = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                                    blocktableRec.AppendEntity(spotHeight);
                                                    tr.AddNewlyCreatedDBObject(spotHeight, true);
                                                    insertedBlockId = spotHeight.ObjectId;
                                                    foreach (ObjectId attrID in blockTableRecord)
                                                    {
                                                        DBObject            atttObj = attrID.GetObject(OpenMode.ForRead);
                                                        AttributeDefinition attrib  = atttObj as AttributeDefinition;
                                                        if ((attrib != null) && (!attrib.Constant))
                                                        {
                                                            using (AttributeReference attributeRef = new AttributeReference())
                                                            {
                                                                attributeRef.SetAttributeFromBlock(attrib, spotHeight.BlockTransform);
                                                                attributeRef.TextString = Decimal.Round(Convert.ToDecimal(spotHeight.Position.Z), 2, MidpointRounding.AwayFromZero).ToString();

                                                                spotHeight.AttributeCollection.AppendAttribute(attributeRef);
                                                                tr.AddNewlyCreatedDBObject(attributeRef, true);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (blockTable.Has(blockName))
                                {
                                    BlockTableRecord blockTableRecord = blockTable[blockName].GetObject(OpenMode.ForRead) as BlockTableRecord;
                                    if (blockTable != null)
                                    {
                                        using (BlockReference spotHeight = new BlockReference(vertex.Position, blockTableRecord.ObjectId))
                                        {
                                            blockCount++;
                                            using (DocumentLock doclock = doc.LockDocument())
                                            {
                                                spotHeight.ScaleFactors = new Autodesk.AutoCAD.Geometry.Scale3d(blockScale, blockScale, blockScale);
                                                BlockTableRecord blocktableRec = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                                blocktableRec.AppendEntity(spotHeight);
                                                tr.AddNewlyCreatedDBObject(spotHeight, true);
                                                insertedBlockId = spotHeight.ObjectId;
                                                foreach (ObjectId attrID in blockTableRecord)
                                                {
                                                    DBObject            atttObj = attrID.GetObject(OpenMode.ForRead);
                                                    AttributeDefinition attrib  = atttObj as AttributeDefinition;
                                                    if ((attrib != null) && (!attrib.Constant))
                                                    {
                                                        using (AttributeReference attributeRef = new AttributeReference())
                                                        {
                                                            attributeRef.SetAttributeFromBlock(attrib, spotHeight.BlockTransform);
                                                            attributeRef.TextString = Decimal.Round(Convert.ToDecimal(spotHeight.Position.Z), 2, MidpointRounding.AwayFromZero).ToString();

                                                            spotHeight.AttributeCollection.AppendAttribute(attributeRef);
                                                            tr.AddNewlyCreatedDBObject(attributeRef, true);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        tr.Commit();
                    }
                    ed.Regen();
                    this.Close();
                    ed.WriteMessage("Successfully added {0} instances of block {1}", blockCount, blockName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Creates a pendant.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <param name="name">The name.</param>
        /// <param name="level">The level.</param>
        /// <param name="durability">The durability.</param>
        /// <param name="excellentOptionDamageType">Type of the excellent option damage.</param>
        /// <param name="optionTargetAttribute">The option target attribute.</param>
        /// <param name="resistanceAttribute">The resistance attribute.</param>
        /// <remarks>
        /// Pendants always have offensive excellent options. If it's wizardry or physical depends on the specific item. I didn't find a pattern yet.
        /// </remarks>
        private void CreatePendant(byte number, string name, byte level, byte durability, DamageType excellentOptionDamageType, AttributeDefinition optionTargetAttribute, AttributeDefinition resistanceAttribute)
        {
            var excellentOption = excellentOptionDamageType == DamageType.Physical
                ? this.GameConfiguration.ExcellentPhysicalAttackOptions()
                : this.GameConfiguration.ExcellentWizardryAttackOptions();

            this.CreateJewelery(number, 9, true, name, level, durability, excellentOption, optionTargetAttribute, resistanceAttribute);
        }
Exemplo n.º 47
0
        /// <summary>
        /// 用于在AutoCAD图形中插入带属性的块参照
        /// </summary>
        /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param>
        /// <param name="layer">块参照要加入的图层名</param>
        /// <param name="blockName">块参照所属的块名</param>
        /// <param name="position">块参照的插入点</param>
        /// <param name="scale">块参照的缩放比例</param>
        /// <param name="rotateAngle">块参照的旋转角度</param>
        /// <param name="attNameValues">属性的名称和取值</param>
        /// <returns></returns>
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle, Dictionary <string, string> attNameValues)
        {
            //获取数据库对象
            Database db = spaceId.Database;
            //以读的方式打开块表
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            //如果没有blockName表示的块,则程序返回
            if (!bt.Has(blockName))
            {
                return(ObjectId.Null);
            }
            //以写的方式打开空间(模型空间或图纸空间)
            BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite);
            //获取块表记录的Id
            ObjectId btrId = bt[blockName];
            //打开块表记录
            BlockTableRecord btr = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead);
            //创建一个块参照并设置插入点
            BlockReference br = new BlockReference(position, bt[blockName])
            {
                //设置块参照的缩放比例
                ScaleFactors = scale,
                //设置块参照的图层
                Layer = layer,
                //设置块参照的旋转角度
                Rotation = rotateAngle
            };

            //将块参照添加到模型空间
            space.AppendEntity(br);

            //判断块表记录是否包含属性定义
            if (btr.HasAttributeDefinitions)
            {
                //遍历属性定义
                foreach (ObjectId id in btr)
                {
                    //检查是否是属性定义
                    AttributeDefinition attDef = id.GetObject(OpenMode.ForRead) as AttributeDefinition;
                    if (attDef != null)
                    {
                        //创建一个新的属性对象
                        AttributeReference attribute = new AttributeReference();
                        //从属性定义获得属性对象的对象特征
                        attribute.SetAttributeFromBlock(attDef, br.BlockTransform);
                        //设置属性对象的其它特征
                        attribute.Position = attDef.Position.TransformBy(br.BlockTransform);
                        attribute.Rotation = attDef.Rotation;
                        attribute.AdjustAlignment(db);
                        //判断是否包含指定的属性名称
                        if (attNameValues.ContainsKey(attDef.Tag.ToUpper()))
                        {
                            //设置属性值
                            attribute.TextString = attNameValues[attDef.Tag.ToUpper()].ToString();
                        }
                        //向块参照添加属性对象
                        br.AttributeCollection.AppendAttribute(attribute);
                        db.TransactionManager.AddNewlyCreatedDBObject(attribute, true);
                    }
                }
            }
            db.TransactionManager.AddNewlyCreatedDBObject(br, true);
            //返回添加的块参照的Id
            return(br.ObjectId);
        }
Exemplo n.º 48
0
        public void ExtractAttributesStart()
        {
            #region Init local vars
            List <Block> OriginalBlockDefs         = new List <Block>();
            List <Block> OriginalBlockRefs         = new List <Block>();
            SortedList <string, double> AttsTotals = new SortedList <string, double>();

            ObjectIdCollection OrigBlockRefsIds = new ObjectIdCollection();
            ObjectIdCollection OrigBlockDefsIds = new ObjectIdCollection();

            Document Doc = Application.DocumentManager.MdiActiveDocument;
            Database Db  = Doc.Database;
            Editor   Ed  = Doc.Editor;

            char[] badChars = { '\'', ' ', '-', '`', '~', '"', '_' };

            string dateFormat = "yyyy.MM.dd_HH.mm.ss";

            string[] stringSeparators = new string[] { "\\" };
            string[] fileNameExploded = Db.Filename.Split(stringSeparators, StringSplitOptions.None);

            string outputFileName = fileNameExploded[fileNameExploded.Length - 2] + "." + DateTime.Now.ToString(dateFormat) + ".xls";
            string outputDir      = Db.Filename.Remove(Db.Filename.LastIndexOf("\\") + 1);

            ExcelDocument document = new ExcelDocument();
            document.UserName = Environment.UserName;
            document.CodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
            document.ColumnWidth(0, 120);
            document.ColumnWidth(1, 80);
            int XLSrows = 0;
            int XLScols = 0;

            document.WriteCell(XLSrows, 4, fileNameExploded[fileNameExploded.Length - 2]);
            XLSrows += 3;
            #endregion

            #region Prompt user for BlockRefs and dwg file/dir opts

            PromptEntityOptions PromptForBlocksOpts = new PromptEntityOptions("\nSelect single block");
            PromptForBlocksOpts.SetRejectMessage("\nYou can select blocks only.");
            PromptForBlocksOpts.AddAllowedClass(typeof(BlockReference), true);
            PromptForBlocksOpts.AllowNone = true;
            PromptEntityResult PromptForBlocksRes = Ed.GetEntity(PromptForBlocksOpts);
            if (PromptForBlocksRes.Status == PromptStatus.Cancel)
            {
                return;
            }

            // Prompt the user for blocks
            while (PromptForBlocksRes.Status == PromptStatus.OK)
            {
                using (Transaction Tr = Db.TransactionManager.StartTransaction())
                {
                    BlockReference Bref = (BlockReference)Tr.GetObject(PromptForBlocksRes.ObjectId, OpenMode.ForRead);
                    Bref.Highlight();         // highlight the selected BlockReference
                    OrigBlockRefsIds.Add(PromptForBlocksRes.ObjectId);

                    // extract the BlockTableRecord from the BlockReference
                    BlockTableRecord Btr = (BlockTableRecord)Tr.GetObject(Bref.BlockTableRecord, OpenMode.ForRead);

                    bool BlockIsAlreadyIn = false;
                    foreach (Block BlockDef in OriginalBlockDefs)
                    {
                        if (BlockDef.Name == Btr.Name)
                        {
                            BlockIsAlreadyIn = true;
                        }
                    }

                    if (!BlockIsAlreadyIn)
                    {
                        StringCollection AttributeTags = new StringCollection();
                        StringBuilder    Atts          = new StringBuilder();

                        foreach (ObjectId ObjId in Btr)
                        {
                            AttributeDefinition attDef = ObjId.GetObject(OpenMode.ForRead) as AttributeDefinition;
                            if (attDef != null)
                            {
                                Atts.Append(attDef.Tag + ";");
                                AttributeTags.Add(attDef.Tag);
                            }
                        }

                        if (AttributeTags.Count > 0)
                        {
                            OriginalBlockDefs.Add(new Block(Btr.Name));
                            OriginalBlockDefs[OriginalBlockDefs.Count - 1].AttributeTags = AttributeTags;

                            XLScols = 1;
                            foreach (string AttTag in AttributeTags)
                            {
                                document.WriteCell(XLSrows, XLScols, AttTag);
                                XLScols++;
                            }
                            XLSrows++;
                        }
                        else   // If a Block Def does not contain AttributeDefs - it is excluded
                        {
                            //ProcLogger.WriteToLog( "Block Definition ;" + Btr.Name + " was excluded becase it has no attributes" );
                        }
                    }
                    else
                    {
                        //ProcLogger.WriteToLog( "Block Definition not imported : ; already in." );
                    }
                    Tr.Commit();
                }

                #region If the user presses cancel in the middle
                //unhighlight all Block References and flush the collections

                PromptForBlocksRes = Ed.GetEntity(PromptForBlocksOpts);
                if (PromptForBlocksRes.Status == PromptStatus.Cancel)
                {
                    using (Transaction Tr = Db.TransactionManager.StartTransaction())
                    {
                        foreach (ObjectId BlockRefId in OrigBlockRefsIds)
                        {
                            BlockReference Bref = (BlockReference)Tr.GetObject(BlockRefId, OpenMode.ForWrite);
                            Bref.Unhighlight();
                            Bref.DowngradeOpen();
                        }

                        OriginalBlockDefs.Clear();
                        OriginalBlockRefs.Clear();

                        Tr.Commit();
                    }
                    return;
                }
                #endregion
            }

            #region Unhighlight all entities and get their BlockTableRecords ObjectIds
            using (Transaction Tr = Db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId BlockRefId in OrigBlockRefsIds)
                {
                    BlockReference Bref = (BlockReference)Tr.GetObject(BlockRefId, OpenMode.ForRead);
                    Bref.Unhighlight();
                }
                Tr.Commit();
            }
            #endregion

            #region prompt for file or dir option
            PromptKeywordOptions KeywordsOpts = new PromptKeywordOptions("Scan current DWG or all files in DWGs dir?");
            KeywordsOpts.AllowArbitraryInput = false;
            KeywordsOpts.AllowNone           = false;
            KeywordsOpts.Keywords.Add("File");
            KeywordsOpts.Keywords.Add("Dir");
            PromptResult FileOrDirRes = Ed.GetKeywords(KeywordsOpts);
            // If the user pressed cancel - return with no error
            if (FileOrDirRes.Status != PromptStatus.OK)
            {
                return;
            }

            List <string> Files = new List <string>();
            string[]      tempFiles;
            if (FileOrDirRes.StringResult == "Dir")
            {
                string currFile = Db.Filename;
                string currDir  = currFile.Remove(currFile.LastIndexOf("\\") + 1);
                tempFiles = Directory.GetFiles(currDir, "*.dwg", SearchOption.AllDirectories);
                foreach (string tempFile in tempFiles)
                {
                    Files.Add(tempFile);
                }
            }
            else
            {
                Files.Add(Db.Filename);
            }

            // return;
            #endregion

            #endregion

            #region Traverse Dwgs and extract raw data
            Database UnopenedDb;

            Files.Sort();
            // Open every file
            foreach (string file in Files)
            {
                document.WriteCell(XLSrows, 0, file.Remove(0, file.LastIndexOf("\\") + 1));

                if (!file.EndsWith(".dwg", StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                // Open the Db from the file
                using (UnopenedDb = new Database(false, false))
                {
                    if (Db.Filename != file)
                    {
                        UnopenedDb.ReadDwgFile(file, FileShare.Read, true, "");
                    }
                    else
                    {
                        UnopenedDb = Db;
                    }

                    List <string>           AppendedTags    = new List <string>();
                    List <StringCollection> AttributeValues = new List <StringCollection>();
                    // open transaction to the db
                    using (Transaction Tr = UnopenedDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            // Get the BlockTable
                            BlockTable Bt = (BlockTable)Tr.GetObject(UnopenedDb.BlockTableId, OpenMode.ForRead);

                            // Traverse all the layouts for Block References
                            foreach (ObjectId ObjId in Bt)
                            {
                                BlockTableRecord LayoutBtr = (BlockTableRecord)Tr.GetObject(ObjId, OpenMode.ForRead);
                                if (LayoutBtr.IsLayout)
                                {
                                    Layout currLayout = (Layout)Tr.GetObject(LayoutBtr.LayoutId, OpenMode.ForRead);
                                    if (!currLayout.LayoutName.Contains("Model"))
                                    {
                                        document.WriteCell(XLSrows++, 0, currLayout.LayoutName);
                                    }

                                    foreach (ObjectId LayoutObjId in LayoutBtr)
                                    {
                                        BlockReference Bref = Tr.GetObject(LayoutObjId, OpenMode.ForRead) as BlockReference;   // Dont tuch this!
                                        if (Bref != null)
                                        {
                                            StringCollection AttRefValuesForXLS = new StringCollection();
                                            foreach (Block BDef in OriginalBlockDefs)
                                            {
                                                if (Bref.Name == BDef.Name)
                                                {
                                                    for (int i = 0; i < Bref.AttributeCollection.Count; i++)
                                                    {
                                                        AttributeReference AttRef = (AttributeReference)Tr.GetObject(Bref.AttributeCollection[i], OpenMode.ForRead);

                                                        AttRefValuesForXLS.Add(AttRef.TextString.Trim(badChars).Trim());
                                                        continue;
                                                    }
                                                    AttributeValues.Add(AttRefValuesForXLS);
                                                }
                                            }
                                        }
                                    }

                                    #region // bubble sort the attributes by PartNr

                                    string tempAA     = "";
                                    string tempBB     = "";
                                    int    tempA      = 0;
                                    int    tempB      = 0;
                                    bool   parseAIsOk = false;
                                    bool   parseBIsOk = false;
                                    Match  MatchA;
                                    Match  MatchB;
                                    //string AlphaPattern = @"[a-z]|[A-Z]";
                                    string NumericPattern = @"[0-9]+";


                                    try
                                    {
                                        if (AttributeValues.Count > 1)
                                        {
                                            for (int j = 0; j < AttributeValues.Count; j++)
                                            {
                                                for (int i = 1; i < AttributeValues.Count; i++)
                                                {
                                                    tempBB = AttributeValues[i][0] = AttributeValues[i][0];
                                                    tempAA = AttributeValues[i - 1][0] = AttributeValues[i - 1][0];

                                                    MatchA = Regex.Match(tempAA, NumericPattern);
                                                    MatchB = Regex.Match(tempBB, NumericPattern);

                                                    parseAIsOk = Int32.TryParse(MatchA.ToString(), out tempA);
                                                    parseBIsOk = Int32.TryParse(MatchB.ToString(), out tempB);

                                                    if (parseAIsOk && parseBIsOk)
                                                    {
                                                        if (tempA > tempB)
                                                        {
                                                            StringCollection temp = AttributeValues[i];
                                                            AttributeValues[i]     = AttributeValues[i - 1];
                                                            AttributeValues[i - 1] = temp;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (System.Exception Ex)
                                    {
                                        Ed.WriteMessage(Ex.Message + Ex.Source + Ex.StackTrace);
                                    }

                                    #endregion

                                    #region Parse and write the attribute collection to XLS file


                                    try
                                    {
                                        foreach (StringCollection BlockRefAttValues in AttributeValues)
                                        {
                                            if (!AttsTotals.Keys.Contains(BlockRefAttValues[4]))
                                            {
                                                double value;
                                                if (Double.TryParse(BlockRefAttValues[2], out value))
                                                {
                                                    AttsTotals.Add(BlockRefAttValues[4], value);
                                                }
                                                else
                                                {
                                                    AttsTotals.Add(BlockRefAttValues[4], 0);
                                                }
                                            }
                                            else
                                            {
                                                double value;
                                                double z;
                                                if (Double.TryParse(BlockRefAttValues[2], out value))
                                                {
                                                    z = value;
                                                }
                                                else
                                                {
                                                    z = 0;
                                                }
                                                double x;

                                                if (Double.TryParse(BlockRefAttValues[4], out value))
                                                {
                                                    x = value;
                                                }
                                                else
                                                {
                                                    x = 0;
                                                }

                                                //double total = AttsTotals[BlockRefAttValues[4]];
                                                //AttsTotals[BlockRefAttValues[4]] = total + z + x;
                                                AttsTotals[BlockRefAttValues[4]] += z + x;
                                            }

                                            XLScols = 1;
                                            foreach (string AttVal in BlockRefAttValues)
                                            {
                                                string tmp     = AttVal;
                                                double tempInt = 0;
                                                if (Double.TryParse(tmp, out tempInt))
                                                {
                                                    document.WriteCell(XLSrows, XLScols, tempInt);
                                                }
                                                else
                                                {
                                                    document.WriteCell(XLSrows, XLScols, tmp);
                                                }
                                                XLScols++;
                                            }
                                            XLSrows++;
                                        }
                                    }
                                    catch (System.Exception Ex)
                                    {
                                        MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace);
                                    }
                                    #endregion
                                    AttributeValues.Clear();
                                }
                            }
                        }
                        catch (System.Exception Ex)
                        {
                            Ed.WriteMessage(Ex.Message + Ex.Source + Ex.StackTrace);
                        }
                    }
                }
                XLSrows += 3;
            }// foreach ( file in files )

            try
            {
                document.WriteCell(XLSrows, 5, "Parts");
                document.WriteCell(XLSrows, 3, "Totals");
                XLSrows++;

                foreach (KeyValuePair <string, double> Total in AttsTotals)
                {
                    //document.WriteCell(XLSrows, 5, Total.Key.ToString());
                    document.WriteCell(XLSrows, 5, Total.Key);
                    double value;
                    if (Double.TryParse(Total.Value.ToString(), out value))
                    {
                        document.WriteCell(XLSrows, 3, value);
                    }
                    else
                    {
                        document.WriteCell(XLSrows, 3, Total.Value.ToString());
                    }

                    document.WriteCell(XLSrows, 4, "Stk");
                    XLSrows++;
                }
            }
            catch (System.Exception Ex)
            {
                MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace);
            }

            FileStream stream = new FileStream(outputDir + outputFileName, FileMode.Create);
            document.Save(stream);
            stream.Close();
            #endregion
        }
        public void Initialize()
        {
            #region Vars

            IReadonlyEntityRepositoryGroup<IContentStore> readonlyContentStoreRepository;
            IReadonlySchemaRepositoryGroup<IContentStore> readonlyContentStoreSchemaRepository;
            IEntityRepositoryGroup<IContentStore> contentStoreRepository;
            ISchemaRepositoryGroup<IContentStore> contentStoreSchemaRepository;

            IReadonlyEntityRepositoryGroup<IFileStore> readonlyFileStoreRepository;
            IReadonlySchemaRepositoryGroup<IFileStore> readonlyFileStoreSchemaRepository;
            IEntityRepositoryGroup<IFileStore> fileStoreRepository;
            ISchemaRepositoryGroup<IFileStore> fileStoreSchemaRepository;

            #endregion

            var hive = MockHiveManager.GetManager()
                .MockContentStore(out readonlyContentStoreRepository, out readonlyContentStoreSchemaRepository, out contentStoreRepository, out contentStoreSchemaRepository)
                .MockFileStore(out readonlyFileStoreRepository, out readonlyFileStoreSchemaRepository, out fileStoreRepository, out fileStoreSchemaRepository);

            //Setup file store
            var fileId = new HiveId("storage", "file-uploader", new HiveIdValue("test.jpg"));
            var file = new File
            {
                Id = fileId,
                Name = "test.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test")
            };

            readonlyFileStoreRepository
                .Get<File>(true, Arg.Any<HiveId[]>())
                .Returns(new[] { file });

            var thumbnailId = new HiveId("storage", "file-uploader", new HiveIdValue("test_100.jpg"));
            var thumbnail = new File
            {
                Id = thumbnailId,
                Name = "test_100.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test_100")
            };

            var relation = Substitute.For<IReadonlyRelation<IRelatableEntity, IRelatableEntity>>();
            relation.MetaData.Returns(new RelationMetaDataCollection(new[] { new RelationMetaDatum("size", "100") }));
            relation.Source.Returns(file);
            relation.SourceId.Returns(fileId);
            relation.Destination.Returns(thumbnail);
            relation.DestinationId.Returns(thumbnailId);

            readonlyFileStoreRepository.GetLazyChildRelations(fileId, FixedRelationTypes.ThumbnailRelationType)
                .Returns(new[]{ relation });

            //Setup media store
            var mediaPickerAttributeDefType = new AttributeType { RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId };
            var mediaPickerAttributeDef = new AttributeDefinition("umbracoFile", "") { Id = FixedHiveIds.FileUploadAttributeType, AttributeType = mediaPickerAttributeDefType };
            var mediaPickerProperty = new TypedAttribute(mediaPickerAttributeDef, fileId.ToString());

            var mediaId = new HiveId("0A647849-BF5C-413B-9420-7AB4C9521505");
            var mediaEntity = new TypedEntity { Id = mediaId };
            //mediaEntity.SetupFromSchema(FixedSchemas.MediaImageSchema);
            mediaEntity.Attributes.Add(mediaPickerProperty);
            mediaEntity.Attributes["umbracoFile"].Values["MediaId"] = "0A647849-BF5C-413B-9420-7AB4C9521505";

            //readonlyContentStoreRepository
            //    .Get<TypedEntity>(true, Arg.Any<HiveId[]>())
            //    .Returns(new[] { mediaEntity });

            //readonlyContentStoreRepository
            //    .SingleOrDefault<TypedEntity>(Arg.Any<Expression<Func<TypedEntity, bool>>>())
            //    .Returns(mediaEntity);

            var mediaEntityList = new List<TypedEntity> { mediaEntity };
            readonlyContentStoreRepository
                .Query()
                .Returns(mediaEntityList.AsQueryable());

            // Setup application
            var appContext = Substitute.For<IUmbracoApplicationContext>();
            appContext.Hive.Returns(hive);

            // Setup back office request
            _backOfficeRequestContext = Substitute.For<IBackOfficeRequestContext>();
            _backOfficeRequestContext.Application.Returns(appContext);

            var member = new Member {Id = new HiveId("0285372B-AB14-45B6-943A-8709476AB655"), Username = "******"};

            // Setup fake HttpContext (Just needed to fake current member)
            var identity = new GenericIdentity(member.Username);
            var user = new GenericPrincipal(identity, new string[0]);
            var wp = new SimpleWorkerRequest("/virtual", "c:\\inetpub\\wwwroot\\physical\\", "page.aspx", "query", new StringWriter());
            HttpContext.Current = new HttpContext(wp) {User = user};

            appContext.Security.Members.GetByUsername(member.Username).Returns(member);

            appContext.Security.PublicAccess.GetPublicAccessStatus(member.Id, mediaEntity.Id)
                .Returns(new PublicAccessStatusResult(mediaEntity.Id, true));
        }