Exemplo n.º 1
0
        private void clearAppearance() //清除所有表达
        {
            Search search = new Search();

            search.Selection.SelectAll();

            //oDoc.Models.ResetAllPermanentMaterials();

            VariantData oData = VariantData.FromDisplayString("门");

            SearchCondition oSearchCondition = SearchCondition.HasPropertyByDisplayName("项目", "类型");

            oSearchCondition = oSearchCondition.EqualValue(oData);
            search.SearchConditions.Add(oSearchCondition);
            ModelItemCollection items = search.FindAll(oDoc, false);

            oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Blue);
            oDoc.Models.OverridePermanentTransparency(items, 0.5);

            Search search1 = new Search();

            search1.Selection.SelectAll();
            oData = VariantData.FromDisplayString("房间");

            oSearchCondition = SearchCondition.HasPropertyByDisplayName("项目", "类型");
            oSearchCondition = oSearchCondition.EqualValue(oData);
            search1.SearchConditions.Add(oSearchCondition);
            items = search1.FindAll(oDoc, false);
            oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.White);
            oDoc.Models.OverridePermanentTransparency(items, 1);
            //oDoc.CurrentSelection.CopyFrom(items);
        }
Exemplo n.º 2
0
        private object createSearchSet(object name, object category, object property, object value)
        {
            //https://adndevblog.typepad.com/aec/2012/08/add-search-selectionset-in-net.html

            Document doc = Autodesk.Navisworks.Api.Application.ActiveDocument;

            //Create a new search object
            Search          s  = new Search();
            SearchCondition sc = SearchCondition.HasPropertyByDisplayName(category.ToString(), property.ToString());

            s.SearchConditions.Add(sc.EqualValue(VariantData.FromDisplayString(value.ToString())));


            //Set the selection which we wish to search
            s.Selection.SelectAll();
            s.Locations = SearchLocations.DescendantsAndSelf;

            //halt searching below ModelItems which match this
            s.PruneBelowMatch = true;

            //get the resulting collection by applying this search
            ModelItemCollection searchResults = s.FindAll(Autodesk.Navisworks.Api.Application.ActiveDocument, false);
            SelectionSet        selectionSet  = new SelectionSet();

            selectionSet.DisplayName = name.ToString();
            selectionSet.CopyFrom(s);
            Autodesk.Navisworks.Api.Application.ActiveDocument.SelectionSets.InsertCopy(0, selectionSet);
            var ss = Autodesk.Navisworks.Api.Application.ActiveDocument.SelectionSets.ToSavedItemCollection();


            return(ss);
        }
Exemplo n.º 3
0
        private object createSearch(object category, object property, object value, object Negate)
        {
            //https://adndevblog.typepad.com/aec/2012/08/add-search-selectionset-in-net.html

            Document doc = Autodesk.Navisworks.Api.Application.ActiveDocument;

            //Create a new search object
            Search          s      = new Search();
            SearchCondition sc     = SearchCondition.HasPropertyByDisplayName(category.ToString(), property.ToString());
            bool            negate = Negate != null?bool.Parse(Negate.ToString()) : false;

            if (negate)
            {
                sc = sc.Negate();
            }


            s.SearchConditions.Add(sc.EqualValue(VariantData.FromDisplayString(value.ToString())));


            //Set the selection which we wish to search
            s.Selection.SelectAll();
            s.Locations = SearchLocations.DescendantsAndSelf;

            //halt searching below ModelItems which match this
            s.PruneBelowMatch = true;

            return(s);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Aula/Lesson 9
        /// </summary>
        private void btCreateSearch_MouseUp(object sender, MouseEventArgs e)
        {
            var ac = NavisworksApp.ActiveDocument;
            var cs = ac.CurrentSelection;
            var ss = ac.SelectionSets;

            var fn = "Saved Search";
            var sn = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss.fff");

            try
            {
                var s = new Search();
                s.Selection.SelectAll();
                s.Locations = SearchLocations.DescendantsAndSelf;

                var sc = SearchCondition.HasPropertyByDisplayName(tbCatName.Text, tbPropName.Text);
                s.SearchConditions.Add(sc.EqualValue(VariantData.FromDisplayString(tbValueName.Text)));

                var sSet = new SelectionSet(s)
                {
                    DisplayName = sn
                };
                ss.AddCopy(sSet);

                var fi = ss.Value.IndexOfDisplayName(fn);

                if (fi == -1)
                {
                    var sf = new FolderItem()
                    {
                        DisplayName = fn
                    };
                    ss.AddCopy(sf);
                }

                fi = ss.Value.IndexOfDisplayName(fn);
                var fo = ss.Value[fi] as FolderItem;

                var si = ss.Value.IndexOfDisplayName(sn);
                var se = ss.Value[si] as SavedItem;

                ss.Move(se.Parent, si, fo, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Aula 8
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCreateSearch_MouseUp(object sender, MouseEventArgs e)
        {
            var ac = App.ActiveDocument;
            var cs = ac.CurrentSelection;
            var se = ac.SelectionSets;

            var fn = "Search Sets";             //Nome da pasta de set selection
            var sn = Guid.NewGuid().ToString(); //Nome do set selection

            try
            {
                var fi = se.Value.IndexOfDisplayName(fn);
                if (fi == -1)
                {
                    //Cria pasta de sets de seleçao dos itens
                    se.AddCopy(new FolderItem()
                    {
                        DisplayName = fn
                    });
                }

                //Cria seleção dos itens selecionados
                var s = new Search();
                s.Locations = SearchLocations.DescendantsAndSelf;
                s.Selection.SelectAll();

                var sc = SearchCondition.HasPropertyByDisplayName(this.tbCategoryName.Text, this.tbPropertyName.Text);
                s.SearchConditions.Add(sc.EqualValue(VariantData.FromDisplayString(this.tbPropertyValue.Text)));

                var set = new SelectionSet(s)
                {
                    DisplayName = sn
                };

                //Insere set de seleção
                se.AddCopy(set);

                var fo = se.Value[se.Value.IndexOfDisplayName(fn)] as FolderItem;
                var ns = se.Value[se.Value.IndexOfDisplayName(fn)] as SavedItem;

                //Move o set para a pasta no indice novo
                se.Move(ns.Parent, se.Value.IndexOfDisplayName(fn), fo, 0);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 6
0
        public IResult GetEntities(string type, string dataPropertyNames)
        {
            var returnresult = new Result_Model();

            Search s = new Search();

            s.SearchConditions.Add(SearchCondition.HasCategoryByName(PropertyCategoryNames.Geometry));
            s.SearchConditions.Add(SearchCondition.HasPropertyByName(PropertyCategoryNames.Item, DataPropertyNames.ItemHidden).EqualValue(VariantData.FromBoolean(false)));
            s.SearchConditions.Add(SearchCondition.HasPropertyByName(PropertyCategoryNames.Item, dataPropertyNames).EqualValue(VariantData.FromDisplayString(type)));
            s.Selection.SelectAll();
            s.Locations = SearchLocations.DescendantsAndSelf;

            var result = s.FindAll(Application.ActiveDocument, false);

            result.ToList().ForEach(model => returnresult.Payload.Add(model));

            return(returnresult);
        }
Exemplo n.º 7
0
        private void btnShow_Click(object sender, EventArgs e)
        {
            VariantData         oData;
            SearchCondition     oSearchCondition;
            ModelItemCollection items;


            string pattern  = @"\{[^\{^\}]*\}";
            string pattern1 = @"\[[^\[^\]]*\]";
            Regex  regex    = new Regex(pattern, RegexOptions.IgnoreCase);
            Regex  regex1   = new Regex(pattern1, RegexOptions.IgnoreCase);


            //清除表达
            clearAppearance();

            int    i;
            string sT = "";

            for (i = 0; i < dataGridViewDFS.SelectedRows.Count; i++)
            {
                sT = dataGridViewDFS.SelectedRows[i].Cells[5].Value.ToString();
                //MessageBox.Show(sT);

                //分离房间

                MatchCollection matches = regex.Matches(sT);
                //StringBuilder sb = new StringBuilder();//存放匹配结果
                foreach (Match match in matches)
                {
                    //Thread.Sleep(1000);
                    string value = match.Value.Trim('{', '}');


                    string[] sArray = value.Split(':');
                    if (sArray.Length != 2)
                    {
                        continue;
                    }
                    //MessageBox.Show(value + "sArray[0]=" + sArray[0] + "sArray[1]="+sArray[1]);
                    //找到房间
                    Search search = new Search();
                    search.Selection.SelectAll();

                    oData = VariantData.FromDisplayString(sArray[0]);

                    oSearchCondition = SearchCondition.HasPropertyByDisplayName("元素 ID", "值");
                    oSearchCondition = oSearchCondition.EqualValue(oData);
                    search.SearchConditions.Add(oSearchCondition);
                    items = search.FindAll(oDoc, false);


                    switch (sArray[1])
                    {
                    case "0":
                        oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Red);
                        oDoc.Models.OverridePermanentTransparency(items, 0.5);
                        break;

                    case "1":
                        oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Blue);
                        oDoc.Models.OverridePermanentTransparency(items, 0.6);
                        break;

                    case "2":
                        oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Green);
                        oDoc.Models.OverridePermanentTransparency(items, 0.9);
                        break;
                    }
                }

                //分离门
                matches = regex1.Matches(sT);
                //StringBuilder sb1 = new StringBuilder();//存放匹配结果
                foreach (Match match in matches)
                {
                    string value = match.Value.Trim('[', ']');

                    string[] sArray1 = value.Split(',');


                    foreach (string s in sArray1)
                    {
                        //MessageBox.Show(value + "sArray[0]=" + sArray[0] + "sArray[1]="+sArray[1]);
                        //找到
                        Search search = new Search();
                        search.Selection.SelectAll();

                        //MessageBox.Show(value);

                        oData = VariantData.FromDisplayString(s);

                        oSearchCondition = SearchCondition.HasPropertyByDisplayName("元素 ID", "值");
                        oSearchCondition = oSearchCondition.EqualValue(oData);
                        search.SearchConditions.Add(oSearchCondition);
                        items = search.FindAll(oDoc, false);
                        oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Red);
                        oDoc.Models.OverridePermanentTransparency(items, 0);
                    }
                }
            }
        }
Exemplo n.º 8
0
        private void dataGridViewPaths_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridViewPaths.RowCount < 1)
            {
                return;
            }

            if (dataGridViewPaths.SelectedRows.Count < 1)
            {
                return;
            }



            VariantData         oData;
            SearchCondition     oSearchCondition;
            ModelItemCollection items;



            //清除表达
            //clearAppearance();

            int i;

            oDoc.CurrentSelection.Clear();

            for (i = 0; i < dataGridViewPaths.SelectedRows.Count; i++)
            {
                if (dataGridViewPaths.SelectedRows[i].Cells[0].Value.ToString() == "空间")
                {
                    string[] sArray = dataGridViewPaths.SelectedRows[i].Cells[2].Value.ToString().Split(':');
                    if (sArray.Length != 2)
                    {
                        continue;
                    }
                    //MessageBox.Show(value + "sArray[0]=" + sArray[0] + "sArray[1]="+sArray[1]);
                    //找到房间
                    Search search = new Search();
                    search.Selection.SelectAll();

                    oData = VariantData.FromDisplayString(sArray[0]);

                    oSearchCondition = SearchCondition.HasPropertyByDisplayName("元素 ID", "值");
                    oSearchCondition = oSearchCondition.EqualValue(oData);
                    search.SearchConditions.Add(oSearchCondition);
                    items = search.FindAll(oDoc, false);


                    oDoc.CurrentSelection.CopyFrom(items);

                    /*
                     *
                     * switch (sArray[1])
                     * {
                     *  case "0":
                     *      oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Red);
                     *      oDoc.Models.OverridePermanentTransparency(items, 0.5);
                     *      break;
                     *  case "1":
                     *      oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Blue);
                     *      oDoc.Models.OverridePermanentTransparency(items, 0.6);
                     *      break;
                     *  case "2":
                     *      oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Green);
                     *      oDoc.Models.OverridePermanentTransparency(items, 0.9);
                     *      break;
                     * }
                     * */
                }
                else
                {
                    string[] sArray1 = dataGridViewPaths.SelectedRows[i].Cells[2].Value.ToString().Split(',');


                    foreach (string s in sArray1)
                    {
                        //MessageBox.Show(value + "sArray[0]=" + sArray[0] + "sArray[1]="+sArray[1]);
                        //找到
                        Search search = new Search();
                        search.Selection.SelectAll();

                        //MessageBox.Show(value);

                        oData = VariantData.FromDisplayString(s);

                        oSearchCondition = SearchCondition.HasPropertyByDisplayName("元素 ID", "值");
                        oSearchCondition = oSearchCondition.EqualValue(oData);
                        search.SearchConditions.Add(oSearchCondition);
                        items = search.FindAll(oDoc, false);

                        oDoc.CurrentSelection.CopyFrom(items);

                        /*
                         * oDoc.Models.OverridePermanentColor(items, Autodesk.Navisworks.Api.Color.Red);
                         * oDoc.Models.OverridePermanentTransparency(items, 0);
                         */
                    }
                }
            }

            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                ComApiBridge.State.ZoomInCurViewOnCurSel();
            }

            //ComApiBridge.State.ZoomInCurViewOnCurSel();
        }
Exemplo n.º 9
0
        public override int Execute(params string[] parameters)
        {
            try
            {
                Document doc = Application.ActiveDocument;

                //ModelItemCollection currSelectionColl = doc.CurrentSelection.SelectedItems;

                string initialPath     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string initialFileName = Environment.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string docFileName     = doc.FileName;
                if (!String.IsNullOrEmpty(docFileName))
                {
                    initialPath      = Path.GetDirectoryName(docFileName);
                    initialFileName += "_" + Path.GetFileNameWithoutExtension(docFileName);
                }


                //if (currSelectionColl.Count > 0)
                //{
                //    //Если выбран какой-либо объект в дереве (или несколько), то открывается такое же окно как в команде SetProps
                //    //(но при этом у каждого объекта обязательно должен быть настроенный id)
                //    //Объекты DisplayDataTab, DisplayProperty, DisplayURL должны быть serializable
                //    List<string> ids = new List<string>();
                //    List<ModelItem> itemsToSetProps = new List<ModelItem>();
                //    foreach (ModelItem item in currSelectionColl)
                //    {
                //        DataProperty idProp = item.PropertyCategories
                //                    .FindPropertyByDisplayName(S1NF0_DATA_TAB_DISPLAY_NAME,
                //                    ID_PROP_DISPLAY_NAME);
                //        if (idProp != null)
                //        {
                //            ids.Add(Utils.GetDisplayValue(idProp.Value));
                //            itemsToSetProps.Add(item);
                //        }
                //    }

                //    if (ids.Count == 0)
                //    {
                //        Win.MessageBox.Show("Ни у одного из выбранных элементов нет id");
                //        return 0;
                //    }

                //    //Инициализация окна SetProps
                //    SetPropsWindow setPropsWindow = SetProps.ConfigureAndOppenSetPropsWindow(doc, itemsToSetProps);
                //    setPropsWindow.Loaded += (a, b) =>
                //    {
                //        setPropsWindow.PreserveExistingProperties = true;
                //    };
                //    bool? result = setPropsWindow.ShowDialog();
                //    if (result != null && result.Value)
                //    {
                //        //После подтверждения объекты DisplayDataTab и DisplayURL сохраняются в объект ObjectData
                //        //Объект ObjectsData сразу же сериализуется. Открывается окно сохранения файла
                //        //Имя XML по умолчанию - дата и время до минут + имя пользователя + имя файла
                //        ObjectsData objectsData = new ObjectsData()
                //        {
                //            PreserveExistingProperties = setPropsWindow.PreserveExistingProperties,
                //            OverwriteLinks = setPropsWindow.OverwriteLinks,
                //            OverwriteUserAttr = setPropsWindow.OverwriteUserAttr,
                //            Ids = ids,
                //            DataTabs = setPropsWindow.OverwriteUserAttr ? setPropsWindow.DataTabs : null,
                //            URLs = setPropsWindow.OverwriteLinks ? setPropsWindow.URLs : null

                //        };



                //        WinForms.SaveFileDialog saveFileDialog = new WinForms.SaveFileDialog();
                //        saveFileDialog.InitialDirectory = initialPath;
                //        saveFileDialog.Filter = "xml files (*.xml)|*.xml";
                //        saveFileDialog.FilterIndex = 1;
                //        saveFileDialog.RestoreDirectory = true;
                //        if (!String.IsNullOrWhiteSpace(initialFileName))
                //            saveFileDialog.FileName = initialFileName;
                //        saveFileDialog.Title = "Укажите файл для записи свойств";

                //        if (saveFileDialog.ShowDialog() == WinForms.DialogResult.OK)
                //        {
                //            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ObjectsData));
                //            using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName))
                //            {
                //                xmlSerializer.Serialize(sw, objectsData);
                //            }
                //        }

                //        //выбранные объекты скрываются, чтобы пользователь не выбирал их по второму разу
                //        doc.Models.SetHidden(itemsToSetProps, true);

                //    }
                //}
                //else
                //{
                //get state object of COM API
                ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;

                //предлагается выбрать несколько готовых XML для создания свойств в текущей модели
                WinForms.OpenFileDialog ofd = new WinForms.OpenFileDialog();
                ofd.InitialDirectory = initialPath;
                ofd.Filter           = "xml files (*.xml)|*.xml";
                ofd.FilterIndex      = 1;
                ofd.RestoreDirectory = true;
                ofd.Multiselect      = true;
                ofd.Title            = "Выберите файлы с данными о свойствах ";

                if (ofd.ShowDialog() == WinForms.DialogResult.OK)
                {
                    List <string> filenames = ofd.FileNames.ToList();
                    filenames.Sort();
                    foreach (string filename in filenames)
                    {
                        ObjectsData objectsData = null;
                        try
                        {
                            //Десериализуются объекты ObjectData.
                            using (StreamReader sr = new StreamReader(filename))
                            {
                                string        serializedData = sr.ReadToEnd();
                                XmlSerializer xmlSerializer  = new XmlSerializer(typeof(ObjectsData));
                                StringReader  stringReader   = new StringReader(serializedData);
                                objectsData = (ObjectsData)xmlSerializer.Deserialize(stringReader);
                            }
                        }
                        catch { }

                        if (objectsData != null)
                        {
                            //Для каждого объекта ищется соответствующий объект по Id
                            ModelItemCollection itemsToSetProps = new ModelItemCollection();
                            foreach (string id in objectsData.Ids)
                            {
                                //Search API
                                VariantData idVd = VariantData.FromDisplayString(id);

                                SearchCondition searchForIDCondition
                                    = new SearchCondition(tabCN, idCN, SearchConditionOptions.None,
                                                          SearchConditionComparison.Equal, idVd);
                                Search searchForCertainID = new Search();
                                searchForCertainID.Selection.SelectAll();
                                searchForCertainID.PruneBelowMatch = false;
                                searchForCertainID.SearchConditions.Add(searchForIDCondition);

                                ModelItem itemIdMatch = searchForCertainID.FindFirst(doc, false);
                                if (itemIdMatch != null)
                                {
                                    itemsToSetProps.Add(itemIdMatch);
                                }
                            }

                            bool preserveExistingProperties = objectsData.PreserveExistingProperties;
                            bool overwriteUserAttr          = objectsData.OverwriteUserAttr;
                            bool overwriteLinks             = objectsData.OverwriteLinks;

                            List <DisplayDataTab> displayDataTabs = objectsData.DataTabs;
                            List <DisplayURL>     displayURLs     = objectsData.URLs;

                            //и для этого набора объектов запускается процедура создания свойств как в команде SetProps
                            SetProps.SetPropsMethod(oState, itemsToSetProps, displayDataTabs,
                                                    displayURLs, overwriteUserAttr, overwriteLinks, preserveExistingProperties);
                        }
                    }
                }


                //}
            }
            catch (Exception ex)
            {
                CommonException(ex, "Ошибка при заполнении атрибутов в Navis");
            }



            return(0);
        }
        public IResult GetEntities(dynamic obj)
        {
            var returnresult = new Result_Model();

            if (obj is KeyValuePair <string, string> data)
            {
                Search s = new Search();

                s.SearchConditions.Add(SearchCondition.HasCategoryByName(PropertyCategoryNames.Geometry));
                s.SearchConditions.Add(SearchCondition.HasPropertyByName(PropertyCategoryNames.Item, DataPropertyNames.ItemHidden).EqualValue(VariantData.FromBoolean(false)));
                s.SearchConditions.Add(SearchCondition.HasPropertyByName(PropertyCategoryNames.Item, data.Key).EqualValue(VariantData.FromDisplayString(data.Value)));
                s.Selection.SelectAll();
                s.Locations = SearchLocations.DescendantsAndSelf;

                var result = s.FindAll(Application.ActiveDocument, false);
                result.ToList().ForEach(model => returnresult.Payload.Add(model));
            }
            else
            {
                returnresult.ResultType = Core.Enums.ResultTypes.Failed;
            }

            return(returnresult);
        }
Exemplo n.º 11
0
        private static ModelItem findModelItem(object sel)
        {
            var    guid   = ((ModelItem)sel).InstanceGuid;
            Search search = new Search();

            search.Selection.SelectAll();

            search.SearchConditions.Add(



                SearchCondition.HasPropertyByName("LcOaNode", "LcOaNodeGuid").EqualValue(VariantData.FromDisplayString(guid.ToString())));

            // Execute Search

            ModelItemCollection items = search.FindAll(Autodesk.Navisworks.Api.Application.ActiveDocument, false);

            return(items.FirstOrDefault());
        }