Пример #1
0
        /// <summary>
        /// Gets the index of the display field for the feature's layer, if it is on the map
        /// </summary>
        /// <param name="feature">IFeature to look for</param>
        /// <returns>int</returns>
        //public int GetDisplayIndex(ESRI.ArcGIS.Geodatabase.IFeature feature)
        //{
        //    if (null == feature)
        //    {
        //        throw new ArgumentNullException("feature");
        //    }
        //    else if (null == feature.Class)
        //    {
        //        throw new InvalidOperationException("feature.Class cannot be null");
        //    }

        //    int result = -1;

        //    int key = feature.Class.ObjectClassID;

        //    if (_displayIndices.ContainsKey(key))
        //    {
        //        result = _displayIndices[key];
        //    }
        //    else
        //    {
        //        ESRI.ArcGIS.Geodatabase.IDataset dataset = feature.Class as ESRI.ArcGIS.Geodatabase.IDataset;
        //        if (null != dataset)
        //        {
        //            string className = GdbUtils.ParseTableName(dataset);
        //            ESRI.ArcGIS.Carto.IFeatureLayer ftLayer = this.FindFeatureLayer(className);
        //            if (null != ftLayer)
        //            {
        //                result = feature.Fields.FindField(ftLayer.DisplayField);
        //            }
        //        }

        //        _displayIndices[key] = result;  // Putting it here means that we may store -1 even if the layer was undiscoverable
        //                                        // even one time...we could move it into where result is assigned if we wanted
        //                                        // it to recheck every time this is called
        //    }

        //    return result;
        //}

        /// <summary>
        /// Creates a new Progress Dialog in the hook, with a given ITrackCancel
        /// </summary>
        /// <param name="trackCancel">Tracks cancel</param>
        /// <param name="message">The message</param>
        /// <param name="min">Minimum progress</param>
        /// <param name="max">Maximum progress</param>
        /// <param name="step">Progress per step</param>
        /// <param name="desc">Description</param>
        /// <param name="title">Title</param>
        /// <returns>IProgressDialog2</returns>
        public ESRI.ArcGIS.Framework.IProgressDialog2 CreateProgressDialog(ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel, string message, int min, int max, int step, string desc, string title)
        {
            int?hWnd = this.hWnd;

            if (null == hWnd)
            {
                throw new InvalidOperationException("Unable to determine hWnd of Hook");
            }

            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

            // Set the properties of the Step Progressor
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, (int)hWnd);
            stepProgressor.MinRange  = min;
            stepProgressor.MaxRange  = max;
            stepProgressor.StepValue = step;
            stepProgressor.Message   = message;

            // Create the ProgressDialog. This automatically displays the dialog
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

            // Set the properties of the ProgressDialog
            progressDialog.CancelEnabled = true;
            progressDialog.Description   = desc;
            progressDialog.Title         = title;
            progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;

            return(progressDialog);
        }
Пример #2
0
        private bool RemoveFiberCableConfigDomains(IWorkspace wksp)
        {
            bool result = true;

            if (wksp == null || ((wksp as IWorkspaceDomains3) == null))
            {
                return(false);
            }

            try
            {
                // get Handles to everything we need first or bail.
                IFeatureClass cableFc = FindFeatureClass(ConfigUtil.FiberCableFtClassName);
                if (cableFc == null)
                {
                    return(false);
                }
                ISubtypes subs = cableFc as ISubtypes;
                if (subs == null)
                {
                    return(false);
                }
                IClassSchemaEdit4 schEdit = cableFc as IClassSchemaEdit4;
                if (schEdit == null)
                {
                    return(false);
                }

                // ----------------------------------------------------
                // First we have to unassign the domains from the FC fields
                // ----------------------------------------------------
                schEdit.AlterDomain(ConfigUtil.NumberOfFibersFieldName, null);
                schEdit.AlterDomain(ConfigUtil.NumberOfBuffersFieldName, null);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Unassigned FiberCable domains", "NumberOfFibers + NumberOfBuffers");

                // ----------------------------------------------------
                // Also have to remove domain from the subtypes (arghh)
                // 1 & 2 are overhead and underground.
                // ----------------------------------------------------
                IEnumSubtype types = subs.Subtypes;
                subs.set_Domain(1, ConfigUtil.NumberOfFibersFieldName, null);
                subs.set_Domain(2, ConfigUtil.NumberOfFibersFieldName, null);
                subs.set_Domain(1, ConfigUtil.NumberOfBuffersFieldName, null);
                subs.set_Domain(2, ConfigUtil.NumberOfBuffersFieldName, null);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Removed FiberCable subtype domains", "NumberOfFibers + NumberOfBuffers");

                // ----------------------------------------------------
                // Now we can remove the domains
                // ----------------------------------------------------
                IWorkspaceDomains3 wkspDomains = wksp as IWorkspaceDomains3;
                if (wkspDomains.get_CanDeleteDomain("NumberOfFibers") &&
                    wkspDomains.get_CanDeleteDomain("NumberOfBuffers"))
                {
                    wkspDomains.DeleteDomain("NumberOfFibers");
                    wkspDomains.DeleteDomain("NumberOfBuffers");
                    MessageBox.Show("Domains successfully deleted");
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Domains successfully deleted", "NumberOfFibers + NumberOfBuffers");
                }
                else
                {
                    MessageBox.Show("Upgrade failed. \nCould not get exclusive access to this database. \nPLEASE RESTORE FROM YOUR BACKUP");
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Cannot delete domains.", "Non-Exclusive access?");
                    return(false);
                }

                // ----------------------------------------------------
                // Recalculate the fields based on the count of actual
                // related objects found. We'll use this code later
                // for integrity checking.
                // ----------------------------------------------------
                IRelationshipClass bufferRelationship = GdbUtils.GetRelationshipClass(cableFc, ConfigUtil.FiberCableToBufferRelClassName);
                IRelationshipClass strandRelationship = GdbUtils.GetRelationshipClass(cableFc, ConfigUtil.FiberCableToFiberRelClassName);
                IFeature           ft;
                int bufferIdx = cableFc.Fields.FindField(ConfigUtil.NumberOfBuffersFieldName);
                int strandIdx = cableFc.Fields.FindField(ConfigUtil.NumberOfFibersFieldName);
                if (bufferIdx == -1 || strandIdx == -1)
                {
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Cannot find buffer or strand fields.",
                                           ConfigUtil.NumberOfBuffersFieldName + " " + ConfigUtil.NumberOfFibersFieldName);
                    MessageBox.Show("Upgrade failed. \nCould not find appropriate fields based on current config settings. \nPLEASE RESTORE FROM YOUR BACKUP.");
                    return(false);
                }
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Recalculating buffer and strand counts...");
                // Start edit session do the updates....
                ArcMap.Editor.StartEditing(wksp);
                IFeatureCursor cables = cableFc.Update(null, false);
                int            count  = cableFc.FeatureCount(null);

                //ProgressBar
                ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, ArcMap.Application.hWnd);
                stepProgressor.MinRange  = 1;
                stepProgressor.MaxRange  = count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = "Updating cable config for " + count + " cables";

                // Create the ProgressDialog. This automatically displays the dialog
                ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = false;
                progressDialog.Description   = "";
                progressDialog.Title         = "Workspace Upgrade";
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                int i = 1;
                while ((ft = cables.NextFeature()) != null)
                {
                    progressDialog.Description = string.Format("Updating cable {0} of {1}", i, count);
                    stepProgressor.Step();

                    ISet buffers = bufferRelationship.GetObjectsRelatedToObject(ft);
                    ft.set_Value(bufferIdx, buffers.Count);
                    ISet strands = strandRelationship.GetObjectsRelatedToObject(ft);
                    ft.set_Value(strandIdx, strands.Count);
                    ft.Store();
                    i++;
                }
                progressDialog.HideDialog();
                ArcMap.Editor.StopEditing(true);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Upgrade Completed Successfully.");
                MessageBox.Show("Upgrade Completed Successfully.");
            }
            catch (Exception e)
            {
                _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "RemoveFiberCableConfigDomains", e.Message);
                result = false;
            }
            return(result);
        }
        /*
         * private String fiberOrBufferColorLookup(int number)
         * {
         *  switch (number)
         *  {
         *      case 1:
         *          return "Blue";
         *      case 2:
         *          return "Orange";
         *      case 3:
         *          return "Green";
         *      case 4:
         *          return "Brown";
         *      case 5:
         *          return "Slate";
         *      case 6:
         *          return "White";
         *      case 7:
         *          return "Red";
         *      case 8:
         *          return "Black";
         *      case 9:
         *          return "Yellow";
         *      case 10:
         *          return "Violet";
         *      case 11:
         *          return "Rose";
         *      case 12:
         *          return "Aqua";
         *      default:
         *          return string.Empty;
         *  }
         * }
         */

        /// <summary>
        /// Generates a number of buffer tubes and fiber records for a fiber cable, given a configuration.
        /// </summary>
        /// <param name="feature">IFeature to generate for</param>
        /// <param name="configuration">Specification of buffer and fiber counts</param>
        /// <param name="progressDialog">Progress dialog for user notification</param>
        /// <param name="trackCancel">TrackCancel used in the progress dialog</param>
        /// <returns>Success</returns>
        private bool GenerateUnits(ESRI.ArcGIS.Geodatabase.IFeature feature, FiberCableConfiguration configuration, ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog, ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel)
        {
            bool isComplete  = false;
            bool isCancelled = false;
            Guid g;

            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog;
            ESRI.ArcGIS.Geodatabase.IObjectClass   ftClass        = feature.Class;

            using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser())
            {
                ESRI.ArcGIS.Geodatabase.IRelationshipClass cableHasBuffer = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.FiberCableToBufferRelClassName);
                releaser.ManageLifetime(cableHasBuffer);
                ESRI.ArcGIS.Geodatabase.IRelationshipClass cableHasFiber = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.FiberCableToFiberRelClassName);
                releaser.ManageLifetime(cableHasFiber);
                ESRI.ArcGIS.Geodatabase.IRelationshipClass bufferHasFiber = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.BufferToFiberRelClassName);
                releaser.ManageLifetime(bufferHasFiber);

                ESRI.ArcGIS.Geodatabase.ITable bufferTable = cableHasBuffer.DestinationClass as ESRI.ArcGIS.Geodatabase.ITable;
                ESRI.ArcGIS.Geodatabase.ITable fiberTable  = cableHasFiber.DestinationClass as ESRI.ArcGIS.Geodatabase.ITable;

                // Fields to populate on buffer
                int    bufferIpidIdx      = bufferTable.Fields.FindField(ConfigUtil.IpidFieldName);
                int    fiberCountIdx      = bufferTable.Fields.FindField(ConfigUtil.NumberOfFibersFieldName);
                int    bufferToCableIdx   = bufferTable.Fields.FindField(cableHasBuffer.OriginForeignKey);
                object bufferToCableValue = feature.get_Value(feature.Fields.FindField(cableHasBuffer.OriginPrimaryKey));

                // Fields to populate on fiber
                int    fiberIpidIdx          = fiberTable.Fields.FindField(ConfigUtil.IpidFieldName);
                int    fiberNumberIdx        = fiberTable.Fields.FindField(ConfigUtil.Fiber_NumberFieldName);
                int    fiberColorIdx         = fiberTable.Fields.FindField(ConfigUtil.Fiber_ColorFieldName);
                int    fiberToCableIdx       = fiberTable.Fields.FindField(cableHasFiber.OriginForeignKey);
                object fiberToCableValue     = feature.get_Value(feature.Fields.FindField(cableHasFiber.OriginPrimaryKey));
                int    fiberToBufferIdx      = fiberTable.Fields.FindField(bufferHasFiber.OriginForeignKey);
                int    fiberToBufferValueIdx = bufferTable.Fields.FindField(bufferHasFiber.OriginPrimaryKey);

                // Research using InsertCursor for speed.
                int fiberNumber = 0;
                for (int bufferIdx = 1; bufferIdx <= configuration.BufferCount; bufferIdx++)
                {
                    g = Guid.NewGuid();
                    string bufferId = g.ToString("B").ToUpper();

                    ESRI.ArcGIS.Geodatabase.IRow row = bufferTable.CreateRow();
                    releaser.ManageLifetime(row);

                    row.set_Value(bufferIpidIdx, bufferId);
                    row.set_Value(fiberCountIdx, configuration.FibersPerTube);
                    row.set_Value(bufferToCableIdx, bufferToCableValue);
                    row.Store();

                    object fiberToBufferValue = row.get_Value(fiberToBufferValueIdx);

                    // Research using InsertCursor for speed.
                    for (int fiberIdx = 1; fiberIdx <= configuration.FibersPerTube; fiberIdx++)
                    {
                        fiberNumber++;
                        progressDialog.Description = string.Format("Creating fiber {0} of {1}", fiberNumber, configuration.TotalFiberCount);
                        stepProgressor.Step();

                        g = Guid.NewGuid();
                        ESRI.ArcGIS.Geodatabase.IRow fiberRow = fiberTable.CreateRow();
                        releaser.ManageLifetime(fiberRow);


                        fiberRow.set_Value(fiberIpidIdx, g.ToString("B").ToUpper());
                        fiberRow.set_Value(fiberNumberIdx, fiberNumber);

                        // Dangerous if coded values are altered but while
                        // domain type is int Rather than string coded, this
                        // is quickest way to add this
                        // Dont do for fiber groupings of more than 12
                        if (configuration.FibersPerTube <= 12)
                        {
                            fiberRow.set_Value(fiberColorIdx, fiberIdx);
                        }

                        fiberRow.set_Value(fiberToBufferIdx, fiberToBufferValue);
                        fiberRow.set_Value(fiberToCableIdx, fiberToCableValue);

                        fiberRow.Store();

                        if (!trackCancel.Continue())
                        {
                            isCancelled = true;
                            break;
                        }
                    }

                    if (!trackCancel.Continue())
                    {
                        isCancelled = true;
                        break;
                    }
                }

                if (!isCancelled)
                {
                    isComplete = true;
                }
            }

            return(isComplete);
        }
        /// <summary>
        /// Sets the buffer tube and strand counts based on the given configuration. If IPID and/or CABLEID are null, it also
        /// takes care of them
        /// </summary>
        /// <param name="feature">The FiberCable feature to configure</param>
        /// <param name="configuration">The tube/strand counts</param>
        /// <param name="isExistingOperation">Flag to control whether this method is being called from within an existing
        /// edit operation</param>
        /// <returns>Success</returns>
        protected bool ConfigureCable(ESRI.ArcGIS.Geodatabase.IFeature feature, FiberCableConfiguration configuration, bool isExistingOperation)
        {
            bool isComplete         = false;
            bool isOurOperationOpen = false;

            // The following assignments are defaults for the case where they are not already populated on the feature
            string fiberCableIpid = Guid.NewGuid().ToString("B").ToUpper();

            // The following will be set during Validation
            ESRI.ArcGIS.Geodatabase.IObjectClass ftClass = null;
            ESRI.ArcGIS.Geodatabase.IFields      fields  = null;
            int ipidIdx        = -1;
            int bufferCountIdx = -1;
            int strandCountIdx = -1;

            #region Validation

            if (null == feature)
            {
                throw new ArgumentNullException("feature");
            }

            if (null == configuration)
            {
                throw new ArgumentNullException("configuration");
            }

            if (_editor.EditState == ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing)
            {
                throw new InvalidOperationException("You must be editing the workspace to perform this operation.");
            }

            ftClass = feature.Class;
            fields  = ftClass.Fields;

            string missingFieldFormat = "Field {0} is missing.";

            ipidIdx = fields.FindField(ConfigUtil.IpidFieldName);
            if (-1 == ipidIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.IpidFieldName));
            }

            bufferCountIdx = fields.FindField(ConfigUtil.NumberOfBuffersFieldName);
            if (-1 == bufferCountIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.NumberOfBuffersFieldName));
            }

            strandCountIdx = fields.FindField(ConfigUtil.NumberOfFibersFieldName);
            if (-1 == strandCountIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.NumberOfFibersFieldName));
            }

            #endregion


            ESRI.ArcGIS.esriSystem.ITrackCancel    trackCancel    = new ESRI.ArcGIS.Display.CancelTrackerClass();
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = _hookHelper.CreateProgressDialog(trackCancel, "Preparing to configure cable...", 1, configuration.TotalFiberCount, 1, "Starting edit operation...", "Fiber Configuration");
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog;

            progressDialog.ShowDialog();
            stepProgressor.Step();

            if (!isExistingOperation)
            {
                _editor.StartOperation();
                isOurOperationOpen = true;
            }

            try
            {
                if (DBNull.Value == feature.get_Value(ipidIdx))
                {
                    feature.set_Value(ipidIdx, fiberCableIpid);
                }
                else
                {
                    fiberCableIpid = feature.get_Value(ipidIdx).ToString();
                }

                feature.set_Value(bufferCountIdx, configuration.BufferCount);
                feature.set_Value(strandCountIdx, configuration.FibersPerTube);

                isComplete = GenerateUnits(feature, configuration, progressDialog, trackCancel);

                progressDialog.Description = "Completing configuration...";
                stepProgressor.Step();

                if (isOurOperationOpen)
                {
                    if (isComplete)
                    {
                        feature.Store();
                        _editor.StopOperation("Configure Fiber");
                    }
                    else
                    {
                        _editor.AbortOperation();
                    }
                }
            }
            catch (Exception e)
            {
                if (isOurOperationOpen)
                {
                    _editor.AbortOperation();
                }
            }

            progressDialog.HideDialog();
            return(isComplete);
        }
        /// <summary>
        /// Delete the ports for a given device
        /// </summary>
        /// <param name="device">The device feature</param>
        /// <returns>True if completed</returns>
        private bool DeletePorts(ESRI.ArcGIS.Geodatabase.IFeature device, int highInputPort, int highOutputPort, ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog, ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel)
        {
            bool isCancelled = false;

            ESRI.ArcGIS.esriSystem.IStepProgressor     stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog;
            ESRI.ArcGIS.Geodatabase.IRelationshipClass deviceHasPorts = ConfigUtil.GetPortRelationship((ESRI.ArcGIS.Geodatabase.IFeatureClass)device.Class);

            if (null != deviceHasPorts)
            {
                using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser())
                {
                    ESRI.ArcGIS.Geodatabase.ITable portTable = (ESRI.ArcGIS.Geodatabase.ITable)deviceHasPorts.DestinationClass;
                    releaser.ManageLifetime(portTable);

                    ESRI.ArcGIS.Geodatabase.IQueryFilter filter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass();
                    releaser.ManageLifetime(filter);

                    filter.WhereClause = string.Format("{0}='{1}' AND {2} > {3} AND {4}='{5}'",
                                                       deviceHasPorts.OriginForeignKey,
                                                       device.get_Value(device.Fields.FindField(deviceHasPorts.OriginPrimaryKey)),
                                                       ConfigUtil.PortIdFieldName,
                                                       highInputPort,
                                                       ConfigUtil.PortTypeFieldName,
                                                       1);

                    stepProgressor.Message = "Deleting higher input ports...";
                    int deletedPorts = portTable.RowCount(filter);

                    portTable.DeleteSearchedRows(filter);
                    for (int i = 0; i < deletedPorts; i++)
                    {
                        stepProgressor.Step();
                    }

                    filter.WhereClause = string.Format("{0}='{1}' AND {2} > {3} AND {4}='{5}'",
                                                       deviceHasPorts.OriginForeignKey,
                                                       device.get_Value(device.Fields.FindField(deviceHasPorts.OriginPrimaryKey)),
                                                       ConfigUtil.PortIdFieldName,
                                                       highOutputPort,
                                                       ConfigUtil.PortTypeFieldName,
                                                       2);

                    stepProgressor.Message = "Deleting higher output ports...";
                    deletedPorts           = portTable.RowCount(filter);

                    portTable.DeleteSearchedRows(filter);
                    for (int i = 0; i < deletedPorts; i++)
                    {
                        stepProgressor.Step();
                    }
                }
            }

            return(!isCancelled);
        }
        /// <summary>
        /// Generate the ports for a given device
        /// </summary>
        /// <param name="device">The device feature</param>
        /// <returns>True if completed</returns>
        private bool GeneratePorts(ESRI.ArcGIS.Geodatabase.IFeature device, int lowInputPort, int inputPortCount, int lowOutputPort, int outputPortCount, ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog, ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel)
        {
            bool isCancelled = false;

            ESRI.ArcGIS.esriSystem.IStepProgressor     stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog;
            ESRI.ArcGIS.Geodatabase.IRelationshipClass deviceHasPorts = ConfigUtil.GetPortRelationship((ESRI.ArcGIS.Geodatabase.IFeatureClass)device.Class);
            Guid g;

            if (null != deviceHasPorts)
            {
                using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser())
                {
                    ESRI.ArcGIS.Geodatabase.ITable portTable = (ESRI.ArcGIS.Geodatabase.ITable)deviceHasPorts.DestinationClass;
                    releaser.ManageLifetime(portTable);

                    // Fields to populate on port
                    int portIpidIdx   = portTable.Fields.FindField(ConfigUtil.IpidFieldName);
                    int portNumberIdx = portTable.Fields.FindField(ConfigUtil.PortIdFieldName);
                    int portTypeIdx   = portTable.Fields.FindField(ConfigUtil.PortTypeFieldName);
                    int fkeyIdx       = portTable.Fields.FindField(deviceHasPorts.OriginForeignKey);

                    object originPrimaryKey = device.get_Value(device.Fields.FindField(deviceHasPorts.OriginPrimaryKey));

                    for (int portIdx = lowInputPort; portIdx <= inputPortCount; portIdx++)
                    {
                        stepProgressor.Message = string.Format("Creating input port {0} of {1}", portIdx, inputPortCount);
                        stepProgressor.Step();

                        g = Guid.NewGuid();
                        string portIpid = g.ToString("B").ToUpper();

                        ESRI.ArcGIS.Geodatabase.IRow portRow = portTable.CreateRow();
                        releaser.ManageLifetime(portRow);

                        portRow.set_Value(portIpidIdx, portIpid);
                        portRow.set_Value(portTypeIdx, PortType.Input);
                        portRow.set_Value(portNumberIdx, portIdx);
                        portRow.set_Value(fkeyIdx, originPrimaryKey);

                        portRow.Store();

                        if (!trackCancel.Continue())
                        {
                            isCancelled = true;
                            break;
                        }
                    }

                    if (trackCancel.Continue())
                    {
                        for (int portIdx = lowOutputPort; portIdx <= outputPortCount; portIdx++)
                        {
                            stepProgressor.Message = string.Format("Creating output port {0} of {1}", portIdx, outputPortCount);
                            stepProgressor.Step();

                            g = Guid.NewGuid();
                            string portIpid = g.ToString("B").ToUpper();

                            ESRI.ArcGIS.Geodatabase.IRow portRow = portTable.CreateRow();
                            releaser.ManageLifetime(portRow);

                            portRow.set_Value(portIpidIdx, portIpid);
                            portRow.set_Value(portTypeIdx, PortType.Output);
                            portRow.set_Value(portNumberIdx, portIdx);
                            portRow.set_Value(fkeyIdx, originPrimaryKey);

                            portRow.Store();

                            if (!trackCancel.Continue())
                            {
                                isCancelled = true;
                                break;
                            }
                        }
                    }
                }
            }

            return(!isCancelled);
        }
        /// <summary>
        /// Sets the input and output ports based on the given configuration. If IPID and/or CABLEID are null, it also
        /// takes care of them
        /// </summary>
        /// <param name="feature">The device feature to configure</param>
        /// <param name="inputPorts">Number of input ports</param>
        /// <param name="outputPorts">Number of output ports</param>
        /// <param name="isExistingOperation">Flag to control whether this method is being called from within an existing
        /// edit operation -- the default behavior is "false" in which case it adds an operation of its own</param>
        /// <returns>True if the configuration is complete</returns>
        public bool ConfigureDevice(ESRI.ArcGIS.Geodatabase.IFeature feature, int inputPorts, int outputPorts, bool isExistingOperation)
        {
            bool   isComplete         = false;
            bool   isOurOperationOpen = false;
            string deviceIpid         = string.Empty;

            #region Validation

            string missingFieldFormat = "Field {0} is missing.";

            // The following will be set during Validation
            ESRI.ArcGIS.Geodatabase.IObjectClass ftClass = null;
            ESRI.ArcGIS.Geodatabase.IFields      fields  = null;

            ftClass = feature.Class;
            fields  = ftClass.Fields;

            if (null == feature)
            {
                throw new ArgumentNullException("feature");
            }

            if (_editor.EditState == ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing)
            {
                throw new InvalidOperationException("You must be editing the workspace to perform this operation.");
            }

            if (0 > inputPorts)
            {
                throw new ArgumentOutOfRangeException("inputPorts");
            }

            if (0 > outputPorts)
            {
                throw new ArgumentOutOfRangeException("outputPorts");
            }

            int ipidIdx = fields.FindField(ConfigUtil.IpidFieldName);
            if (-1 == ipidIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.IpidFieldName));
            }

            int inPortsIdx = fields.FindField(ConfigUtil.InputPortsFieldName);
            if (-1 == inPortsIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.InputPortsFieldName));
            }

            int outPortsIdx = fields.FindField(ConfigUtil.OutputPortsFieldName);
            if (-1 == outPortsIdx)
            {
                throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.OutputPortsFieldName));
            }

            #endregion

            // Are we RE-configuring?
            //            int? oldInputPorts = GdbUtils.GetDomainedIntName(feature, ConfigUtil.InputPortsFieldName);
            //            int? oldOutputPorts = GdbUtils.GetDomainedIntName(feature, ConfigUtil.OutputPortsFieldName);

            //            int inputPortDifference = oldInputPorts.HasValue ? Math.Abs(inputPorts - oldInputPorts.Value) : inputPorts;
            //            int outputPortDifference = oldOutputPorts.HasValue ? Math.Abs(outputPorts - oldOutputPorts.Value) : outputPorts;

            ESRI.ArcGIS.esriSystem.ITrackCancel    trackCancel    = new ESRI.ArcGIS.Display.CancelTrackerClass();
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = _hookHelper.CreateProgressDialog(trackCancel, "Configuring device...", 1, inputPorts + outputPorts, 1, "Starting edit operation...", "Device Configuration");
            //            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = CreateProgressDialog(trackCancel, "Configuring device...", 1, inputPortDifference + outputPortDifference + 2, 1, "Starting edit operation...", "Device Configuration");
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog;

            progressDialog.ShowDialog();
            stepProgressor.Step();

            if (!isExistingOperation)
            {
                try
                {
                    _editor.StartOperation();
                    isOurOperationOpen = true;
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to start edit operation.", ex);
                }
            }

            try
            {
                feature.set_Value(inPortsIdx, inputPorts);
                feature.set_Value(outPortsIdx, outputPorts);

                if (DBNull.Value == feature.get_Value(ipidIdx))
                {
                    Guid g = Guid.NewGuid();
                    deviceIpid = g.ToString("B").ToUpper();
                    feature.set_Value(ipidIdx, deviceIpid);
                }
                else
                {
                    deviceIpid = feature.get_Value(ipidIdx).ToString();
                }

                //                if (!oldOutputPorts.HasValue && !oldInputPorts.HasValue)
                //                {
                isComplete = GeneratePorts(feature, 1, inputPorts, 1, outputPorts, progressDialog, trackCancel);
                //                }
                //                else
                //                {
                //                    bool additionsComplete = false;
                //                    bool deletionsComplete = false;
                //
                //                    additionsComplete = GeneratePorts(feature, oldInputPorts.Value + 1, oldInputPorts.Value + inputPortDifference, oldOutputPorts.Value + 1, oldOutputPorts.Value + outputPortDifference, progressDialog, trackCancel);
                //                    deletionsComplete = DeletePorts(feature, inputPorts, outputPorts, progressDialog, trackCancel);
                //
                //                    isComplete = additionsComplete && deletionsComplete;
                //                }

                if (isComplete)
                {
                    stepProgressor.Message = "Finishing configuration...";
                    stepProgressor.Step();

                    if (isOurOperationOpen)
                    {
                        feature.Store();
                        _editor.StopOperation("Configure Device");
                    }
                }
                else
                {
                    stepProgressor.Message = "Cancelling configuration...";
                    stepProgressor.Step();

                    if (isOurOperationOpen)
                    {
                        _editor.AbortOperation();
                    }
                }
            }
            catch
            {
                if (isOurOperationOpen)
                {
                    _editor.AbortOperation();
                }
            }

            if (null != progressDialog)
            {
                progressDialog.HideDialog();
            }

            return(isComplete);
        }