예제 #1
0
        public static ComApi.InwOaProperty CopyProp(ComApi.InwOpState3 oState,
                                                    ComApi.InwOaProperty propToCopy)
        {
            object value = propToCopy.value;

            if (value != null)
            {
                return(Utils.CreateNewUserProp(oState, propToCopy.UserName, value));
            }
            return(null);
        }
예제 #2
0
        /// <summary>
        /// Создать новое свойство
        /// </summary>
        /// <param name="oState"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ComApi.InwOaProperty CreateNewUserProp(ComApi.InwOpState3 oState,
                                                             string name, object value)
        {
            // create new property
            ComApi.InwOaProperty newP = (ComApi.InwOaProperty)oState
                                        .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);

            // set the name, username and value of the new property
            newP.name     = Common.Transliteration.Front(name);
            newP.UserName = name;
            if (value == null || (value is string && String.IsNullOrWhiteSpace(value as string)))
            {
                value = "_";
            }
            newP.value = ObjectToSetAsUserPropertyValue(value);
            return(newP);
        }
        private void addProperty(NVApi.ModelItem PropModelItem, string strPropName, string strPropValue)
        {
            try
            {
                COM.InwOpState10 state;
                state = ComApiBridge.State;
                // get current selection
                NVApi.ModelItemCollection modelItemCollectionIn = new NVApi.ModelItemCollection();
                modelItemCollectionIn.Add(PropModelItem);
                // get the selection in COM
                Autodesk.Navisworks.Api.Interop.ComApi.InwOpSelection comSelectionOut = ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
                // get paths within the selection
                COM.InwSelectionPathsColl oPaths = comSelectionOut.Paths();
                COM.InwOaPath3            oPath  = (COM.InwOaPath3)oPaths.Last();
                // get properties collection of the path
                COM.InwGUIPropertyNode2 propn = (COM.InwGUIPropertyNode2)state.GetGUIPropertyNode(oPath, true);

                // create new property category
                // (new tab in the properties dialog)
                COM.InwOaPropertyVec newPvec = (COM.InwOaPropertyVec)state.ObjectFactory(COM.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
                // create new property
                COM.InwOaProperty newP = (COM.InwOaProperty)state.ObjectFactory(COM.nwEObjectType.eObjectType_nwOaProperty, null, null);
                // set the name, username and value of the new property
                newP.name     = "lc" + strPropName;
                newP.UserName = strPropName;
                newP.value    = strPropValue;
                // add the new property to the new property category
                newPvec.Properties().Add(newP);
                // add the new property category to the path
                propn.SetUserDefined(0, "NV-AddedProety", "lcNVAddedProety", newPvec);
            }
            catch
            {
                throw;
            }
        }
예제 #4
0
        public override int Execute(params string[] parameters)
        {
            DebugMessage DebugP     = new DebugMessage();
            string       EndMessage = "";

            #region "Interop COM Setup"
            /////////////////////////////////////////////////////////////////////////////////////////////////
            // .Net: Setup
            Document openDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;
            Model    model   = openDoc.Models[0];

            // .Net: get current selection from .NET API
            ModelItemCollection ObjectSelectionInNet = openDoc.CurrentSelection.SelectedItems;
            // .Net: get model item
            ModelItem ObjectsModelItem;
            try
            {
                ObjectsModelItem = openDoc.CurrentSelection.SelectedItems[0];
            }
            catch
            {
                MessageBox.Show("No Objects Selected.");
                goto Exit;
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////
            // COM: Declare "InwOpState" (COM API Main Entry) Object
            ComApi.InwOpState InteropState = ComBridge.State; // Analogous To .Net "Document"
                                                              // COM: Convert .Net Selection To COM Selection
            ComApi.InwOpSelection ObjectsSelectionInCOM = ComApiBridge.ToInwOpSelection(ObjectSelectionInNet);
            // COM: Convert .Net Path To Path In COM
            ComApi.InwOaPath ObjectsPathInCOM = ComApiBridge.ToInwOaPath(ObjectsModelItem);

            // convert to model item in .NET
            ModelItem ObjectsItemInNet = ComApiBridge.ToModelItem(ObjectsPathInCOM);
            #endregion

            // zoom in current view to selected objects
            ComApiBridge.State.ZoomInCurViewOnCurSel();

            // ???
            ComApi.InwOpState9 oStateAPI = ComApiBridge.State;
            //convert to COM selection

            ComApi.InwOpSelection CurrentGUISelection = ComApiBridge.ToInwOpSelection(ObjectSelectionInNet);

            // Debug Variables
            uint levelOneIterator = 0, levelTwoIterator = 0;
            // Takeoff Tracking Variables
            uint   existingIDsCount = 0;
            string CurrentTime      = DateTime.Now.ToString("h:mm:ss tt");
            //ComApi.InwSelectionPathsColl ModelObjectsPaths =

            #region "Change Custom Properties"
            //get paths collection within the selection
            ComApi.InwSelectionPathsColl ObjectCurrentSelectPaths = CurrentGUISelection.Paths();
            // Custom Properties Variables
            const string PropertiesNameString  = "Custom_Properties";
            const string NWAttPropIDNameString = "ID";
            uint         PropertyIndex         = 0; // Used To Locate The Node For Updating Properties
            int          IDPropertyIndex       = 0;

            // Find Existing Custom Properties
            //foreach (ComApi.InwOaPath3


            //add custom properties To Selected Objects
            // http://adndevblog.typepad.com/aec/2012/08/addmodifyremove-custom-attribute-using-com-api.html
            foreach (ComApi.InwOaPath3 ObjectPath in ObjectCurrentSelectPaths)
            {
                //// Make Sure All Children Are Iterated Through
                //foreach(ComApi.InwOaPath3 terminalPath in oPath)
                //{ }

                //get property categories
                ComApi.InwGUIPropertyNode2 NWPropertyNode = (ComApi.InwGUIPropertyNode2)oStateAPI.GetGUIPropertyNode(ObjectPath, true);
                //create a new property category
                ComApi.InwOaPropertyVec NewPropertyCategory = (ComApi.InwOaPropertyVec)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
                //create a new property
                ComApi.InwOaProperty NewProperty1 = (ComApi.InwOaProperty)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
                NewProperty1.name     = "Time";
                NewProperty1.UserName = "******";
                NewProperty1.value    = CurrentTime;
                // Add To Category
                NewPropertyCategory.Properties().Add(NewProperty1);

                //create a new property
                ComApi.InwOaProperty NewProperty2 = (ComApi.InwOaProperty)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
                NewProperty2.name     = NWAttPropIDNameString;
                NewProperty2.UserName = NWAttPropIDNameString;
                NewProperty2.value    = "ERROR: Unassigned ID";
                // Add To Category
                //NewPropertyCategory.Properties().Add(NewProperty2);


                //////////////////////////////////////////////////////////////////////////////////////////
                // Find User Defined GUIAttributes
                PropertyIndex = 0; // Reset Property Index (0 Indicates New Property Category)
                uint i = 0, j = 0;
                foreach (ComApi.InwGUIAttribute2 NWAttribute in NWPropertyNode.GUIAttributes())
                {
                    if (NWAttribute.UserDefined == true)
                    {
                        ++i;// Move Index Finder
                        // If Particular Category Name (e.g. "Custom_Properties" Or Whatever PropertiesNameString Is Set To)
                        if (NWAttribute.ClassUserName == PropertiesNameString)
                        {
                            PropertyIndex = i;// Set Index
                            //DebugP.Send("NWAttribute.ClassUserName: "******"Loop Here Found: " + NWProperty.name.ToString());
                                }
                                ++j;
                            }
                        }
                    }
                }

                //////////////////////////////////////////////////////////////////////////////////////
                try// Update Takeoff Time (Don't Change ID) If Property Exists
                {
                    //DebugP.Send("Trying To Update With Index: " + PropertyIndex.ToString());
                    //DebugP.Send("Start Property Update");
                    //DebugP.Send("a1 IDPropertyIndex Value: " + IDPropertyIndex.ToString());
                    //DebugP.Send("a2 Current Value: " + NewProperty2.value.ToString());
                    NewProperty2.value = existingIDsCount.ToString();
                    //DebugP.Send("a3 ID Value Changed");
                    //DebugP.Send("a4 Current Value: " + NewProperty2.value.ToString());
                    //NewPropertyCategory.Properties().Remove(IDPropertyIndex);
                    //DebugP.Send("a5 ID Value Changed");
                    //NewPropertyCategory.Properties().Clear();// Works
                    //DebugP.Send("a6 Properties Category Cleared");

                    NewPropertyCategory.Properties().Add(NewProperty2);
                    //DebugP.Send("a7 Properties Re-Added");
                    NWPropertyNode.SetUserDefined((int)PropertyIndex, PropertiesNameString, "Custom_Properties_InteralName", NewPropertyCategory);
                    ++existingIDsCount;
                    //DebugP.Send("a8 Update Properties Complete");
                }
                catch (Exception e)
                {
                    MessageBox.Show("Failed To Change Custom Properties.\nExiting.", "ERROR: Exception Catch");
                    goto Exit;
                }
            }
            #endregion

            //////////////////////////////////////////////////////////////////////////////////////
            // Comb For Existing ID Objects
            // ?ERROR Possibility of Doubling Up Count Because Of Children Nodes
            //++existingIDsCount;

            // Show Location Of Working Directory
            //MessageBox.Show(Directory.GetCurrentDirectory());
            System.IO.File.AppendAllText(@".\" + KANGVars.PrimitivesFileName + ".txt", "File Made At " + CurrentTime + "\n\n");
            System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", "File Made At " + CurrentTime + "\n\nName,,X,Y,Z\n");

            // create the callback object
            CallbackGeomListener callbkListener = new CallbackGeomListener();
            foreach (ComApi.InwOaPath3 objectPath in CurrentGUISelection.Paths())// Each Object In The Selection As Distinguished By Individual Paths
            {
                // Properties
                KANGVars.strg = levelOneIterator.ToString();

                foreach (PropertyCategory oPC in ObjectSelectionInNet[(int)levelOneIterator].PropertyCategories)
                {
                    //DebugP.Send("Loop Value: " + oPC.DisplayName);
                }

                //MessageBox.Show("Begin Level1: " + levelOneIterator.ToString());
                int TriangleExceptionCount = 0;
                foreach (ComApi.InwOaFragment3 frag in objectPath.Fragments())// Each Fragment Part Of Object
                {
                    //DebugP.Send("Begin Level2: " + levelTwoIterator.ToString());
                    // generate the primitives
                    frag.GenerateSimplePrimitives(ComApi.nwEVertexProperty.eNORMAL, callbkListener);
                    try
                    {
                        callbkListener.Triangle(frag.Geometry, frag.Geometry, frag.Geometry);
                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show("An Error Occurred Calling Callback Method: '{0}'", e.ToString());
                        // Keep Count Of These Exceptions?
                        ++TriangleExceptionCount;
                        if (TriangleExceptionCount > 1)
                        {
                            EndMessage = EndMessage + "\nERROR: Primitives Exceptions Exceed 1!";
                            //DebugP("ERROR: Primitives Exceptions Exceed 1!");
                        }
                    }
                    ++levelTwoIterator;
                }
                ++levelOneIterator;
                // XYZ Lengths From Min Max Values
                string XYZLengths = "";
                float  calcValue;
                calcValue  = KANGlobalMinMaxCoords.maxX - KANGlobalMinMaxCoords.minX;
                XYZLengths = "," + calcValue.ToString();
                calcValue  = KANGlobalMinMaxCoords.maxY - KANGlobalMinMaxCoords.minY;
                XYZLengths = XYZLengths + "," + calcValue.ToString();
                calcValue  = KANGlobalMinMaxCoords.maxZ - KANGlobalMinMaxCoords.minZ;
                XYZLengths = XYZLengths + "," + calcValue.ToString() + "\n";
                System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", KANGVars.strg + ",");
                System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", XYZLengths);
                #region Reset Global Min Max
                KANGlobalMinMaxCoords.minX = 100000;
                KANGlobalMinMaxCoords.maxX = -100000;
                KANGlobalMinMaxCoords.minY = 100000;
                KANGlobalMinMaxCoords.maxY = -100000;
                KANGlobalMinMaxCoords.minZ = 100000;
                KANGlobalMinMaxCoords.maxZ = -100000;
                #endregion // Reset Global Min Max
            }


            EndMessage = EndMessage + "\n Objects Evaluated: " + ObjectSelectionInNet.Count.ToString();

Exit:
            EndMessage = EndMessage + "\n\nPlugin Operation Exit.";
            MessageBox.Show(EndMessage);
            return(0);
        }
        void CurrentSelection_Changed(object sender,
                                      System.EventArgs e)
        {
            if (sender != null)
            {
                Document oDoc = sender as Document;


                if (oDoc.Title == "gatehouse.nwd")
                {
                    //this is the new selection after selecting
                    if (oDoc.CurrentSelection.SelectedItems.Count > 0)
                    {
                        ComApi.InwOpState9 oState = ComApiBridge.State;

                        try
                        {
                            ComApi.InwOaPath3 oPath = oState.CurrentSelection.Paths()[1];
                            if ((oPath.Nodes().Last() as ComApi.InwOaNode).IsLayer)
                            {
                                //check whether the custom property tab has been added.

                                string mytabname         = "MyCustomTabUserName";
                                int    customProTabIndex = 1;
                                ComApi.InwGUIPropertyNode2 nodePropertiesOwner = oState.GetGUIPropertyNode(oPath, true) as ComApi.InwGUIPropertyNode2;
                                ComApi.InwGUIAttribute2    customTab           = null;
                                foreach (ComApi.InwGUIAttribute2 nwAtt in nodePropertiesOwner.GUIAttributes())
                                {
                                    if (!nwAtt.UserDefined)
                                    {
                                        continue;
                                    }

                                    if (nwAtt.ClassUserName == mytabname)
                                    {
                                        customTab = nwAtt;
                                        break;
                                    }
                                    customProTabIndex += 1;
                                }


                                if (customTab == null)
                                {
                                    ////create the tab if it does not exist
                                    ComApi.InwOaPropertyVec newPvec =
                                        (ComApi.InwOaPropertyVec)oState.ObjectFactory(
                                            ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);

                                    ComApi.InwOaProperty prop1 = oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaProperty) as ComApi.InwOaProperty;
                                    ComApi.InwOaProperty prop2 = oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaProperty) as ComApi.InwOaProperty;
                                    prop1.name     = "Finish";
                                    prop1.UserName = "******";
                                    object linkVal = m_dblink.read("Finish", (oPath.Nodes().Last() as ComApi.InwOaNode).UserName);
                                    if (linkVal != null)
                                    {
                                        prop1.value = linkVal;
                                        newPvec.Properties().Add(prop1);
                                    }

                                    prop2.name     = "Notes";
                                    prop2.UserName = "******";
                                    linkVal        = m_dblink.read("Notes", (oPath.Nodes().Last() as ComApi.InwOaNode).UserName);
                                    if (linkVal != null)
                                    {
                                        prop2.value = linkVal;
                                        newPvec.Properties().Add(prop2);
                                    }

                                    //the first argument is always 0 if adding a new tab
                                    nodePropertiesOwner.SetUserDefined(0, mytabname, mytabname, newPvec);
                                }
                                else
                                {
                                    ////update the properties in the tab with the new values from database
                                    ComApi.InwOaPropertyVec newPvec =
                                        (ComApi.InwOaPropertyVec)oState.ObjectFactory(
                                            ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);

                                    foreach (ComApi.InwOaProperty nwProp in customTab.Properties())
                                    {
                                        ComApi.InwOaProperty prop = oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaProperty) as ComApi.InwOaProperty;
                                        prop.name     = nwProp.name;
                                        prop.UserName = nwProp.UserName;
                                        object linkVal = m_dblink.read(prop.name, (oPath.Nodes().Last() as ComApi.InwOaNode).UserName);
                                        if (linkVal != null)
                                        {
                                            prop.value = linkVal;
                                            newPvec.Properties().Add(prop);
                                        }
                                    }
                                    nodePropertiesOwner.SetUserDefined(customProTabIndex, mytabname, mytabname, newPvec);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
        }
예제 #6
0
        public static void SetPropsMethod(ComApi.InwOpState3 oState,
                                          ModelItemCollection modelItemColl, List <DisplayDataTab> displayDataTabs,
                                          List <DisplayURL> displayURLs, bool overwriteUserAttr, bool overwriteLinks,
                                          bool preserveExistingProperties)
        {
            //Удалить пустые строки из наборов
            displayDataTabs.RemoveAll(ddt => String.IsNullOrEmpty(ddt.DisplayName));
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                ddt.DisplayProperties.RemoveAll(dp => String.IsNullOrEmpty(dp.DisplayName));
            }
            displayURLs.RemoveAll(dUrl =>
                                  String.IsNullOrEmpty(dUrl.DisplayName) || String.IsNullOrEmpty(dUrl.URL));

            //Если пользователь зачем-то ввел значение нередактируемого свойства, то убрать его
            DisplayDataTab idDataTab
                = displayDataTabs.Find(ddt => ddt.DisplayName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME));

            if (idDataTab != null)
            {
                idDataTab.DisplayProperties.RemoveAll(p
                                                      => propsNotModifiable.Contains(p.DisplayName));
            }

            //Конвертировать значения всех свойств
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                foreach (DisplayProperty dp in ddt.DisplayProperties)
                {
                    dp.ConvertValue();
                }
            }


            #region Старое

            /*
             *  //Заполнить список свойств, которые нужно будет добавить на панель Id
             *  ComApi.InwOaPropertyVec idDataTabPropertyVec = (ComApi.InwOaPropertyVec)oState
             *                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
             *                  null, null);
             *
             *  //Заполнить список свойств для панели Id
             *  //(в ней хранятся уникальные Id для каждого элемента, которые не должны меняться этой командой)
             *  if (idDataTab != null)
             *  {
             *      foreach (DisplayProperty dp in idDataTab.DisplayProperties)
             *      {
             *          idDataTabPropertyVec.Properties()
             *              .Add(Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value));
             *      }
             *  }
             */

            //Заполнены ли списки свойств?
            //Если список пустой, то панели должны быть удалена
            //bool userPropsDefined = displayDataTabs.Count > 0;


            //Создание набора для присоединения к объектам модели
            //List<DisplayDataTab> propsToSet = new List<DisplayDataTab>();
            #endregion

            //Словарь свойств, которые добавляются
            Dictionary <string, DisplayProperty> propsDefined = new Dictionary <string, DisplayProperty>();

            //Создать базовые наборы свойств, которые будут привязываться к объектам
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                //if (!ddt.DisplayName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME))
                //{
                //ddt.InwOaPropertyVec = (ComApi.InwOaPropertyVec)oState
                //        .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                //        null, null);
                //propsToSet.Add(ddt);
                foreach (DisplayProperty dp in ddt.DisplayProperties)
                {
                    //ComApi.InwOaProperty newP
                    //        = Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value);
                    //// add the new property to the new property category
                    //ddt.InwOaPropertyVec.Properties().Add(newP);

                    string key = ddt.DisplayName + dp.DisplayName;
                    if (!propsDefined.ContainsKey(key))
                    {
                        propsDefined.Add(key, dp);
                    }
                }
                //}
            }

            //словарь ссылок, которые добавляются
            Dictionary <string, string> linksDefined = new Dictionary <string, string>();

            //Создание набора ссылок для привязки к объектам
            //ComApi.InwOpState10 state = ComApiBridge.ComApiBridge.State;
            //ComApi.InwURLOverride urlOverride
            //    = (ComApi.InwURLOverride)state
            //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);
            //ComApi.InwURLColl oURLColl = urlOverride.URLs();
            foreach (DisplayURL dUrl in displayURLs)
            {
                //ComApi.InwURL2 oUrl = (ComApi.InwURL2)state
                //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                //oUrl.name = dUrl.DisplayName;
                //oUrl.URL = dUrl.URL;
                //oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка
                //oURLColl.Add(oUrl);

                string key = dUrl.DisplayName;
                if (!linksDefined.ContainsKey(key))
                {
                    linksDefined.Add(key, dUrl.URL);
                }
            }


            foreach (ModelItem item in modelItemColl.DescendantsAndSelf)
            {
                //convert the .NET object to COM object
                ComApi.InwOaPath oPath = ComApiBridge.ComApiBridge.ToInwOaPath(item);


                //Переделать панель атрибутов в соответствии с заполненными строками в окне
                if (overwriteUserAttr)//Только если стояла галка в окне!!!
                {
                    //наборы свойств
                    //ключ - имя панели, значение - набор свойств для привязки к объекту
                    Dictionary <string, ComApi.InwOaPropertyVec> propVectorsCurr
                        = new Dictionary <string, ComApi.InwOaPropertyVec>();
                    // Сначала скопировать базовые наборы свойств для каждой из заданных панелей в словарь
                    //foreach (DisplayDataTab ddt in displayDataTabs)
                    //{
                    //    propVectorsCurr.Add(ddt.DisplayName, ddt.InwOaPropertyVec.Copy());
                    //}

                    //Изучаются текущие свойства объекта модели
                    //Сначала в наборы свойств нужно добавить если присутствуют:
                    //- свойства, которые не редактируются данной командой
                    //- если нажата галка "Не удалять свойства", то любые свойства, которых не было в окне SetProps
                    //- свойства которые были заданы в окне SetProps, но они уже присутствуют в модели
                    //  (их значение задается как введено в окне,
                    //  если эти свойства добавлены на этом этапе, то они не должны добавляться на следующем)
                    HashSet <string> alreadyAdded = new HashSet <string>();//набор ключей свойств, которые добавлены на этом этапе

                    ComApi.InwGUIPropertyNode2 propn
                        = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                    foreach (ComApi.InwGUIAttribute2 attr in propn.GUIAttributes())
                    {
                        if (attr.UserDefined)
                        {
                            foreach (ComApi.InwOaProperty prop in attr.Properties())
                            {
                                string key = attr.ClassUserName + prop.UserName;

                                if (
                                    (attr.ClassUserName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME) && propsNotModifiable.Contains(prop.UserName)) //- свойства, которые не редактируются данной командой
                                    ||
                                    (preserveExistingProperties && !propsDefined.ContainsKey(key))                                         //- если нажата галка Не удалять свойства, то любые свойства, которых не было в окне
                                    ||
                                    propsDefined.ContainsKey(key)                                                                          //- свойства которые были заданы в окне SetProps, но они уже присутствуют в модели
                                    )
                                {
                                    ComApi.InwOaPropertyVec vec = null;
                                    propVectorsCurr.TryGetValue(attr.ClassUserName, out vec);
                                    if (vec == null)
                                    {
                                        vec = (ComApi.InwOaPropertyVec)oState
                                              .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                                                             null, null);
                                        propVectorsCurr.Add(attr.ClassUserName, vec);
                                    }
                                    if (!propsDefined.ContainsKey(key))
                                    {
                                        vec.Properties().Add(Utils.CopyProp(oState, prop));
                                    }
                                    else
                                    {
                                        //Учесть введенное значение
                                        DisplayProperty dp = propsDefined[key];
                                        vec.Properties().Add(Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value));
                                        alreadyAdded.Add(key);
                                    }
                                }
                            }
                        }
                    }

                    //Затем добавить вновь создаваемые свойства, которых ранее не было в модели
                    //(с учетом тех, которые были добавлены на предыдущем этапе)
                    foreach (DisplayDataTab ddt in displayDataTabs)
                    {
                        ComApi.InwOaPropertyVec vec = null;
                        propVectorsCurr.TryGetValue(ddt.DisplayName, out vec);
                        if (vec == null)
                        {
                            vec = (ComApi.InwOaPropertyVec)oState
                                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                                                 null, null);
                            propVectorsCurr.Add(ddt.DisplayName, vec);
                        }

                        foreach (DisplayProperty dp in ddt.DisplayProperties)
                        {
                            string key = ddt.DisplayName + dp.DisplayName;
                            if (!alreadyAdded.Contains(key))
                            {
                                ComApi.InwOaProperty newP
                                    = Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value);
                                // add the new property to the new property category
                                vec.Properties().Add(newP);
                            }
                        }
                    }


                    //Удалить старые панели
                    try
                    { propn.RemoveUserDefined(0); }
                    catch (System.Runtime.InteropServices.COMException) { }
                    //Создать новые
                    foreach (KeyValuePair <string, ComApi.InwOaPropertyVec> kvp in propVectorsCurr)
                    {
                        propn.SetUserDefined(0, kvp.Key, "S1NF0",
                                             kvp.Value);
                    }

                    #region Старое

                    /*
                     *          // get properties collection of the path
                     *          ComApi.InwGUIPropertyNode2 propn
                     *              = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                     *
                     *
                     *
                     *          ComApi.InwOaPropertyVec idDataTabPropertyVecCurr = idDataTabPropertyVec.Copy();
                     *
                     *          //Добавить нередактируемые свойства если они есть в исходном
                     *          foreach (string dn in propsNotModifiable)
                     *          {
                     *              DataProperty prop = item.PropertyCategories
                     *              .FindPropertyByDisplayName(S1NF0_DATA_TAB_DISPLAY_NAME, dn);
                     *
                     *              if (prop != null)
                     *              {
                     *                  ComApi.InwOaProperty copyProp = Utils.CopyProp(oState, prop);
                     *                  idDataTabPropertyVecCurr.Properties().Add(copyProp);
                     *              }
                     *          }
                     *
                     *
                     *          //Удалить старые панели
                     *          try
                     *          { propn.RemoveUserDefined(0); }
                     *          catch (System.Runtime.InteropServices.COMException) { }
                     *          //Создать новые
                     *          if (userPropsDefined)
                     *          {
                     *              foreach (DisplayDataTab ddt in propsToSet)
                     *              {
                     *                  //Создание одной панели
                     *                  propn.SetUserDefined(0, ddt.DisplayName, "S1NF0",
                     *                      ddt.InwOaPropertyVec);
                     *              }
                     *
                     *              //Создание панели Id
                     *              if (idDataTabPropertyVecCurr.Properties().Count > 0)
                     *              {
                     *                  propn.SetUserDefined(0, S1NF0_DATA_TAB_DISPLAY_NAME, "S1NF0",
                     *                      idDataTabPropertyVecCurr);
                     *              }
                     *
                     *
                     *          }
                     */
                    #endregion
                }



                //Переделать все ссылки в соответствии с заполненными строками в окне
                if (overwriteLinks)//Только если стояла галка в окне!!!
                {
                    ComApi.InwURLOverride urlOverrideCurr = (ComApi.InwURLOverride)oState
                                                            .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);//urlOverride.Copy();

                    //Изучаются текущие ссылки
                    //Сначала в набор ссылок нужно добавить если присутствуют:
                    //- если нажата галка "Не удалять свойства", то любые ссылки, которых не было в окне SetProps
                    //- ссылки которые были заданы в окне SetProps, но они уже присутствуют в модели
                    //  (их значение задается как введено в окне,
                    //  если эти ссылки добавлены на этом этапе, то они не должны добавляться на следующем)
                    HashSet <string> alreadyAdded = new HashSet <string>();//набор ключей ссылок, которые добавлены на этом этапе

                    PropertyCategory linksCat = item.PropertyCategories.FindCategoryByName("LcOaExURLAttribute");
                    if (linksCat != null)
                    {
                        int linksCount = linksCat.Properties.Count / 3;

                        for (int i = 0; i < linksCount; i++)
                        {
                            string       suffix   = i == 0 ? "" : i.ToString();
                            DataProperty nameProp = item.PropertyCategories
                                                    .FindPropertyByName("LcOaExURLAttribute", "LcOaURLAttributeName" + suffix);
                            DataProperty urlProp = item.PropertyCategories
                                                   .FindPropertyByName("LcOaExURLAttribute", "LcOaURLAttributeURL" + suffix);
                            if (nameProp != null && urlProp != null)
                            {
                                string key = nameProp.Value.ToDisplayString();
                                if ((preserveExistingProperties && !linksDefined.ContainsKey(key))//- если нажата галка "Не удалять свойства", то любые ссылки, которых не было в окне SetProps
                                    ||
                                    (linksDefined.ContainsKey(key)))
                                {
                                    ComApi.InwURL2 oUrl = (ComApi.InwURL2)oState
                                                          .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                                    oUrl.name = nameProp.Value.ToDisplayString();
                                    if (!linksDefined.ContainsKey(key))
                                    {
                                        oUrl.URL = urlProp.Value.ToDisplayString();//Сохранить существующее значение
                                    }
                                    else
                                    {
                                        oUrl.URL = linksDefined[key];//присвоить заданное в окне значение ссылки
                                        alreadyAdded.Add(key);
                                    }
                                    oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка

                                    urlOverrideCurr.URLs().Add(oUrl);
                                }
                            }
                        }
                    }


                    foreach (DisplayURL dUrl in displayURLs)
                    {
                        string key = dUrl.DisplayName;
                        if (!alreadyAdded.Contains(key))
                        {
                            ComApi.InwURL2 oUrl = (ComApi.InwURL2)oState
                                                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                            oUrl.name = dUrl.DisplayName;
                            oUrl.URL  = dUrl.URL;
                            oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка
                            urlOverrideCurr.URLs().Add(oUrl);
                        }
                    }


                    ComApi.InwOpSelection comSelectionOut =
                        ComApiBridge.ComApiBridge.ToInwOpSelection(new ModelItemCollection()
                    {
                        item
                    });
                    oState.SetOverrideURL(comSelectionOut, urlOverrideCurr);
                }
            }
        }
예제 #7
0
        private void SearchForExcelTableMatches
            (Document doc, IEnumerable <ModelItem> items, bool ignoreNonVisible,
            Excel.Range keyColumn,
            //Dictionary<string, int> keyValues,
            /*NamedConstant*/ string keyCatName, /*NamedConstant*/ string keyPropName,
            ComApi.InwOpState3 oState, Excel._Worksheet worksheet,
            SortedDictionary <int, Common.ExcelInterop.CellValue> tableHeader, string tabName
            )
        {
            foreach (ModelItem item in items)
            {
                if (ignoreNonVisible && item.IsHidden)
                {
                    continue;//Пропустить скрытый элемент
                }

                DataProperty property
                    = item.PropertyCategories.FindPropertyByDisplayName/*.FindPropertyByCombinedName*/ (keyCatName, keyPropName);
                //object searchValue = Utils.GetUserPropValue(property.Value);
                string searchValue = Utils.GetDisplayValue(property.Value);
                //Найти в выбранном столбце Excel ячейку с таким же значением


                Excel.Range row = keyColumn.Find(searchValue,
                                                 LookIn: Excel.XlFindLookIn.xlValues, LookAt: Excel.XlLookAt.xlWhole,
                                                 SearchOrder: Excel.XlSearchOrder.xlByColumns,
                                                 MatchByte: false);

                //int rowNum = 0;
                //keyValues.TryGetValue(searchValue, out rowNum);

                if (/*rowNum != 0*/ row != null)
                {
                    matchCount++;

                    int rowNum = row.Row;
                    //Получить данные из этой строки таблицы
                    SortedDictionary <int, Common.ExcelInterop.CellValue> rowValues
                        = Common.ExcelInterop.Utils.GetRowValues(worksheet, rowNum);
                    //Привязать пользовательские атрибуты как в строке таблицы. Если такие атрибуты уже были созданы, то переписать их значение
                    //Набор свойств для задания для этого элемента модели
                    ComApi.InwOaPropertyVec propsToSet
                        = oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec);
                    //Заполнить данными из строки Excel
                    foreach (KeyValuePair <int, Common.ExcelInterop.CellValue> kvp in tableHeader)
                    {
                        int    colIndex = kvp.Key;
                        string propName = kvp.Value.DisplayString;
                        Common.ExcelInterop.CellValue cellValue = null;
                        rowValues.TryGetValue(colIndex, out cellValue);
                        object propValue = null;
                        if (cellValue != null)
                        {
                            propValue = Utils.ConvertValueByString(cellValue.DisplayString);//.Value2;
                        }

                        // create new property
                        ComApi.InwOaProperty newP = Utils.CreateNewUserProp(oState, propName, propValue);

                        // add the new property to the new property category
                        propsToSet.Properties().Add(newP);
                    }


                    foreach (ModelItem dItem in item.DescendantsAndSelf)
                    {
                        //convert the .NET collection to COM object
                        ComApi.InwOaPath oPath = ComApiBridge.ComApiBridge.ToInwOaPath(dItem);
                        //Получить текущие свойства элемента
                        ComApi.InwGUIPropertyNode2 propertyNode
                            = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                        //Проверить есть ли у элемента панель данных пользователя с точно таким же названием
                        //Получить ее индекс
                        int indexToSet = 0;
                        int i          = 1;
                        foreach (ComApi.InwGUIAttribute2 attr in propertyNode.GUIAttributes())
                        {
                            if (attr.UserDefined)
                            {
                                if (attr.ClassUserName.Equals(tabName))
                                {
                                    indexToSet = i;
                                    break;
                                }
                                else
                                {
                                    i++;
                                }
                            }
                        }

                        //Перезаписать панель данными из Excel
                        propertyNode.SetUserDefined(
                            indexToSet,
                            tabName, "S1NF0", propsToSet);
                    }
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(row);
                }
                else
                {
                    //Если неправильно указать ключевое свойство и столбец, возникает зависание из-за многократного поиска Search во вложенных элементах

                    //Search search = new Search();
                    //search.Selection.CopyFrom(item.Descendants);
                    //search.PruneBelowMatch = true;//объекты без вложенных
                    //search.SearchConditions
                    //    .Add(SearchCondition.HasPropertyByCombinedName(keyCatCombName, keyPropCombName));
                    //ModelItemCollection dItems = search.FindAll(doc, false);

                    //IEnumerable<ModelItem> dItems
                    //    = item.Descendants.Where(SearchCondition.HasPropertyByCombinedName(keyCatCombName, keyPropCombName));//Не обрезает вложенные объекты


                    //TODO: Это чревато огромными задержками на большой модели если неправильно задано ключевое поле!!!
                    //Вместо Search API Линейный поиск по дереву до нахождения соответствия
                    List <ModelItem> dItems = new List <ModelItem>();
                    SearchHasPropertyByCombinedName(item.Children, keyCatName, keyPropName, dItems);


                    SearchForExcelTableMatches(doc, dItems, ignoreNonVisible,
                                               keyColumn,
                                               //keyValues,
                                               keyCatName, keyPropName,
                                               oState, worksheet, tableHeader, tabName
                                               );
                }
            }
        }
        public void Add_newTab(IEnumerable <ModelItem> items, string[] Lines, int N)
        {
            // Intialize the parameters
            ComApi.InwOpState9 oState              = ComApiBridge.State;
            string[]           OldCategory         = new string[N];
            string[]           OldParameters       = new string[N];
            string[]           NewParameters       = new string[N];
            string[]           Parameters_hasAdded = new string[N];
            int     ind = 0;
            Boolean Parameter_isNotRepeated = true;

            ComApi.InwOaProperty[] NewProperties = new ComApi.InwOaProperty[N];

            // Iterate over all the selected items
            foreach (ModelItem oItem in items)
            {
                if (oItem.Children.Count() > 0)
                {
                    // Convert the .NET to COM object
                    ComApi.InwOaPath oPath = ComApiBridge.ToInwOaPath(oItem);
                    // Create new property category
                    ComApi.InwOaPropertyVec newPvec = (ComApi.InwOaPropertyVec)oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
                    // Get properties collection of the path
                    ComApi.InwGUIPropertyNode2 propn = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                    // Iterate over all properties in textfile
                    ind = 0;
                    for (int i = 1; i < N; i++)
                    {
                        // Check if line is empty
                        if (Lines[i] != null && Lines[i].Length > 1)
                        {
                            // Get Category, old property and new property from the line
                            string[] WordsInLine = Lines[i].Split('\t');
                            OldCategory[i]   = WordsInLine[0];
                            OldParameters[i] = WordsInLine[1];
                            NewParameters[i] = WordsInLine[2];
                            // By default the property is not repeated
                            Parameter_isNotRepeated = true;
                            // Iterate over properties of the item
                            foreach (PropertyCategory oPC in oItem.PropertyCategories)
                            {
                                if (oPC.DisplayName == OldCategory[i])
                                {
                                    foreach (DataProperty oDP in oPC.Properties)
                                    {
                                        if (oDP.DisplayName == OldParameters[i])
                                        {
                                            // Create new property
                                            NewProperties[i]          = (ComApi.InwOaProperty)oState.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
                                            NewProperties[i].name     = NewParameters[i];
                                            NewProperties[i].UserName = NewParameters[i];

                                            // Check if the property had been added
                                            Parameters_hasAdded[ind] = NewParameters[i]; ind = ind + 1;
                                            for (int d = 0; d < ind - 1; d++)
                                            {
                                                if (NewParameters[i] == Parameters_hasAdded[d])
                                                {
                                                    Parameter_isNotRepeated = false;
                                                }
                                            }
                                            //  If the property had not added yet, add it
                                            if (Parameter_isNotRepeated)
                                            {
                                                // Check datatype of the property
                                                switch (oDP.Value.DataType)
                                                {
                                                case VariantDataType.Boolean:
                                                    bool NewValueBool = oDP.Value.ToBoolean();
                                                    NewProperties[i].value = NewValueBool;
                                                    break;

                                                case VariantDataType.DateTime:
                                                    DateTime NewValueDate = oDP.Value.ToDateTime();
                                                    NewProperties[i].value = NewValueDate;
                                                    break;

                                                case VariantDataType.DisplayString:
                                                    string NewValueDString = oDP.Value.ToDisplayString();
                                                    NewProperties[i].value = NewValueDString;
                                                    break;

                                                case VariantDataType.Double:
                                                    double NewValueDouble = oDP.Value.ToDouble();
                                                    NewProperties[i].value = NewValueDouble;
                                                    break;

                                                case VariantDataType.DoubleAngle:
                                                    double NewValueAngle = oDP.Value.ToDoubleAngle();
                                                    NewProperties[i].value = NewValueAngle;
                                                    break;

                                                case VariantDataType.DoubleArea:
                                                    double NewValueArea = oDP.Value.ToDoubleArea();
                                                    NewProperties[i].value = NewValueArea * Math.Pow(meter_scale, 2);
                                                    break;

                                                case VariantDataType.DoubleLength:
                                                    double NewValueLength = oDP.Value.ToDoubleLength();
                                                    NewProperties[i].value = NewValueLength * meter_scale;
                                                    break;

                                                case VariantDataType.DoubleVolume:
                                                    double NewValueVolume = oDP.Value.ToDoubleVolume();
                                                    NewProperties[i].value = NewValueVolume * Math.Pow(meter_scale, 3);
                                                    break;

                                                case VariantDataType.IdentifierString:
                                                    string NewValueIString = oDP.Value.ToIdentifierString();
                                                    NewProperties[i].value = NewValueIString;
                                                    break;

                                                case VariantDataType.Int32:
                                                    int NewValueInt = oDP.Value.ToInt32();
                                                    NewProperties[i].value = NewValueInt;
                                                    break;

                                                case VariantDataType.NamedConstant:
                                                    NamedConstant NewValueConst = oDP.Value.ToNamedConstant();
                                                    String        s             = NewValueConst.DisplayName;
                                                    s = s.Substring(s.IndexOf("\"") + 1);
                                                    s = s.Substring(0, s.IndexOf("\""));

                                                    NewProperties[i].value = s;
                                                    break;

                                                case VariantDataType.None:
                                                    string NewValueNone = oDP.Value.ToString();
                                                    NewProperties[i].value = NewValueNone;
                                                    break;

                                                case VariantDataType.Point3D:
                                                    string NewValuePoint = oDP.Value.ToString();
                                                    NewProperties[i].value = NewValuePoint;
                                                    break;
                                                }
                                                // Add the new property to the new property category
                                                newPvec.Properties().Add(NewProperties[i]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Add new tab to the object
                    // The name of the newtab is saved in first line in the textfile
                    propn.SetUserDefined(0, Lines[0], "MyAttribute", newPvec);
                }
            }
        }