public IECInstance getInstanceForCurrentSelection
        (
            int rowIndex,
            string dropDownValue
        )
        {
            DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, rowIndex] as DataGridViewComboBoxCell;

            if (itemInstanceCell.Tag == null)
            {
                return(null);
            }

            IECClass ecClass = itemInstanceCell.Tag as IECClass;

            if (null != ecClass)
            {
                return(null);
            }

            Dictionary <string, IECInstance> cachedInstances = itemInstanceCell.Tag as Dictionary <string, IECInstance>;

            if (null == cachedInstances)
            {
                return(null);
            }

            if (cachedInstances.ContainsKey(dropDownValue))
            {
                return(cachedInstances[dropDownValue]);
            }

            return(null);
        }
        public IECClass getECClassInformationForCurrentSelection
        (
            int rowIndex
        )
        {
            DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, rowIndex] as DataGridViewComboBoxCell;
            IECClass ecClass = itemInstanceCell.Tag as IECClass;

            if (null != ecClass)
            {
                return(ecClass);
            }

            if (itemInstanceCell.Tag == null)
            {
                return(null);
            }

            Dictionary <string, IECInstance> cachedInstances = itemInstanceCell.Tag as Dictionary <string, IECInstance>;

            if (null == cachedInstances)
            {
                return(null);
            }

            foreach (KeyValuePair <string, IECInstance> entry in cachedInstances)
            {
                ecClass = entry.Value.ClassDefinition;
                break;
            }

            return(ecClass);
        }
Ejemplo n.º 3
0
 public ImportItem(IECClass cls, string instanceIdName)
 {
     Instance = cls.CreateInstance();
     RelationClassValueCache = new Dictionary <string, object> ();
     Instance.InstanceId     = instanceIdName;
     Valid = true;
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Writes the stream states to the current schema.
        /// </summary>
        /// <param name="streamStates"></param>
        public static void WriteStreamStateList(DgnFile File, List <StreamState> streamStates)
        {
            DgnECManager       Manager = DgnECManager.Manager;
            FindInstancesScope scope   = FindInstancesScope.CreateScope(File, new FindInstancesScopeOption(DgnECHostType.All));

            IECSchema schema  = RetrieveSchema(File, scope);
            IECClass  ecClass = schema.GetClass(className);

            ECQuery readWidget = new ECQuery(ecClass);

            readWidget.SelectClause.SelectAllProperties = true;

            using (DgnECInstanceCollection instances = Manager.FindInstances(scope, readWidget))
            {
                foreach (IDgnECInstance instance in instances)
                {
                    instance.Delete();
                }
            }

            DgnECInstanceEnabler instanceEnabler = Manager.ObtainInstanceEnabler(File, ecClass);

            var data = JsonConvert.SerializeObject(streamStates) as string;
            StandaloneECDInstance _instance = instanceEnabler.SharedWipInstance;

            _instance.SetAsString(propertyName, data);
            instanceEnabler.CreateInstanceOnFile(File, _instance);
        }
Ejemplo n.º 5
0
        protected bool PropertyExists(IECClass cls, string propertyName)
        {
            if (cls == null)
            {
                return(false);
            }

            return(cls.FindProperty(propertyName) == null ? false : true);
        }
Ejemplo n.º 6
0
        protected ImportItem CreateInstance(string clsName, string instanceIdName)
        {
            IECClass cls = GetClass(clsName);

            if (cls == null)
            {
                return(null);
            }
            return(new ImportItem(cls, instanceIdName));
        }
Ejemplo n.º 7
0
        protected bool PropertyExists(string clsName, string propertyName)
        {
            IECClass cls = GetClass(clsName);

            if (cls == null)
            {
                return(false);
            }

            return(cls.FindProperty(propertyName) == null ? false : true);
        }
Ejemplo n.º 8
0
        protected bool IsAPBS(string clsName)
        {
            if (string.IsNullOrEmpty(clsName))
            {
                return(false);
            }

            IECClass cls = m_AppSchema.GetClass(clsName);

            return(cls != null && cls.Is(PBSParentCls) ? true : false);
        }
Ejemplo n.º 9
0
        public static List <CellHeaderElement> FindSPDSElementsByInstance(DgnModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }

            DgnFile      file      = model.GetDgnFile();
            DgnFileOwner fileOwner = new DgnFileOwner(file);

            IECSchema Schema = null;

            { // todo Правильная инициализация схемы:
                Schema = DgnECManager.Manager?.LocateDeliveredSchema(
                    ECHelper.SCHEMA_NAME,
                    VrnMajor, VrnMinor, SchemaMatchType.LatestCompatible, file);
            }

            if (Schema == null)
            {
                return(null);
            }

            IECClass commonClass = Schema.GetClass(ECCLASS_COMMON_NAME);

            ECQuery query = new ECQuery(commonClass);

            var modelConn = DgnModelRepositoryConnection.CreateConnection(
                new DgnECConnectionOptions(), fileOwner, model);

            var instColl = DgnECManager.Manager.FindDgnECInstances(modelConn, query);

            if (instColl == null)
            {
                return(null);
            }

            List <CellHeaderElement> resList = new List <CellHeaderElement>();

            foreach (var item in instColl)
            {
                Element element;
                if (DgnECManager.TryGetElementInfo(modelConn, item.InstanceId,
                                                   out element))
                {
                    if (element is CellHeaderElement)
                    {
                        resList.Add(element as CellHeaderElement);
                    }
                }
            }
            return(resList);
        }
Ejemplo n.º 10
0
            public static DgnECInstanceCollection RetrieveInstances()
            {
                DgnFile      File    = Session.Instance.GetActiveDgnFile();
                DgnECManager Manager = DgnECManager.Manager;

                FindInstancesScope scope   = FindInstancesScope.CreateScope(File, new FindInstancesScopeOption(DgnECHostType.All));
                IECSchema          schema  = Manager.LocateSchemaInScope(scope, schemaName, 1, 0, SchemaMatchType.Latest);
                IECClass           ecClass = schema.GetClass(className);

                ECQuery readWidget = new ECQuery(ecClass);

                readWidget.SelectClause.SelectAllProperties = true;
                DgnECInstanceCollection instances = Manager.FindInstances(scope, readWidget);

                return(instances);
            }
        private IECInstance GetAssociatedItemFromInstance
        (
            IECInstance ecInstance,
            IECRelationshipClass ecRelClass,
            IECClass ecParentClass
        )
        {
            DgnUtilities dgnUtil = DgnUtilities.GetInstance();

            if (ecInstance.InstanceId == "mechanical")
            {
                return(null);
            }

            ECInstanceList ecList = dgnUtil.GetParentInstances(ecInstance, ecRelClass, ecParentClass, dgnUtil.GetDGNConnection());

            return((ecList.Count > 0) ? ecList[0] : null);
        }
Ejemplo n.º 12
0
            public static IDgnECInstance RetrieveInstance(StreamState streamState)
            {
                DgnFile      File    = Session.Instance.GetActiveDgnFile();
                DgnECManager Manager = DgnECManager.Manager;

                FindInstancesScope scope   = FindInstancesScope.CreateScope(File, new FindInstancesScopeOption(DgnECHostType.All));
                IECSchema          schema  = Manager.LocateSchemaInScope(scope, schemaName, 1, 0, SchemaMatchType.Latest);
                IECClass           ecClass = schema.GetClass(className);

                ECQuery readWidget = new ECQuery(ecClass);

                readWidget.SelectClause.SelectAllProperties = true;
                DgnECInstanceCollection instances = Manager.FindInstances(scope, readWidget);

                var instance = instances.Where(x => x["Id"].StringValue == streamState.Stream.id).FirstOrDefault();

                return(instance);
            }
        private void SaveSettings()
        {
            ArrayList arr = new ArrayList();

            for (int i = 0; i < this.Rows.Count; i++)
            {
                //DataGridViewTextBoxCell itemTypeCell = this[s_wbsClass, i] as DataGridViewTextBoxCell;
                //IECClass ecClass = itemTypeCell.Tag as IECClass;

                DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, i] as DataGridViewComboBoxCell;
                string   selectedInstanceString           = itemInstanceCell.Value as string;
                IECClass ecClass = getECClassInformationForCurrentSelection(i);
                //itemInstanceCell.Tag as IECClass;

                arr.Add(ecClass.Name + "=" + selectedInstanceString);
            }

            WorkspaceUtilities.SaveSettings("Associations." + _ClassDef.Name, arr);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Writes the stream states to the current schema.
        /// </summary>
        /// <param name="streamStates"></param>
        public static void WriteStreamStateList(List <StreamState> streamStates)
        {
            DgnFile      File    = Session.Instance.GetActiveDgnFile();
            DgnECManager Manager = DgnECManager.Manager;

            FindInstancesScope scope  = FindInstancesScope.CreateScope(File, new FindInstancesScopeOption(DgnECHostType.All));
            IECSchema          schema = Manager.LocateSchemaInScope(scope, schemaName, 1, 0, SchemaMatchType.Latest);

            if (schema == null)
            {
                schema = StreamStateListSchema.GetSchema();
            }

            IECClass ecClass = schema.GetClass(className);

            ECQuery readWidget = new ECQuery(ecClass);

            readWidget.SelectClause.SelectAllProperties = true;

            using (DgnECInstanceCollection instances = Manager.FindInstances(scope, readWidget))
            {
                foreach (IDgnECInstance instance in instances)
                {
                    instance.Delete();
                }
            }

            DgnECInstanceEnabler instanceEnabler = Manager.ObtainInstanceEnabler(File, ecClass);

            foreach (var streamState in streamStates)
            {
                var data = JsonConvert.SerializeObject(streamState) as string;
                StandaloneECDInstance instance = instanceEnabler.SharedWipInstance;

                instance.SetAsString("Id", streamState.Stream.id);
                instance.SetAsString("StreamData", data);

                instanceEnabler.CreateInstanceOnFile(File, instance);
            }
        }
        private void OnCellValueChanged
        (
            object sender,
            DataGridViewCellEventArgs e
        )
        {
            if (e.ColumnIndex != 1)
            {
                return;
            }

            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            IECClass ecClass = getECClassInformationForCurrentSelection(e.RowIndex);
            //this[ClassColumn, e.RowIndex].Tag as IECClass;
            IECRelationshipClass ecRelClass = getECRelationshipClassInformationForCurrentSelection(e.RowIndex);
            //this[ClassColumn, e.RowIndex].Tag as IECRelationshipClass;
            string strVal = LocalizableStrings.None;

            if (null != this[ComboBoxColumn, e.RowIndex].Value)
            {
                strVal = this[ComboBoxColumn, e.RowIndex].Value.ToString();
            }

            if (strVal == _cstr_Varies)
            {
                return;
            }

            DgnUtilities dgnUtil = DgnUtilities.GetInstance();

            IECInstance newECIsnt = getInstanceForCurrentSelection(e.RowIndex, strVal);

            // get from Tag
            //dgnUtil.GetSourceInstance (ecClass, strVal);

            foreach (IECInstance ecInstance in _instList)
            {
                IECRelationshipInstanceCollection     ecRelCol      = ecInstance.GetRelationshipInstances();
                IEnumerator <IECRelationshipInstance> ecRelInstEnum = ecRelCol.GetEnumerator();

                bool newSourceSet = false;
                while (ecRelInstEnum.MoveNext())
                {
                    IECRelationshipInstance ecRelInst = ecRelInstEnum.Current;
                    if (!ecRelInst.ClassDefinition.Is(ecRelClass))
                    {
                        continue;
                    }

                    if (strVal == LocalizableStrings.None || string.IsNullOrEmpty(strVal))
                    {
                        ecRelCol.Remove(ecRelInst);
                    }
                    else
                    {
                        ecRelInst.Source = newECIsnt;
                    }
                    newSourceSet = true;
                    break;
                }

                if (!newSourceSet && newECIsnt != null)
                {
                    IECRelationshipInstance temporaryRelInst = ecRelClass.CreateInstance() as IECRelationshipInstance;
                    temporaryRelInst.Source = newECIsnt;
                    temporaryRelInst.Target = ecInstance;
                    ecInstance.GetRelationshipInstances().Add(temporaryRelInst);
                }

                IECInstance ecInst = newECIsnt;
                if (ecInst != null)
                {
                    if ((dgnUtil.IsECInstanceFromReferenceFile(ecInst) || dgnUtil.IsECInstanceReferencedOut(ecInst) || ecInst.IsReadOnly))
                    {
                        ecInst = null;
                    }
                }

                DataGridViewImageCell tempImageCell = this["optionEdit", e.RowIndex] as DataGridViewImageCell;
                tempImageCell.Tag = ecInst;

                tempImageCell     = this["optionDelete", e.RowIndex] as DataGridViewImageCell;
                tempImageCell.Tag = ecInst;

                //Mark the property (having business key CA/or NAME property if no Business key is defined) as changed and set the event which will reset the property pane.
                //This is required to update UNIT and SERVICE property listed in property pane on the fly whenever user changes the UNIT or SERVICE in ASSOCIATIONS pane.
                IECPropertyValue propVal = BusinessKeyUtility.GetPropertyValue(ecInstance);
                if (propVal != null)
                {
                    ecInstance.OnECPropertyValueChanged(propVal);
                }
            }

            SaveSettings();
        }
        private void OnCellMouseClick
        (
            object sender,
            DataGridViewCellMouseEventArgs e
        )
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            if (e.ColumnIndex == 1)
            {
                this.BeginEdit(true);
                ComboBox comboBox = (ComboBox)this.EditingControl;
                if (null != comboBox)
                {
                    comboBox.DroppedDown = true;
                }
            }

            if (e.ColumnIndex < AddButtonColumn)
            {
                return;
            }

            DgnUtilities dgnUtil = DgnUtilities.GetInstance();
            IECClass     ecClass = getECClassInformationForCurrentSelection(e.RowIndex);
            //this[ClassColumn, e.RowIndex].Tag as IECClass;
            IECRelationshipClass ecRelClass = getECRelationshipClassInformationForCurrentSelection(e.RowIndex);
            //this[ComboBoxColumn, e.RowIndex].Tag as IECRelationshipClass;
            DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, e.RowIndex] as DataGridViewComboBoxCell;

            string strVal = this[s_WBSInstanceKey, e.RowIndex].Value as string;

            if (strVal == LocalizableStrings.None && (e.ColumnIndex != AddButtonColumn && e.ColumnIndex != BrowseButtonColumn))
            {
                this[e.ColumnIndex, e.RowIndex].Selected = false;
                return;
            }

            //ADD///////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (e.ColumnIndex == AddButtonColumn)
            {
                // If we are connected to iModelHub we should acquire a a new tag for WBS

                ECInstanceDialog ecDlg = new ECInstanceDialog(ecClass.Name);
                ecDlg.ShowDialog();
                //User didn't save the new instance
                if (!ecDlg.SavePressed)
                {
                    return;
                }
                //We were not able to save the new instance
                if (!ecDlg.SaveData())
                {
                    return;
                }

                RefillItems(e.RowIndex, ecClass.Name);

                if (itemInstanceCell.Items.Count > 0)
                {
                    itemInstanceCell.Value = SchemaUtilities.GetDisplayNameForECInstance(ecDlg.GetECInstance(), false);
                }
            }
            //EDIT//////////////////////////////////////////////////////////////////////////////////////////////////////////
            else if (e.ColumnIndex == EditButtonColumn)
            {
                IECInstance ecInst = this[e.ColumnIndex, e.RowIndex].Tag as IECInstance;
                if (ecInst == null)
                {
                    MessageBox.Show(LocalizableStrings.NoEditDesc, LocalizableStrings.NoEditTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    IECInstance ecInstance = EditECInstance(ecInst);
                    if (ecInstance == null)
                    {
                        return;
                    }

                    RefillItems(e.RowIndex, ecClass.Name);

                    if (itemInstanceCell.Items.Count > 0)
                    {
                        itemInstanceCell.Value = SchemaUtilities.GetDisplayNameForECInstance(ecInstance, false);
                    }

                    _bInstanceModified = true;
                }
            }
            //DELETE////////////////////////////////////////////////////////////////////////////////////////////////////////
            else if (e.ColumnIndex == DeleteButtonColumn)
            {
                IECInstance ecInst = this[e.ColumnIndex, e.RowIndex].Tag as IECInstance;
                if (ecInst == null)
                {
                    MessageBox.Show(LocalizableStrings.NoDeleteDescRefOut, LocalizableStrings.NoDeleteTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    //.GetRelationshipInstances (ecClass.Name, _instance.ClassDefinition.Name, ecRelClass.Name, dgnUtil.GetDGNConnection());
                    ECInstanceList ecList = dgnUtil.GetRelatedInstances(ecInst, ecRelClass, _ClassDef, dgnUtil.GetDGNConnection());
                    if (ecList.Count > 0)
                    {
                        MessageBox.Show(string.Format(LocalizableStrings.NoDeleteDescAssocCompFound, itemInstanceCell.Value), LocalizableStrings.NoDeleteTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        return;
                    }

                    if (MessageBox.Show(String.Format(LocalizableStrings.AreYouSureDelete, SchemaUtilities.GetDisplayNameForECInstance(ecInst, true)),
                                        String.Format(LocalizableStrings.DeleteInstanceTitle, ecInst.ClassDefinition.DisplayLabel), MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.No)
                    {
                        return;
                    }

                    dgnUtil.DeleteECInstanceFromDgn(ecInst, dgnUtil.GetDGNConnection());

                    RefillItems(e.RowIndex, ecClass.Name);

                    if (itemInstanceCell.Items.Count > 0)
                    {
                        itemInstanceCell.Value = itemInstanceCell.Items[0];
                    }
                    else
                    {
                        itemInstanceCell.Value = null;
                    }
                }
                _bInstanceModified = true;
            }
            //BROWSE////////////////////////////////////////////////////////////////////////////////////////////////////////
            else if (e.ColumnIndex == BrowseButtonColumn)
            {
                IECInstance newEcinstance = ecClass.CreateInstance() as IECInstance;
                if (newEcinstance == null)
                {
                    return;
                }

                object instance = dgnUtil.TagBrowser(newEcinstance, dgnUtil.AssoicatedItemsTagBrowserOverrides);
                if (instance == null || !(instance is IECInstance))
                {
                    return;
                }
                IECInstance selectedECInstance = instance as IECInstance;

                //CommonTools.BIMAdapter.BIMAdapter.ReleaseTag (newEcinstance);
                dgnUtil.CopyProperties(selectedECInstance, newEcinstance, false);
                //BusinessKeyUtility.Release (newEcinstance);
                BusinessKeyUtility.SetIsReserved(newEcinstance, true);
                dgnUtil.UpdateFunctionalGuidProperty(selectedECInstance, newEcinstance);
                dgnUtil.WriteECInstanceToDgn(newEcinstance, dgnUtil.GetDGNConnection());

                //CommonTools.BIMAdapter
                //IECInstance inst = EditECInstance (ecInstance);
                //if(inst == null)
                //    return;
                //    inst = ecInstance;

                RefillItems(e.RowIndex, ecClass.Name);

                if (itemInstanceCell.Items.Count > 0)
                {
                    itemInstanceCell.Value = SchemaUtilities.GetDisplayNameForECInstance(newEcinstance, false);
                }

                _bInstanceModified = true;
            }
            this[e.ColumnIndex, e.RowIndex].Selected = false;
        }
        public bool LoadSettings
        (
            ArrayList arr,
            bool resetStandardPrefOnOnImport
        )
        {
            Hashtable hTable = new Hashtable();
            bool      status = true;

            string strUseStandPref = GetMSConfigVariable("OPM_EQUIP_ASSOC_USE_STANDPREF");

            if (Get2D3DInstance())
            {
                strUseStandPref = "1";
            }
            if (resetStandardPrefOnOnImport)
            {
                strUseStandPref = "";
            }

            for (int i = 0; i < arr.Count; i++)
            {
                string   strLine = arr[i] as string;
                string[] strs    = strLine.Split(new char[] { '=' });
                if (!hTable.ContainsKey(strs[0]))
                {
                    hTable.Add(strs[0], strs[1]);
                }
            }

            if (this == null)
            {
                return(status);
            }

            for (int i = 0; i < this.Rows.Count; i++)
            {
                DataGridViewTextBoxCell itemTypeCell = this[s_WBSClassKey, i] as DataGridViewTextBoxCell;
                IECClass ecClass = getECClassInformationForCurrentSelection(i);
                DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, i] as DataGridViewComboBoxCell;

                if (hTable.Contains(ecClass.Name))
                {
                    if (!string.IsNullOrEmpty(strUseStandPref) && strUseStandPref == "1")
                    {
                        string ret = ReadStandPref(ecClass.Name);
                        if (itemInstanceCell.Items.Contains(ret))
                        {
                            itemInstanceCell.Value = ret;
                            continue;
                        }
                    }
                    if (itemInstanceCell.Items.Contains(hTable[ecClass.Name]))
                    {
                        itemInstanceCell.Value = hTable[ecClass.Name];
                    }
                    else
                    {
                        string ret = ReadStandPref(ecClass.Name);
                        if (itemInstanceCell.Items.Contains(ret))
                        {
                            itemInstanceCell.Value = ret;
                        }
                        else
                        {
                            itemInstanceCell.Value = LocalizableStrings.None;
                            status = false;
                        }
                    }
                }
                else
                {
                    string ret = ReadStandPref(ecClass.Name);

                    if (itemInstanceCell.Items.Contains(ret))
                    {
                        itemInstanceCell.Value = ret;
                    }
                    else
                    {
                        itemInstanceCell.Value = LocalizableStrings.None;
                        status = false;
                    }
                }
            }
            return(status);
        }
            /*------------------------------------------------------------------------------------**/
            /// <summary>
            /// IsImportFileValidFormat
            /// </summary>
            /// <param name="fileName"></param>
            /// <param name="ecClass"></param>
            /// <returns></returns>
            /*--------------+---------------+---------------+---------------+---------------+------*/
            private static bool IsImportFileValidFormat
            (
                string fileName,
                IECClass ecClass
            )
            {
                bool status           = true;
                bool assoicationFound = false;
                bool instanceFound    = false;
                int  lineNumber       = 0;

                ArrayList arr = SchemaUtilities.GetAssociatedItems(ecClass);
                bool      lookForAssociations = (arr.Count > 1);

                System.IO.StreamReader sr = System.IO.File.OpenText(fileName);

                try
                {
                    while (!sr.EndOfStream)
                    {
                        string lineRead = sr.ReadLine().Trim();
                        lineNumber++;

                        if (string.IsNullOrEmpty(lineRead))
                        {
                            continue;
                        }

                        string testString = lineRead.Replace("[Associations]", "|");
                        testString = testString.Replace("[InstanceData]", "|");
                        testString = testString.Replace("=", "|");

                        if (!testString.Contains("|"))
                        {
                            WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.InvalidString, lineRead, lineNumber), "");
                            status = false;
                            break;
                        }

                        else if (lineRead == "[Associations]" && !lookForAssociations)
                        {
                            WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.NoAssociationRequired, lineNumber), "");
                            status = false;
                            break;
                        }

                        else if (lineRead == "[InstanceData]" && lookForAssociations && !assoicationFound)
                        {
                            WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.AssociationsNotDefined, ecClass.Name, lineNumber), "");
                            status = false;
                            break;
                        }

                        //Validate Associations
                        if (lineRead == "[Associations]")
                        {
                            while (!sr.EndOfStream)
                            {
                                lineRead = sr.ReadLine().Trim();
                                lineNumber++;
                                if (string.IsNullOrEmpty(lineRead))
                                {
                                    continue;
                                }

                                if (lineRead == "[InstanceData]")
                                {
                                    break;
                                }

                                string[] strs            = lineRead.Split(new char[] { '=' });
                                IECClass ecAssocateClass = SchemaUtilities.PlantSchema.GetClass(strs[0]);
                                if (ecAssocateClass == null)
                                {
                                    WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.InvalidAssociationClass, lineNumber), "");
                                    status = false;
                                    break;
                                }
                            }
                            assoicationFound = true;
                        }

                        if (status == false)
                        {
                            break;
                        }

                        //Validate Instance Data
                        if (lineRead == "[InstanceData]")
                        {
                            while (!sr.EndOfStream)
                            {
                                lineRead = sr.ReadLine().Trim();
                                lineNumber++;
                                if (lineRead == "[InstanceData]")
                                {
                                    break;
                                }

                                if (lineRead == "[Associations]")
                                {
                                    break;
                                }

                                if (string.IsNullOrEmpty(lineRead))
                                {
                                    continue;
                                }

                                string[]    strs   = lineRead.Split(new char[] { '=' });
                                IECProperty ecProp = ecClass[strs[0]];
                                if (ecProp == null)
                                {
                                    WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.InvalidPropertyName, lineNumber), "");
                                    status = false;
                                    break;
                                }
                            }
                            instanceFound = true;
                        }
                        if (status == false)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    sr.Close();
                }

                return(status && instanceFound);
            }
        public bool FillAssociatedItems(bool isModifyTool)
        {
            ArrayList classRelationshipStrs = SchemaUtilities.GetAssociatedItems(_ClassDef);

            if (classRelationshipStrs.Count == 0)
            {
                return(false);
            }

            if (_bMultiInst)
            {//when editing associations of multiple instances, edit and delete options should not be available.
                this.optionDelete.Visible = false;
                this.optionEdit.Visible   = false;

                //refresh/redraw the grid
                this.OnResize(new EventArgs());
            }

            for (int i = 0; i < classRelationshipStrs.Count; i++)
            {
                string   strData = classRelationshipStrs[i] as string;
                string[] strArr  = strData.Split(new char[] { '|' });

                IECClass ecAssociatedClass           = SchemaUtilities.PlantSchema.GetClass(strArr[0]);
                int      rowIndex                    = this.Rows.Add();
                DataGridViewTextBoxCell itemTypeCell = this[s_WBSClassKey, rowIndex] as DataGridViewTextBoxCell;
                itemTypeCell.Value = ecAssociatedClass.DisplayLabel;
                //itemTypeCell.Tag = ecAssociatedClass;

                DataGridViewComboBoxCell itemInstanceCell = this[s_WBSInstanceKey, rowIndex] as DataGridViewComboBoxCell;
                //ArrayList arr = DgnUtilities.GetInstance().GetECInstanceDisplayLabelsFromDgn (strArr[0]);
                ECInstanceList       arr             = DgnUtilities.GetInstance().GetAllInstancesFromDgn(strArr[0]);
                IECRelationshipClass ecAssociatedRel = SchemaUtilities.PlantSchema.GetClass(strArr[1]) as IECRelationshipClass;
                // move class to 1st column tag, to start with,  later changed

                itemInstanceCell.Tag = ecAssociatedClass;
                itemTypeCell.Tag     = ecAssociatedRel;

                if (_bMultiInst)
                {
                    itemInstanceCell.Items.Add(_cstr_Varies);
                }

                itemInstanceCell.Items.Add(LocalizableStrings.None);

                Dictionary <string, IECInstance> dropDownCache = new Dictionary <string, IECInstance> ();

                foreach (IECInstance returnedInstance in arr)
                //for (int j = 0; j < arr.Count; j++)
                {
                    // insert only if this is not from a referenced file
                    if (DgnUtilities.GetInstance().IsECInstanceFromReferenceFile(returnedInstance))
                    {
                        continue;
                    }

                    string key = SchemaUtilities.GetDisplayNameForECInstance(returnedInstance, true);
                    if (dropDownCache.ContainsKey(key))
                    {
                        dropDownCache[key] = returnedInstance;
                    }
                    else
                    {
                        // insert
                        dropDownCache.Add(key, returnedInstance);
                        itemInstanceCell.Items.Add(key);
                    }
                }
                if (dropDownCache.Count > 0)
                {
                    itemInstanceCell.Tag = dropDownCache;
                }

                if (isModifyTool)
                {
                    string strLastInstID = null;
                    string key           = "";
                    for (int j = 0; j < _instList.Count; j++)
                    {
                        IECInstance parentInstance = GetAssociatedItemFromInstance(_instList[j], ecAssociatedRel, ecAssociatedRel.Source.GetClasses()[0].Class);
                        string      strCurrInstID  = "";

                        // If we have a parent instance, then we must be using an existing instance. We need to make sure we select the existing values.
                        if (null != parentInstance)
                        {
                            key           = SchemaUtilities.GetDisplayNameForECInstance(parentInstance, true);
                            strCurrInstID = parentInstance.InstanceId;
                        }
                        else
                        {
                            key           = LocalizableStrings.None;
                            strCurrInstID = LocalizableStrings.None;
                        }

                        if (String.IsNullOrEmpty(strLastInstID))
                        {
                            strLastInstID = strCurrInstID;
                        }
                        else
                        {
                            if (strCurrInstID != strLastInstID)
                            {
                                key = _cstr_Varies;
                                break;
                            }
                        }
                    } // end for loop

                    itemInstanceCell.Value = key;
                }

                itemInstanceCell.Sorted = true;

                DataGridViewImageCell tempImageCell = this["optionAdd", rowIndex] as DataGridViewImageCell;
                tempImageCell.Tag = ecAssociatedClass;
            }

            if (!isModifyTool)
            {
                ArrayList AssociatonList = WorkspaceUtilities.GetSettings("Associations." + _ClassDef.Name);
                LoadSettings(AssociatonList, false);
            }

            return(true);
        }
            /*------------------------------------------------------------------------------------**/
            /// <summary>
            /// Import
            /// </summary>
            /// <param name="unparsed"></param>
            /*--------------+---------------+---------------+---------------+---------------+------*/
            public static void Import
            (
                string unparsed
            )
            {
                if (string.IsNullOrEmpty(unparsed))
                {
                    WorkspaceUtilities.DisplayErrorMessage(LocalizableStrings.BadImportCommand, LocalizableStrings.ImportCommandFormat);
                    return;
                }

                BMECApi.Instance.ClearActivePlacementTool();  // exit current placement tool
                IECClass ecClass = SchemaUtilities.PlantSchema.GetClass(unparsed.Trim());

                if (ecClass == null)
                {
                    WorkspaceUtilities.DisplayErrorMessage(string.Format(LocalizableStrings.BadClassName, unparsed.Trim()), "");
                    return;
                }

                BMECInstanceManager instanceManager = BMECApi.Instance.InstanceManager;

                OpenFileDialog openFileDlg = new OpenFileDialog();

                openFileDlg.Multiselect = false;
                openFileDlg.Filter      = "Import data file|*.txt";
                openFileDlg.ShowDialog();
                if (string.IsNullOrEmpty(openFileDlg.FileName))
                {
                    return;
                }

                if (!IsImportFileValidFormat(openFileDlg.FileName, ecClass))
                {
                    return;
                }

                System.IO.StreamReader sr = System.IO.File.OpenText(openFileDlg.FileName);

                ArrayList associations   = new ArrayList();
                ArrayList propertyValues = new ArrayList();


                WaitDialog wtDlg = new WaitDialog();

                wtDlg.SetTitleString(LocalizableStrings.ImportingInstances);
                wtDlg.SetInformationSting(LocalizableStrings.ImportingInstancesInfo);
                wtDlg.Show();

                string lineRead = sr.ReadLine().Trim();

                while (!sr.EndOfStream)
                {
                    Application.DoEvents();
                    if (string.IsNullOrEmpty(lineRead))
                    {
                        lineRead = sr.ReadLine().Trim();
                        continue;
                    }
                    if (lineRead == "[Associations]")
                    {
                        associations.Clear();
                        while (!sr.EndOfStream)
                        {
                            lineRead = sr.ReadLine().Trim();
                            if (string.IsNullOrEmpty(lineRead))
                            {
                                continue;
                            }

                            if (lineRead == "[InstanceData]")
                            {
                                break;
                            }

                            associations.Add(lineRead);
                        }
                    }

                    if (lineRead == "[InstanceData]")
                    {
                        propertyValues.Clear();
                        while (!sr.EndOfStream)
                        {
                            lineRead = sr.ReadLine().Trim();
                            if (lineRead == "[InstanceData]")
                            {
                                break;
                            }

                            if (lineRead == "[Associations]")
                            {
                                break;
                            }

                            if (string.IsNullOrEmpty(lineRead))
                            {
                                continue;
                            }

                            propertyValues.Add(lineRead);
                        }

                        IECInstance ecInstance = instanceManager.CreateECInstance(ecClass.Name);
                        BMECApi.Instance.SpecProcessor.FillCurrentPreferences(ecInstance, true);
                        ecInstance.InstanceId = "mechanical";
                        ECInstanceDialog ecDlg = new ECInstanceDialog(ecInstance);
                        ecDlg.InitializeWithCustomProperties(associations, propertyValues, true);
                        ecDlg.SaveData();
                    }
                }
                wtDlg.Close();
                sr.Close();
            }
Ejemplo n.º 21
0
        public NodeUpdateResult PlaceParametricCell
        (
            NodeUpdateContext updateContext,
            [Replicatable, DgnModelProvider] IPoint PlacementPoint,
            [Replicatable] IPlane PlacementPlane,
            [In] string CellLibraryPath,
            [In] string CellDefinitionName,
            [In] string CellVariation,
            [Replicatable(-1, true)] string[] CellVariableNames,
            [Replicatable(-1, true)] string[] CellVariableValues
        )
        {
            this.ClearAndErase(updateContext); // Remove old feature
            
            if (this.ReplicationIndex == 0 && CellLibraryPath == null || CellDefinitionName == null)
            {
                return new NodeUpdateResult.IncompleteInputs(CellLibraryPath, CellDefinitionName);
            }
            else
            {
                //NEED TO IMPLEMENT A SHARED CELL UPDATE IF UpdateSharedCell == true; THEN ONCE UPDATED SET THE PARAMETER TO FALSE SO THAT THE NEXT PLACED CELL DOESN'T UPDATE THE SHARED CELL AGAIN
                //Check if cell library is attached and if not attach it
                if (this.ReplicationIndex == 0 && MSApp.IsCellLibraryAttached == false || MSApp.AttachedCellLibrary.FullName != CellLibraryPath)
                {
                    MSApp.AttachCellLibrary(CellLibraryPath);
                }
                
                DgnFile activeDgnFile = Session.Instance.GetActiveDgnFile();
                DgnModel activeModel = Session.Instance.GetActiveDgnModel();
                DgnModel cellModel = null;
                ParametricCellElement pCell = null;

                ParametricCellDefinitionElement cellDef = ParametricCellDefinitionElement.FindByName(CellDefinitionName, activeDgnFile);

                if (cellDef == null) //cell not in active file, load from attached cell library
                {
                    var opts = CellLibraryOptions.Include3d | CellLibraryOptions.IncludeAllLibraries | CellLibraryOptions.IncludeParametric;
                    var libs = new CellLibraryCollection(opts);

                    foreach (var lib in libs)
                    {
                        if (CellDefinitionName.Equals(lib.Name))
                        {
                            StatusInt status;
                            cellModel = lib.File.LoadRootModelById(out status, lib.File.FindModelIdByName(lib.Name), true, false, true);
                            break;
                        }
                    }

                    if (null == cellModel) //Cell definition (model) doesn't exist in the cell model file
                    {
                        LsBuilder lsBuilder = new LsBuilder();
                        Ls ls = lsBuilder.AppendLineLiteral("Error loading cell definition. Check cell definition name and library are correct.").ToLs();
                        return new NodeUpdateResult.TechniqueFailureMessage(ls);
                    }
                    else
                    {
                        var hdlr = DgnComponentDefinitionHandler.GetForModel(cellModel);
                        var status = hdlr.DefinitionModelHandler.CreateCellDefinition(activeDgnFile);

                        if (ParameterStatus.Success == status)
                            cellDef = ParametricCellDefinitionElement.FindByName(CellDefinitionName, activeDgnFile);
                        else
                        {
                            LsBuilder lsBuilder = new LsBuilder();
                            Ls ls = lsBuilder.AppendLineLiteral("Error creating cell definition in active file.").ToLs();
                            return new NodeUpdateResult.TechniqueFailureMessage(ls);
                        }
                    }
                }
                

                try
                {
                    pCell = ParametricCellElement.Create(cellDef, CellVariation, activeModel);

                    //Cell origin point - adjusted for U.O.R.
                    double uor = MSApp.ActiveModelReference.UORsPerMasterUnit;
                    DPoint3d cellOrigin = DPoint3d.Multiply(uor, PlacementPoint.GetDPoint3d());
                    pCell.Origin = cellOrigin;

                    DTransform3d dTransform3D = PlacementPlane.GetDTransform3d();
                    DPlane3d dPlane3D = PlacementPlane.GetDPlane3d();

                    DMatrix3d dMatrix3D = new DMatrix3d(dTransform3D);

                    pCell.Rotation = dMatrix3D;

                    //pCell.IsInvisible = true; //We don't want multiple elements visible
                    pCell.AddToModel(); //Add to the model so we can assign variables and retrieve the element

                    //Assign custom variables if they exist
                    if (CellVariableNames != null && CellVariableValues != null)
                    {
                        IECClass ecClass = pCell.Parameters.ClassDefinition;
                        IDgnECInstance eci = DgnECManager.FindECInstanceOnElement(pCell, ecClass);

                        for (int i = 0; i < CellVariableNames.Length; ++i)
                        {                            
                            IEnumerator<IECPropertyValue> props = eci.GetEnumerator(false, true);
                            
                            while (props.MoveNext())
                            {
                                if (props.Current.Property.DisplayLabel == CellVariableNames[i].ToString())
                                {
                                    props.Current.StringValue = CellVariableValues[i].ToString();
                                }
                            }
                        }
                        eci.WriteChanges();
                    }
                    
                    IElement ele = MSApp.ActiveModelReference.GetLastValidGraphicalElement();

                    SetElement(ele); //Commit as a GC feature
                    pCell.Dispose(); //Clean up the memory of pCell, only 'ele' will be retained
                }
                catch (Exception ex)
                {
                    return new NodeUpdateResult.TechniqueException(ex);
                }

                return NodeUpdateResult.Success;
            }
        }