public static string AddLaterals(IApplication app, List<AddLateralDetails> addLateralsDetails, IFeature inFeatures, bool logOperation, bool suppressDialog, bool store, bool ForceSourcePointConnection, IFeatureLayer pEditLayer)
        {
            string resetFlow = "";
            bool useDefaultTemplate;
            List<IFeature> ComplFeat = new List<IFeature>();
            IMap map = null;
            IEditor editor = null;
            IMouseCursor appCursor = null;
            IMxDocument mxdoc = null;
            IFeatureLayer pointFLayer = null;
            IFeatureLayer matchLineFLayer = null;
            IFeatureLayer targetLineFLayer = null;
            IEditLayers eLayers = null;
            ISelectionSet2 pointSelSet = null;
            IFeatureSelection pointFeatureSelection = null;
            IEditTemplate pLateralLineEditTemp = null;
            List<pointAlongSettings> pointAlongLayers = null;
            pointAlongSettings pointAlongLayer = null;
            ICursor pointCursor = null;
            IFeature pointFeature = null;

            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;

            try
            {

                if (Control.ModifierKeys == Keys.Control)
                {
                    useDefaultTemplate = false;
                }
                else
                {

                    useDefaultTemplate = true;
                }
                bool boolSelectedEdges = false;
                if (Control.ModifierKeys == Keys.Shift)
                {
                    boolSelectedEdges = true;
                }
                else
                {

                    boolSelectedEdges = false;
                }
                //Get edit session
                bool LatCreated = false;

                editor = Globals.getEditor(app);
                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), _caption);
                    editor = null;

                    return "";
                }

                //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only)
                appCursor = new MouseCursorClass();
                appCursor.SetCursor(2);

                mxdoc = (IMxDocument)app.Document;
                map = editor.Map;

                for (int k = 0; k < addLateralsDetails.Count; k++)
                {
                    bool FCorLayerPoint = true;
                    if (pEditLayer != null)
                    {
                        if (pEditLayer.Name == addLateralsDetails[k].Point_LayerName)
                        {
                            pointFLayer = pEditLayer;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else {
                        pointFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].Point_LayerName, ref FCorLayerPoint);
                    }
                    if (inFeatures != null)
                    {
                        if (pointFLayer == null)
                            continue;
                        if (pointFLayer.FeatureClass == null)
                            continue;

                        if (inFeatures.Class.CLSID.ToString() != pointFLayer.FeatureClass.CLSID.ToString())
                            continue;
                        if (inFeatures.Class.ObjectClassID.ToString() != pointFLayer.FeatureClass.ObjectClassID.ToString())
                            continue;
                        if (inFeatures.Class.AliasName.ToString() != pointFLayer.FeatureClass.AliasName.ToString())
                            continue;

                    }
                    //Report any problems before exiting
                    if (pointFLayer == null)
                    {
                        continue;
                    }

                    bool FCorLayerMatch = true;
                    bool FCorLayerTarget = true;

                    matchLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].MainLine_LayerName, ref FCorLayerMatch);
                    targetLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].LateralLine_LayerName, ref FCorLayerTarget);

                    // IFeatureLayerDefinition2 pFeatLayerdef = matchLineFLayer as IFeatureLayerDefinition2;

                    if (matchLineFLayer == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (matchLineFLayer.FeatureClass == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (matchLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_2") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer.FeatureClass == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_4") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }

                    //Confirm the other layers are the correct shape type
                    if (pointFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint || matchLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
                        return "";

                    //Confirm that target layer is editable and is a line layer
                    eLayers = (IEditLayers)editor;
                    if (!(eLayers.IsEditable(targetLineFLayer)) || (targetLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline))
                        return "";

                    //Confirm that the two line layers are different Feature classes
                    if ((matchLineFLayer.FeatureClass.CLSID == targetLineFLayer.FeatureClass.CLSID) && (matchLineFLayer.FeatureClass.AliasName == targetLineFLayer.FeatureClass.AliasName))
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_1") , A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_2") );
                        return "";
                    }

                    //Verify that some points are selected
                    pointFeatureSelection = (IFeatureSelection)pointFLayer;

                    if (pointFeatureSelection.SelectionSet.Count == 0)
                        continue;

                    pointSelSet = pointFeatureSelection.SelectionSet as ISelectionSet2;

                    if (useDefaultTemplate)
                    {
                        //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate);
                        pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate);
                    }
                    else
                    {
                        pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, "");
                        //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, "");
                    }

                    if (addLateralsDetails[k].PointAlong != null)
                    {

                        if (addLateralsDetails[k].PointAlong.Length > 0)
                        {
                            pointAlongLayers = new List<pointAlongSettings>();

                            // IEditTemplate pPointAlongEditTemp;
                            for (int j = 0; j < addLateralsDetails[k].PointAlong.Length; j++)
                            {
                                pointAlongLayer = new pointAlongSettings();
                                bool FCorLayerPointsAlong = true;
                                pointAlongLayer.PointAlongLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].LayerName, ref FCorLayerPointsAlong);
                                if (pointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PointAlongLayer.FeatureClass == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_2") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";
                                }
                                else if (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint)
                                {
                                    MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_3") , A4LGSharedFunctions.Localizer.GetString("Warning") );

                                    return "";
                                }

                                pointAlongLayer.PolygonIntersectSide = addLateralsDetails[k].PointAlong[j].PolygonOffsetSide;
                                if (pointAlongLayer.PolygonIntersectSide == null)
                                {
                                    pointAlongLayer.PolygonIntersectSide = "TO";

                                }
                                bool FCorLayerTemp = true;
                                pointAlongLayer.PolygonIntersectLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName, ref FCorLayerTemp);
                                pointAlongLayer.FoundAsLayer = FCorLayerTemp;
                                if (pointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PolygonIntersectLayer != null)
                                {

                                    if (pointAlongLayer.PolygonIntersectLayer.FeatureClass != null)
                                    {

                                        //Confirm that target layer is editable and is a line layer
                                        if (pointAlongLayer.PolygonIntersectLayer != null)
                                        {
                                            if (pointAlongLayer.PolygonIntersectLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon)
                                            {
                                                MessageBox.Show(addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_3"));

                                                return "";
                                            }

                                        }
                                    }
                                }
                                //Confirm that target layer is editable and is a line layer
                                if (pointAlongLayer.PointAlongLayer != null)
                                {
                                    if (!(eLayers.IsEditable(pointAlongLayer.PointAlongLayer)) || (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint))
                                    {
                                        MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_4"));

                                        return "";
                                    }
                                    if (useDefaultTemplate)
                                    {
                                        pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate);
                                        //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate);
                                    }
                                    else
                                    {
                                        pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, "");
                                        //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, "");
                                    }

                                }

                                //if (addLateralsDetails[k].PointAlong[j].Distance < 0)
                                //    pointAlongLayer.PointAlongDistance = 0;
                                //else
                                pointAlongLayer.PointAlongDistance = (double)addLateralsDetails[k].PointAlong[j].Distance;

                                //if (addLateralsDetails[k].PointAlong[j].DistanceIsPercent != null)
                                pointAlongLayer.DistanceIsPercent = (bool)addLateralsDetails[k].PointAlong[j].DistanceIsPercent;
                                //else
                                //  pointAlongLayer.DistanceIsPercent =false;

                                pointAlongLayers.Add(pointAlongLayer);

                                //Verify subtype is valid for target point
                                //if (targetPointFLayer != null)
                                //{
                                //    ISubtypes targetPointSubtypes = targetPointFLayer[j].FeatureClass as ISubtypes;
                                //    //string targetPointSubtypeName = targetPointSubtypes.get_SubtypeName(_targetPointSubtype);
                                //    if ((targetPointSubtypes == null) || (!targetPointSubtypes.HasSubtype))// || (String.IsNullOrEmpty(targetPointSubtypeName)))
                                //        addLateralsDetails[k].PointAlong[j].Subtype = -1;
                                //    else
                                //    {
                                //        try
                                //        {
                                //            string SubVal = targetPointSubtypes.get_SubtypeName(addLateralsDetails[k].PointAlong[j].Subtype);
                                //            //  addLateralsDetails[k].PointAlong[j].Subtype = SubVal
                                //            //targetPointSubtype[k] = addLateralsDetails[k].PointAlong[j].Subtype;

                                //        }
                                //        catch
                                //        {
                                //            addLateralsDetails[k].PointAlong[j].Subtype = targetPointSubtypes.DefaultSubtypeCode;
                                //        }
                                //    }
                                //}
                                //else
                                //{
                                //    addLateralsDetails[k].PointAlong[j].Subtype = -1;
                                //}
                                //addLateralsDetails[k].PointAlong[j].Distance
                                //    addLateralsDetails[k].PointAlong[j].DistanceIsPercent
                                //        addLateralsDetails[k].PointAlong[j].FieldToPopulate
                                //        addLateralsDetails[k].PointAlong[j].ValueToPopulate
                            }
                        }
                    }
                    //****************************************

                    int total;

                    total = pointSelSet.Count;

                    int i = 0;

                    // Create a CancelTracker
                    trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                    // Set the properties of the Step Progressor
                    System.Int32 int32_hWnd = app.hWnd;
                    if (suppressDialog == false)
                    {
                        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                        stepProgressor.MinRange = 0;
                        stepProgressor.MaxRange = total;
                        stepProgressor.StepValue = 1;
                        stepProgressor.Message = _caption;
                        // Create the ProgressDialog. This automatically displays the dialog
                        progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                        // Set the properties of the ProgressDialog
                        progressDialog.CancelEnabled = true;
                        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
                        progressDialog.Title = _caption;
                        progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                        progressDialog.ShowDialog();

                    }
                    // Create an edit operation enabling undo/redo

                    if (logOperation)
                    {
                        try
                        {
                            editor.StartOperation();
                        }
                        catch
                        {
                            logOperation = false;
                        }

                    }

                    IPoint fromPoint = null;
                    IPoint selPt1 = null;
                    IPoint selPt2 = null;
                    ILine distanceLine = null;
                    object Missing = null;
                    IEnvelope env = null;
                    IEnumIDs selIds = null;
                    IFeature pointFeature2 = null;
                    List<int> completedOIDArrayList = null;
                    ITopologicalOperator topoOp = null;
                    IPolygon poly = null;
                    ISpatialFilter sFilter = null;
                    IFeatureCursor lineCursor = null;
                    INetworkFeature pNF = null;
                    IFeature testPointFeature = null;

                    int featOID1, featOID2, nearbyCount;

                    try
                    {

                        // ISelectionSet2 sel = pointSelSet as ISelectionSet2;
                        pointSelSet.Update(null, false, out pointCursor);
                        completedOIDArrayList = new List<int>();

                        while ((pointFeature = (IFeature)pointCursor.NextRow()) != null)
                        {
                            try
                            {
                                //if (inFeatures != null)
                                //{
                                //    if (pointFeature.OID != inFeatures.OID)
                                //    {
                                //        continue;

                                //    }
                                //}
                                i += 1;
                                if (suppressDialog == false)
                                {
                                    //Update progress bar
                                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine +
                                      A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID;
                                    stepProgressor.Step();
                                }
                                ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
                                statusBar.set_Message(0, i.ToString());

                                //Check if the cancel button was pressed. If so, stop process
                                bool boolean_Continue = trackCancel.Continue();
                                if (!boolean_Continue)
                                {
                                    break;
                                }

                                if (!ComplFeat.Contains(pointFeature))
                                {
                                    //Get the "from" point for new line (start from selected point)
                                    fromPoint = pointFeature.ShapeCopy as IPoint;

                                    //Create new feature(s)

                                    env = new EnvelopeClass();

                                    //Dual Laterals When Two Selected
                                    if (total == 2 && addLateralsDetails[k].Dual_When_Two_Selected)
                                    {
                                        if (suppressDialog == false)
                                        {
                                            //Update progress bar
                                            progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine +
                                              A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID;
                                            stepProgressor.Step();
                                        }
                                        //Obtain both starting points
                                        selIds = pointSelSet.IDs;
                                        selIds.Reset();
                                        featOID1 = selIds.Next();
                                        featOID2 = selIds.Next();
                                        pointFeature2 = pointFLayer.FeatureClass.GetFeature(featOID2);
                                        selPt1 = pointFeature.ShapeCopy as IPoint;
                                        selPt2 = pointFeature2.ShapeCopy as IPoint;

                                        //Measure distance
                                        distanceLine = new LineClass();
                                        distanceLine.PutCoords(selPt1, selPt2);
                                        if (distanceLine.Length <= addLateralsDetails[k].Dual_Max_Distance_When_Two_Selected)
                                        {
                                            LatCreated = CreateDual(ref app, ref editor, pointFeature, pointFeature2, distanceLine, matchLineFLayer,
                                                              targetLineFLayer, pLateralLineEditTemp, pointAlongLayers,
                                                              addLateralsDetails[k].DeleteExistingLines,
                                                              addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square,
                                                              addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                              addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature2);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature);
                                            //CreateDualOld(pointFeature, pointFeature2, distanceLine, matchLineFLayer,
                                            //                lineFeature, targetLineFLayer, targetPointFLayer, addLateralsDetails[k].DeleteExistingLines,
                                            //                 addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square,
                                            //                 addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                            //                 addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                            //                 addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                            //                 addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                            //                 addLateralsDetails[k].PointAlong);

                                            //_targetPointDistance, _targetPointDistanceIsPercent, _targetPointSubtype, _targetPointValue, _targetPointFieldName);
                                            break;
                                        }
                                        //Create two single laterals if the duals are not created
                                        else
                                        {
                                            LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers,
                                                             addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                                             addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                             addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature);

                                            LatCreated = CreateSingle(ref app, ref editor, pointFeature2, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers,
                                                            addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                                            addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                            addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature2);

                                            //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer,
                                            //                addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                            //                addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                            //                addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                            //                addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                            //                addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                            //                addLateralsDetails[k].PointAlong);

                                            //CreateSingleOld(pointFeature2, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer,
                                            //                addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                            //                addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                            //                addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                            //                addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                            //                addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                            //                addLateralsDetails[k].PointAlong);
                                            break;
                                        }
                                    }

                                    //Dual Laterals when Nearby
                                    else if ((total != 1) & addLateralsDetails[k].Dual_When_Nearby)
                                    {

                                        //Check that this feature has not already been completed
                                        if (completedOIDArrayList.Contains(pointFeature.OID))
                                            continue;

                                        selPt1 = pointFeature.ShapeCopy as IPoint;
                                        nearbyCount = 0;
                                        pointFeature2 = null;

                                        //Determine if extactly one other point is within the specified max distance
                                        topoOp = selPt1 as ITopologicalOperator;
                                        poly = topoOp.Buffer(addLateralsDetails[k].Dual_Max_Distance_When_Nearby / 2) as IPolygon;
                                        sFilter = new SpatialFilterClass();
                                        sFilter.Geometry = poly;
                                        sFilter.GeometryField = pointFLayer.FeatureClass.ShapeFieldName;
                                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                        if (addLateralsDetails[k].SearchOnLayer)
                                            lineCursor = pointFLayer.Search(sFilter, false);
                                        else
                                            lineCursor = pointFLayer.FeatureClass.Search(sFilter, false);

                                        while ((testPointFeature = lineCursor.NextFeature()) != null)
                                        {
                                            if (testPointFeature.OID != pointFeature.OID)
                                            {
                                                //Check that this nearby feature has not already been completed
                                                if (!completedOIDArrayList.Contains(pointFeature.OID))
                                                {
                                                    pointFeature2 = testPointFeature;
                                                    nearbyCount += 1;
                                                }
                                            }
                                            if (nearbyCount > 1)
                                                break;
                                        }

                                        if (nearbyCount == 1)
                                        {
                                            selPt2 = pointFeature2.ShapeCopy as IPoint;

                                            //Measure distance
                                            distanceLine = new LineClass();
                                            distanceLine.PutCoords(selPt1, selPt2);
                                            LatCreated = CreateDual(ref app, ref editor, pointFeature, pointFeature2, distanceLine, matchLineFLayer,
                                                              targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].DeleteExistingLines,
                                                              addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square,
                                                              addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                              addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature2);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature);
                                            //CreateDualOld(pointFeature, pointFeature2, distanceLine, matchLineFLayer,
                                            //               lineFeature, targetLineFLayer, targetPointFLayer, addLateralsDetails[k].DeleteExistingLines,
                                            //                addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].Dual_Option_Make_Square,
                                            //                addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                            //                addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                            //                addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                            //                addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                            //                addLateralsDetails[k].PointAlong);
                                            //Add 2nd OID to completed list
                                            completedOIDArrayList.Add(pointFeature2.OID);
                                        }

                                        //Create a single lateral if 1 nearby not found
                                        else
                                        {
                                            LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers,
                                                addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                                            addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                            addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                            if (LatCreated)
                                                ComplFeat.Add(pointFeature);
                                            //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer,
                                            //    addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                            //                addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                            //                addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                            //                addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                            //                addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                            //                addLateralsDetails[k].PointAlong);
                                        }
                                    }
                                    //Single Laterals
                                    else
                                    {
                                        LatCreated = CreateSingle(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers,
                                              addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                                             addLateralsDetails[k].FromToFields, addLateralsDetails[k].Hook_DoglegDistance,
                                                            addLateralsDetails[k].Hook_DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete, store, addLateralsDetails[k].SearchOnLayer, addLateralsDetails[k].SearchDistance, addLateralsDetails[k].Hook_Angle, boolSelectedEdges);
                                        if (LatCreated)
                                            ComplFeat.Add(pointFeature);
                                        //CreateSingleOld(pointFeature, matchLineFLayer, lineFeature, targetLineFLayer, targetPointFLayer,
                                        //     addLateralsDetails[k].LateralLine_StartAtMain, addLateralsDetails[k].DeleteExistingLines,
                                        //                   addLateralsDetails[k].Point_FieldToCalcFromMain, addLateralsDetails[k].Main_FieldToCalcForPoint,
                                        //                   addLateralsDetails[k].Point_PrefixForMainValue, addLateralsDetails[k].LateralLine_ValueToPopulate,
                                        //                   addLateralsDetails[k].LateralLine_FieldToPopulate, targetLineSubValue,
                                        //                   addLateralsDetails[k].Hook_DoglegDistance, addLateralsDetails[k].DistanceIsPercent, addLateralsDetails[k].TolerenceForDelete,
                                        //                   addLateralsDetails[k].PointAlong);
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);

                            }
                            finally
                            {

                            }
                            //   addLateralsDetails[k].InitDefaults();
                            if (addLateralsDetails[k].Reset_Flow != null)
                            {
                                resetFlow = addLateralsDetails[k].Reset_Flow;

                                if (resetFlow.ToUpper() == "DIGITIZED")
                                {
                                    Globals.GetCommand("A4WaterUtilities_EstablishFlowDigitized", app).Execute();

                                }
                                else if (resetFlow.ToUpper() == "ROLE")
                                {
                                    Globals.GetCommand("A4WaterUtilities_EstablishFlowAncillary", app).Execute();
                                }
                                else if (resetFlow.ToUpper() == "Ancillary".ToUpper())
                                {
                                    Globals.GetCommand("A4WaterUtilities_EstablishFlowAncillary", app).Execute();
                                }
                                else
                                {
                                }
                            }

                        }

                        if (ForceSourcePointConnection)
                        {
                            foreach (IFeature sourcePnt in ComplFeat)
                            {
                                if (sourcePnt != null)
                                {
                                    if (sourcePnt.Shape.IsEmpty != true)
                                    {
                                        if (sourcePnt is INetworkFeature)
                                        {
                                            pNF = (INetworkFeature)sourcePnt;
                                            try
                                            {
                                                pNF.Connect();
                                            }
                                            catch
                                            { }
                                        }
                                    }
                                }
                            }

                        }

                    }
                    catch (Exception ex)
                    {
                        editor.AbortOperation();
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);

                    }
                    finally
                    {
                        // Cleanup
                        if (progressDialog != null)
                            progressDialog.HideDialog();
                        if (lineCursor != null)
                            Marshal.ReleaseComObject(lineCursor);

                        pNF = null;
                        fromPoint = null;
                        selPt1 = null;
                        selPt2 = null;
                        distanceLine = null;
                        Missing = null;
                        env = null;
                        selIds = null;
                        pointFeature2 = null;
                        completedOIDArrayList = null;
                        topoOp = null;
                        poly = null;
                        sFilter = null;
                        lineCursor = null;
                        testPointFeature = null;
                    }

                    if (logOperation)
                    {
                        try
                        {
                            // Stop the edit operation
                            editor.StopOperation(_caption);

                        }
                        catch
                        {
                            logOperation = false;
                        }

                    }

                    //88
                }

                return resetFlow;

            }

            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);
                return "";
            }
            finally
            {
                ComplFeat.Clear();
                if (map != null)
                {
                    (map as IActiveView).Refresh();
                }
                if (progressDialog != null)
                    progressDialog.HideDialog();

                ComplFeat = null;
                map = null;
                editor = null;
                appCursor = null;
                mxdoc = null;
                pointFLayer = null;
                matchLineFLayer = null;
                targetLineFLayer = null;
                eLayers = null;
                pointSelSet = null;
                pointFeatureSelection = null;
                pLateralLineEditTemp = null;
                pointAlongLayers = null;
                pointAlongLayer = null;
                pointCursor = null;
                pointFeature = null;

                //ProgressBar
                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                // Create a CancelTracker
                trackCancel = null;

            }
        }
        public static returnFeatArray ConnectClosestFeature(IApplication app, List<ConnectClosestDetails> connectClosestLayers, bool logOperation, bool suppressDialog, string LayerName)
        {
            bool bUseTemplate;
            bool bSelectedOnly;
            if (Control.ModifierKeys == Keys.Shift)
            {

                bSelectedOnly = true;
                bUseTemplate = true;

            }
            else if (Control.ModifierKeys == (Keys.Control | Keys.Shift))
            {
                bSelectedOnly = true;
                bUseTemplate = false;

            }
            else if (Control.ModifierKeys == Keys.Control)
            {
                bSelectedOnly = false;
                bUseTemplate = false;

            }
            else
            {

                bSelectedOnly = false;
                bUseTemplate = true;
            }

            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;

            List<IFeature> pRetFeature = new List<IFeature>();
            IEditor editor = null;
            IMouseCursor appCursor = null;
            IMxDocument mxdoc = null;
            IMap map = null;
            IFeatureLayer pTargetLayer = null;
            IFeatureLayer pointFLayer = null;
            IFeatureLayer connectLineFLayer = null;
            ICursor pointCursor = null;
            IFeature pointFeature = null;

            IEditTemplate pEditTemp = null;
            IFeatureSelection pointFeatureSelection = null;
            IGeometry pNearestFeature = null;
            ISelectionSet2 sel = null;
            IPolyline pNewPoly = null;
            IFeature pLine = null;
            IEditLayers eLayers = null;
            returnFeatArray retVal = new returnFeatArray();
            try
            {
                //Get edit session
                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
                editor = Globals.getEditor(app);
                if (editor == null)
                    return null;

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), _caption);
                    //_editor = null;

                    return null;
                }

                //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only)
                appCursor = new MouseCursorClass();
                appCursor.SetCursor(2);

                mxdoc = (IMxDocument)app.Document;
                map = mxdoc.FocusMap;

                //Find required layers
                if (connectClosestLayers == null)
                    return null;
                if (connectClosestLayers.Count == 0)
                    return null;

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = app.hWnd;
                if (suppressDialog == false)
                {
                    progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

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

                    // Set the properties of the ProgressDialog
                    progressDialog.CancelEnabled = true;
                    progressDialog.Title = _caption;
                    progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                    progressDialog.ShowDialog();

                }
                // Create an edit operation enabling undo/redo

                bool FCorLayerTarget = true;
                if (LayerName != "")
                {
                    pTargetLayer = Globals.FindLayer(map, LayerName, ref  FCorLayerTarget) as IFeatureLayer;

                }

                for (int k = 0; k < connectClosestLayers.Count; k++)
                {
                    bool FCorLayerPoint = true;
                    bool FCorLayerConnect = true;
                    //int currentLayerSub;
                    pointFLayer = Globals.FindLayer(map, (connectClosestLayers[k] as ConnectClosestDetails).Point_Layer, ref FCorLayerPoint) as IFeatureLayer;
                    connectLineFLayer = Globals.FindLayer(map, (connectClosestLayers[k] as ConnectClosestDetails).Line_Layer, ref FCorLayerConnect) as IFeatureLayer;

                    //Report any problems before exiting
                    if (pointFLayer == null)
                    {
                        //MessageBox.Show("Layer representing connection points was not found.  Configuration indicated feature class name: '" + _pointLayerName + "'.", _caption);
                        //return;
                        continue;
                    }
                    if (connectLineFLayer == null)
                    {
                        //MessageBox.Show("Layer representing connect was not found.  Configuration indicated feature class name: '" + _connectLineLayerName + "'.", _caption);
                        //return;
                        continue;
                    }
                    if (pTargetLayer != null)
                    {
                        if (pTargetLayer.FeatureClass.CLSID.Value.ToString() != pointFLayer.FeatureClass.CLSID.Value.ToString())

                        { continue; }
                    }

                    //Verify that some points are selected

                    pointFeatureSelection = (IFeatureSelection)pointFLayer;
                    if (pointFeatureSelection.SelectionSet.Count == 0)
                        continue;

                    //Confirm that target layer is editable and is a line layer
                    eLayers = (IEditLayers)editor;
                    if (!(eLayers.IsEditable(connectLineFLayer)) || (connectLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline))
                        continue;

                    //Confirm the other layers are the correct shape type
                    if (pointFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
                        continue;
                    if (suppressDialog == false)
                    {
                        stepProgressor.MinRange = 0;
                        stepProgressor.MaxRange = connectClosestLayers.Count;
                        progressDialog.Title = (connectClosestLayers[k] as ConnectClosestDetails).Line_Layer;
                        stepProgressor.Message = (connectClosestLayers[k] as ConnectClosestDetails).Line_Layer;
                        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ConnectAsset") + "1" + A4LGSharedFunctions.Localizer.GetString("Of") + pointFeatureSelection.SelectionSet.Count + ".";
                    }

                    int total = pointFeatureSelection.SelectionSet.Count;
                    int i = 0;

                    try
                    {

                        if (logOperation)
                        {
                            try
                            {
                                editor.StartOperation();
                            }
                            catch
                            {
                                logOperation = false;
                            }

                        }

                        if (bUseTemplate)
                        {
                            pEditTemp = Globals.PromptAndGetEditTemplateGraphic(connectLineFLayer, connectClosestLayers[k].Line_EditTemplate);
                            //pEditTemp = Globals.PromptAndGetEditTemplate(app, connectLineFLayer, connectClosestLayers[k].Line_EditTemplate);
                        }
                        else
                        {
                            //pEditTemp = Globals.PromptAndGetEditTemplate(app, connectLineFLayer, "");
                            pEditTemp = Globals.PromptAndGetEditTemplateGraphic(connectLineFLayer, "");
                        }

                        sel = pointFeatureSelection.SelectionSet as ISelectionSet2;
                        //sel.Update(null, false, out pointCursor);
                        sel.Search(null, false, out pointCursor);
                        while ((pointFeature = (IFeature)pointCursor.NextRow()) != null)
                        {
                            i += 1;
                            if (suppressDialog == false)
                            {
                                //Update progress bar
                                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ConnectAsset") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine +
                                  A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID;
                                stepProgressor.Step();
                            }
                            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
                            statusBar.set_Message(0, i.ToString());

                            //Check if the cancel button was pressed. If so, stop process
                            bool boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                            {
                                break;
                            }

                            //IFeature pNearestFeature =
                            pNearestFeature = Globals.GetClosestFeatureIgnoreExistingLineFeature((connectClosestLayers[k] as ConnectClosestDetails).Search_Threshold,
                                                                             pointFeature.ShapeCopy, pointFLayer, connectLineFLayer, bSelectedOnly);

                            if (pNearestFeature == null)
                                break;

                            pNewPoly = new PolylineClass();
                            pNewPoly.FromPoint = pNearestFeature as IPoint;
                            pNewPoly.ToPoint = pointFeature.ShapeCopy as IPoint;

                            if (pEditTemp == null)
                            {
                                pLine = Globals.CreateFeature(pNewPoly, connectLineFLayer, editor, app, false, false, true);
                            }
                            else
                            {
                                pLine = Globals.CreateFeature(pNewPoly, pEditTemp, editor, app, false, false, true);
                            }
                            pLine.Store();
                            pRetFeature.Add(pLine);

                        }
                        if ((connectClosestLayers[k] as ConnectClosestDetails).Reset_Flow != null)
                        {
                            if ((connectClosestLayers[k] as ConnectClosestDetails).Reset_Flow.ToUpper() == "DIGITIZED")
                            {
                                retVal.Options = "DIGITIZED";

                            }
                            else if ((connectClosestLayers[k] as ConnectClosestDetails).Reset_Flow.ToUpper() == "ROLE")
                            {
                                retVal.Options = "ROLE";

                            }
                            else if ((connectClosestLayers[k] as ConnectClosestDetails).Reset_Flow.ToUpper() == "Ancillary".ToUpper())
                            {
                                retVal.Options = "ANCILLARY";

                            }
                            else
                            {
                            }

                        }

                        if (logOperation)
                        {
                            try
                            {
                                // Stop the edit operation
                                editor.StopOperation((connectClosestLayers[k] as ConnectClosestDetails).Point_Layer);

                            }
                            catch
                            {
                                logOperation = false;
                            }

                        }

                    }

                    catch (Exception ex)
                    {
                        editor.AbortOperation();
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "ConnectClosestFeature\n" + ex.Message, ex.Source);

                        // Cleanup
                        if (progressDialog != null)
                            progressDialog.HideDialog();
                        return null;
                    }

                }
                (map as IActiveView).Refresh();
                retVal.Features = pRetFeature;
                return retVal;
            }

            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "ConnectClosestFeature\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_1"));
                return null;
            }
            finally
            {// Cleanup
                if (progressDialog != null)
                    progressDialog.HideDialog();
                if (pointCursor != null)
                    Marshal.ReleaseComObject(pointCursor);
                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                trackCancel = null;

                pRetFeature = null;
                editor = null;
                appCursor = null;
                mxdoc = null;
                map = null;
                pTargetLayer = null;
                pointFLayer = null;
                connectLineFLayer = null;
                pointCursor = null;
                pointFeature = null;

                pEditTemp = null;
                pointFeatureSelection = null;
                pNearestFeature = null;
                sel = null;
                pNewPoly = null;
                pLine = null;
                eLayers = null;

            }
        }
        public static string AddLateralsFromMainPoint(IApplication app, List<AddLateralFromMainPointDetails> addLateralsDetails, IFeature inFeatures, bool logOperation, bool suppressDialog, bool store)
        {
            string resetFlow = "";
            bool useDefaultTemplate;
            List<IFeature> ComplFeat = new List<IFeature>();
            IMap map = null;
            IEditor editor = null;
            IMouseCursor appCursor = null;
            IMxDocument mxdoc = null;
            IFeatureLayer pointFLayer = null;
            IFeatureLayer matchLineFLayer = null;
            IFeatureLayer targetLineFLayer = null;
            IEditLayers eLayers = null;
            ISelectionSet2 pointSelSet = null;
            IFeatureSelection pointFeatureSelection = null;
            IEditTemplate pLateralLineEditTemp = null;
            List<pointAlongSettings> pointAlongLayers = null;
            pointAlongSettings pointAlongLayer = null;
            ICursor pointCursor = null;
            IFeature pointFeature = null;

            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;

            try
            {

                if (Control.ModifierKeys == Keys.Control)
                {
                    useDefaultTemplate = false;
                }
                else
                {

                    useDefaultTemplate = true;
                }
                bool boolSelectedEdges = false;
                if (Control.ModifierKeys == Keys.Shift)
                {
                    boolSelectedEdges = true;
                }
                else
                {

                    boolSelectedEdges = false;
                }
                //Get edit session
                bool LatCreated = false;

                editor = Globals.getEditor(app);
                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), _caption);
                    editor = null;

                    return "";
                }

                //Change mouse cursor to wait - automatically changes back (ArcGIS Desktop only)
                appCursor = new MouseCursorClass();
                appCursor.SetCursor(2);

                mxdoc = (IMxDocument)app.Document;
                map = editor.Map;

                for (int k = 0; k < addLateralsDetails.Count; k++)
                {
                    bool FCorLayerPoint = true;
                    pointFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].Point_LayerName, ref FCorLayerPoint);
                    if (inFeatures != null)
                    {
                        if (pointFLayer == null)
                            continue;
                        if (pointFLayer.FeatureClass == null)
                            continue;

                        if (inFeatures.Class.CLSID.ToString() != pointFLayer.FeatureClass.CLSID.ToString())
                            continue;

                    }
                    //Report any problems before exiting
                    if (pointFLayer == null)
                    {
                        continue;
                    }

                    bool FCorLayerMatch = true;
                    bool FCorLayerTarget = true;

                    matchLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].MainLine_LayerName, ref FCorLayerMatch);
                    targetLineFLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].LateralLine_LayerName, ref FCorLayerTarget);

                    // IFeatureLayerDefinition2 pFeatLayerdef = matchLineFLayer as IFeatureLayerDefinition2;

                    if (matchLineFLayer == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (matchLineFLayer.FeatureClass == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_1") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (matchLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_2") + "'" + addLateralsDetails[k].MainLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer.FeatureClass == null)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_3") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }
                    if (targetLineFLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsMess_4") + "'" + addLateralsDetails[k].LateralLine_LayerName + "'.", _caption);
                        return "";
                    }

                    //Confirm the other layers are the correct shape type
                    if (pointFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint || matchLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
                        return "";

                    //Confirm that target layer is editable and is a line layer
                    eLayers = (IEditLayers)editor;
                    if (!(eLayers.IsEditable(targetLineFLayer)) || (targetLineFLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline))
                        return "";

                    //Confirm that the two line layers are different Feature classes
                    if ((matchLineFLayer.FeatureClass.CLSID == targetLineFLayer.FeatureClass.CLSID) && (matchLineFLayer.FeatureClass.AliasName == targetLineFLayer.FeatureClass.AliasName))
                    {
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_1") , A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_2") );
                        return "";
                    }

                    //Verify that some points are selected
                    pointFeatureSelection = (IFeatureSelection)pointFLayer;

                    if (pointFeatureSelection.SelectionSet.Count == 0)
                        continue;

                    pointSelSet = pointFeatureSelection.SelectionSet as ISelectionSet2;

                    if (useDefaultTemplate)
                    {
                        //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate);
                        pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, addLateralsDetails[k].LateralLine_EditTemplate);
                    }
                    else
                    {
                        pLateralLineEditTemp = Globals.PromptAndGetEditTemplateGraphic(targetLineFLayer, "");
                        //pLateralLineEditTemp = Globals.PromptAndGetEditTemplate(app, targetLineFLayer, "");
                    }

                    if (addLateralsDetails[k].PointAlong != null)
                    {

                        if (addLateralsDetails[k].PointAlong.Length > 0)
                        {
                            pointAlongLayers = new List<pointAlongSettings>();

                            // IEditTemplate pPointAlongEditTemp;
                            for (int j = 0; j < addLateralsDetails[k].PointAlong.Length; j++)
                            {
                                pointAlongLayer = new pointAlongSettings();
                                bool FCorLayerPointsAlong = true;
                                pointAlongLayer.PointAlongLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].LayerName, ref FCorLayerPointsAlong);
                                if (pointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PointAlongLayer.FeatureClass == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_2") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";
                                }
                                else if (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint)
                                {
                                    MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_3") , A4LGSharedFunctions.Localizer.GetString("Warning") );

                                    return "";
                                }

                                pointAlongLayer.PolygonIntersectSide = addLateralsDetails[k].PointAlong[j].PolygonOffsetSide;
                                if (pointAlongLayer.PolygonIntersectSide == null)
                                {
                                    pointAlongLayer.PolygonIntersectSide = "TO";

                                }
                                bool FCorLayerTemp = true;
                                pointAlongLayer.PolygonIntersectLayer = (IFeatureLayer)Globals.FindLayer(map, addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName, ref FCorLayerTemp);
                                pointAlongLayer.FoundAsLayer = FCorLayerTemp;
                                if (pointAlongLayer == null)
                                {
                                    if (MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsAsk_1") , A4LGSharedFunctions.Localizer.GetString("Warning") , MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)

                                        return "";

                                }
                                else if (pointAlongLayer.PolygonIntersectLayer != null)
                                {

                                    if (pointAlongLayer.PolygonIntersectLayer.FeatureClass != null)
                                    {

                                        //Confirm that target layer is editable and is a line layer
                                        if (pointAlongLayer.PolygonIntersectLayer != null)
                                        {
                                            if (pointAlongLayer.PolygonIntersectLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon)
                                            {
                                                MessageBox.Show(addLateralsDetails[k].PointAlong[j].PolygonOffsetLayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_3"));

                                                return "";
                                            }

                                        }
                                    }
                                }
                                //Confirm that target layer is editable and is a line layer
                                if (pointAlongLayer.PointAlongLayer != null)
                                {
                                    if (!(eLayers.IsEditable(pointAlongLayer.PointAlongLayer)) || (pointAlongLayer.PointAlongLayer.FeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint))
                                    {
                                        MessageBox.Show(addLateralsDetails[k].PointAlong[j].LayerName + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsError_4"));

                                        return "";
                                    }
                                    if (useDefaultTemplate)
                                    {
                                        pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate);
                                        //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, addLateralsDetails[k].PointAlong[j].EditTemplate);
                                    }
                                    else
                                    {
                                        pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplateGraphic(pointAlongLayer.PointAlongLayer, "");
                                        //pointAlongLayer.PointAlongEditTemplate = Globals.PromptAndGetEditTemplate(app, pointAlongLayer.PointAlongLayer, "");
                                    }

                                }

                                //if (addLateralsDetails[k].PointAlong[j].Distance < 0)
                                //    pointAlongLayer.PointAlongDistance = 0;
                                //else
                                pointAlongLayer.PointAlongDistance = (double)addLateralsDetails[k].PointAlong[j].Distance;

                                //if (addLateralsDetails[k].PointAlong[j].DistanceIsPercent != null)
                                pointAlongLayer.DistanceIsPercent = (bool)addLateralsDetails[k].PointAlong[j].DistanceIsPercent;
                                //else
                                //  pointAlongLayer.DistanceIsPercent =false;

                                pointAlongLayers.Add(pointAlongLayer);

                            }
                        }
                    }
                    //****************************************

                    int total;

                    total = pointSelSet.Count;

                    int i = 0;

                    // Create a CancelTracker
                    trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                    // Set the properties of the Step Progressor
                    System.Int32 int32_hWnd = app.hWnd;
                    if (suppressDialog == false)
                    {
                        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                        stepProgressor.MinRange = 0;
                        stepProgressor.MaxRange = total;
                        stepProgressor.StepValue = 1;
                        stepProgressor.Message = _caption;
                        // Create the ProgressDialog. This automatically displays the dialog
                        progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                        // Set the properties of the ProgressDialog
                        progressDialog.CancelEnabled = true;
                        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
                        progressDialog.Title = _caption;
                        progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                        progressDialog.ShowDialog();

                    }
                    // Create an edit operation enabling undo/redo

                    if (logOperation)
                    {
                        try
                        {
                            editor.StartOperation();
                        }
                        catch
                        {
                            logOperation = false;
                        }

                    }

                    //IPoint fromPoint = null;
                    //IPoint selPt1 = null;
                    //IPoint selPt2 = null;
                    //ILine distanceLine = null;
                    //object Missing = null;
                    //IEnvelope env = null;
                    //IEnumIDs selIds = null;
                    //IFeature pointFeature2 = null;
                    List<int> completedOIDArrayList = null;
                    //ITopologicalOperator topoOp = null;
                    //IPolygon poly = null;
                    //ISpatialFilter sFilter = null;
                    IFeatureCursor lineCursor = null;
                    INetworkFeature pNF = null;
                    IFeature testPointFeature = null;

                    int featOID1, featOID2, nearbyCount;

                    try
                    {

                        // ISelectionSet2 sel = pointSelSet as ISelectionSet2;
                        pointSelSet.Update(null, false, out pointCursor);
                        completedOIDArrayList = new List<int>();

                        while ((pointFeature = (IFeature)pointCursor.NextRow()) != null)
                        {
                            try
                            {

                                i += 1;
                                if (suppressDialog == false)
                                {
                                    //Update progress bar
                                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("AddLine") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + "." + Environment.NewLine +
                                      A4LGSharedFunctions.Localizer.GetString("CurrentOID") + pointFeature.OID;
                                    stepProgressor.Step();
                                }
                                ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
                                statusBar.set_Message(0, i.ToString());

                                //Check if the cancel button was pressed. If so, stop process
                                bool boolean_Continue = trackCancel.Continue();
                                if (!boolean_Continue)
                                {
                                    break;
                                }

                                CreateLateralFromMainPoint(ref app, ref editor, pointFeature, matchLineFLayer, targetLineFLayer, pLateralLineEditTemp, pointAlongLayers, addLateralsDetails[k].LateralLine_StartAtMain,
                                    addLateralsDetails[k].FromToFields, addLateralsDetails[k].LateralLine_AngleDetails, addLateralsDetails[k].SearchOnLayer, boolSelectedEdges);

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);

                            }
                            finally
                            {

                            }
                            //   addLateralsDetails[k].InitDefaults();
                            if (addLateralsDetails[k].Reset_Flow != null)
                            {
                                resetFlow = addLateralsDetails[k].Reset_Flow;

                            }
                        }

                        //if (ForceSourcePointConnection)
                        //{
                        //    foreach (IFeature sourcePnt in ComplFeat)
                        //    {
                        //        if (sourcePnt != null)
                        //        {
                        //            if (sourcePnt.Shape.IsEmpty != true)
                        //            {
                        //                if (sourcePnt is INetworkFeature)
                        //                {
                        //                    pNF = (INetworkFeature)sourcePnt;
                        //                    try
                        //                    {
                        //                        pNF.Connect();
                        //                    }
                        //                    catch
                        //                    { }
                        //                }
                        //            }
                        //        }
                        //    }

                        // }

                    }
                    catch (Exception ex)
                    {
                        editor.AbortOperation();
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);

                    }
                    finally
                    {
                        // Cleanup
                        if (progressDialog != null)
                            progressDialog.HideDialog();
                        if (lineCursor != null)
                            Marshal.ReleaseComObject(lineCursor);

                        pNF = null;
                        //fromPoint = null;
                        //selPt1 = null;
                        //selPt2 = null;
                        //distanceLine = null;
                        //Missing = null;
                        //env = null;
                        //selIds = null;
                        //pointFeature2 = null;
                        completedOIDArrayList = null;
                        //topoOp = null;
                        //poly = null;
                        //sFilter = null;
                        lineCursor = null;
                        testPointFeature = null;
                    }

                    if (logOperation)
                    {
                        try
                        {
                            // Stop the edit operation
                            editor.StopOperation(_caption);

                        }
                        catch
                        {
                            logOperation = false;
                        }

                    }

                    //88
                }

                return resetFlow;

            }

            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("ConstructionToolsLbl_2") + "\n" + ex.Message, ex.Source);
                return "";
            }
            finally
            {
                ComplFeat.Clear();
                if (map != null)
                {
                    (map as IActiveView).Refresh();
                }
                if (progressDialog != null)
                    progressDialog.HideDialog();

                ComplFeat = null;
                map = null;
                editor = null;
                appCursor = null;
                mxdoc = null;
                pointFLayer = null;
                matchLineFLayer = null;
                targetLineFLayer = null;
                eLayers = null;
                pointSelSet = null;
                pointFeatureSelection = null;
                pLateralLineEditTemp = null;
                pointAlongLayers = null;
                pointAlongLayer = null;
                pointCursor = null;
                pointFeature = null;

                //ProgressBar
                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                // Create a CancelTracker
                trackCancel = null;

            }
        }
        public static void SetMeasures(IApplication app)
        {
            IEditor editor = null;
            ICursor pCursor = null;
            IFeatureCursor pFCursor = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            IMap map = null;
            IMxDocument mxdoc = null;
            ILayer layer = null;
            IFeatureLayer fLayer = null;
            IFeatureClass fc = null;
            IFeatureSelection fSel = null;
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;

            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;

            IFeature pFeature = null;
            IMSegmentation pMSeg = null;
            ICurve pCurve = null;
            try
            {
                editor = Globals.getEditor(app);
                if (editor == null)
                {
                    return;
                }

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show("Must be editing.", "Set Measures");
                    return;
                }
                mxdoc = app.Document as IMxDocument;
                layer = mxdoc.SelectedLayer as ILayer;
                // Verify that there are layers in the table on contents
                map = mxdoc.FocusMap;
                if (map.LayerCount < 1)
                {
                    MessageBox.Show("Must have at least one layer in your map.");
                    return;
                }

                if (layer == null)
                {
                    MessageBox.Show("You must have one higlighted layer in the TOC." + Environment.NewLine +
                                     "Any selected lines in this layer will have it measures set.");
                    return;
                }

                //Verify that it is a feature layer
                fLayer = layer as IFeatureLayer;
                if (fLayer == null)
                {
                    MessageBox.Show("The highlighted layer in the TOC must be a feature layer.");
                    return;
                }

                //Get the Feature layer and feature class
                fc = fLayer.FeatureClass;
                if (fc == null)
                {
                    MessageBox.Show("The highlighted layer datasource is not set.");
                    return;

                }
                if (fc.Fields.get_Field(fc.Fields.FindField(fc.ShapeFieldName)).GeometryDef.HasM == false)
                {
                    MessageBox.Show("The highlighted layer does not support Measures.");
                    return;

                }
                fSel = fLayer as IFeatureSelection;

                //Verify that it is a line layer
                if (fc.ShapeType != esriGeometryType.esriGeometryPolyline)
                {
                    MessageBox.Show("The highlighted layer in the TOC must contain lines.");
                    return;
                }
                //Verify Layer Selection
                if (fSel.SelectionSet.Count == 0)
                {
                    MessageBox.Show("No features are selected in the highlighed layer.");
                    return;
                }

                bool WithDig = true;
                if (MessageBox.Show("Calibrate lines using the digitized direction?", "Calibrate Lines", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    WithDig = false;
                }

                //Start edit operation (for undo)
                editor.StartOperation();
                //ProgressBar
                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                // Create a CancelTracker
                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = app.hWnd;
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                stepProgressor.MinRange = 0;
                stepProgressor.MaxRange = fSel.SelectionSet.Count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = "Setting Measure for line " + 1 + " of " + fSel.SelectionSet.Count.ToString() + ".";

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

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = "Setting Meaures";
                progressDialog.Title = "Setting measures for the selected lines.";
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
                //Step through each selected line in the highlighted layer
                fSel.SelectionSet.Search(null, false, out pCursor);
                pFCursor = (IFeatureCursor)pCursor;

                pFeature = pFCursor.NextFeature();
                int intCount = 1;
                //'Loop through each selected feature in the highlighted layer

                while ((pFeature != null))
                {

                    stepProgressor.Message = "Setting measure for line " + intCount + " of " + fSel.SelectionSet.Count.ToString() + ".";
                    if (pFeature.Shape is IMSegmentation)
                    {
                        try
                        {
                            if (pFeature.Shape != null)
                            {
                                pMSeg = (IMSegmentation)pFeature.ShapeCopy;
                                pCurve = (ICurve)pFeature.ShapeCopy;
                                if (WithDig)
                                {
                                    pMSeg.SetAndInterpolateMsBetween(0, pCurve.Length);
                                }
                                else
                                    pMSeg.SetAndInterpolateMsBetween(pCurve.Length, 0);

                                pFeature.Shape = (IGeometry)pMSeg;
                                pFeature.Store();
                            }
                            else
                            {
                                MessageBox.Show(" Object ID: " + pFeature.OID + " Has null geometry");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("SetMeasures\n" + ex.Message + " Object ID: " + pFeature.OID);
                        }
                    }

                    Marshal.ReleaseComObject(pFeature);
                    intCount++;
                    pFeature = pFCursor.NextFeature();
                    stepProgressor.Step();

                }

                editor.StopOperation("Set M's");
            }
            catch (Exception ex)
            {
                editor.AbortOperation();
                MessageBox.Show("SetMeasures\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }
                if (pCursor != null)
                    Marshal.ReleaseComObject(pCursor);
                if (pFCursor != null)
                    Marshal.ReleaseComObject(pFCursor);

                editor = null;
                pCursor = null;
                pFCursor = null;
                stepProgressor = null;
                progressDialog = null;
                map = null;
                mxdoc = null;
                layer = null;
                fLayer = null;
                fc = null;
                fSel = null;
                progressDialogFactory = null;
                trackCancel = null;

                pFeature = null;
                pMSeg = null;
                pCurve = null;
            }
        }
        public static void AddFlagsForSewerProfile(IApplication app, double snapTol, List<ProfileGraphDetails> ProfileGraph)
        {
            IFeatureCursor pFeatCursor = null;
            IMxDocument pMxDoc = null;

            IPoint pTracePoint = null;
            ISpatialFilter pSpatialFilter = null;
            // set the symbol for the flag, red circle
            IMarkerSymbol pMarkerSym = null;
            IRgbColor pRGBColor = null;

            IFeatureLayer pManholeLayer = null;
            IFeatureLayer pMainLayer = null;
            IFeatureLayer pTapLayer = null;
            IGraphicsContainer gc = null;

            IElement pProfileElemFirst = null;
            IElementProperties3 pProfileElemPropFirst = null;

            IElement element = null;
            IElementProperties3 elementProp = null;
            ITopologicalOperator pTopoOp = null;

            IFeature pFeature = null;
            double snapdistnet; // NetworkExt search tolerance
            IPolygon pBuffGeometry = null;
            IMarkerElement markerelem = null;
            IGeometricNetwork gn = null;

            IEnumNetEID juncEIDs = null;
            IEnumNetEID edgeEIDs = null;
            try
            {
                pMxDoc = ((IMxDocument)app.Document);

                pTracePoint = pMxDoc.CurrentLocation;

                pMarkerSym = Globals.FindMarkerSym("Esri.style", "Default", "Circle 2", pMxDoc);
                pRGBColor = Globals.GetColor(255, 0, 0);

                pMarkerSym.Color = pRGBColor;
                pMarkerSym.Size = 11;

                gc = pMxDoc.FocusMap as IGraphicsContainer;

                pProfileElemFirst = null;
                pProfileElemPropFirst = null;

                gc.Reset();
                element = gc.Next();

                while (element != null)
                {
                    elementProp = element as IElementProperties3;
                    if (elementProp.Name.Contains("ProfileGraphFlag"))
                    {
                        if (pProfileElemFirst == null)
                        {
                            pProfileElemFirst = element;
                            pProfileElemPropFirst = elementProp;
                            break;
                        }

                    }
                    element = gc.Next();
                }

                for (int i = 0; i < ProfileGraph.Count; i++)
                {
                    if (pProfileElemFirst != null)
                    {
                        if (!pProfileElemPropFirst.Name.Contains(ProfileGraph[i].Network_Name))
                        {
                            //MessageBox.Show("The network (" + ProfileGraph[i].Network_Name + ") was not found, please update the config to make the name of the layer in the mxd");

                            continue;
                        }

                    }
                    bool FCorLayerManhole = true;
                    pManholeLayer = (IFeatureLayer)Globals.FindLayer(pMxDoc.FocusMap, ProfileGraph[i].Point_LayerName, ref FCorLayerManhole);

                    if (pManholeLayer == null)
                    {
                       // MessageBox.Show("The point layer (" + ProfileGraph[i].Point_LayerName + ") was not found, please update the config to make the name of the layer in the mxd");

                        continue;
                    }
                    bool FCorLayerMain = true;
                    pMainLayer = (IFeatureLayer)Globals.FindLayer(pMxDoc.FocusMap, ProfileGraph[i].Line_LayerName, ref FCorLayerMain);
                    if (pMainLayer == null)
                    {
                       // MessageBox.Show("The Main layer (" + ProfileGraph[i].Line_LayerName + ") was not found, please update the config to make the name of the layer in the mxd");

                        continue;
                    }
                    bool FCorLayerTap = true;
                    if (ProfileGraph[i].PointAlong_LayerName != "")
                    {
                        pTapLayer = (IFeatureLayer)Globals.FindLayer(pMxDoc.FocusMap, ProfileGraph[i].PointAlong_LayerName, ref FCorLayerTap);

                    }
                    else
                        pTapLayer = null;
                    // make sure a manhole was selected
                    // buffer the point by the snap tolerance, this is faster than checking
                    //the flag to see if it is on a manhole

                    pTopoOp = (ITopologicalOperator)pTracePoint;  // QI
                    snapdistnet = Globals.ConvertPixelsToMap(snapTol, pMxDoc.FocusMap);
                    pBuffGeometry = (IPolygon)pTopoOp.Buffer(snapdistnet);

                    // get the feature the user clicked to be sure it's a manhole

                    pSpatialFilter = new SpatialFilterClass();
                    pSpatialFilter.Geometry = pBuffGeometry;
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial;
                    pFeatCursor = pManholeLayer.Search(pSpatialFilter, true);

                    // there is a layer definition set to show only manholes, cursor
                    // will return nothing if user didn't click on a manhole
                    pFeature = pFeatCursor.NextFeature();

                    if (pFeature != null)
                    {
                        pMxDoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pBuffGeometry.Envelope);

                        markerelem = new MarkerElementClass();
                        markerelem.Symbol = pMarkerSym;
                        element = (IElement)markerelem;
                        element.Geometry = pFeature.ShapeCopy;
                        elementProp = element as IElementProperties3;
                        elementProp.Name = "ProfileGraphFlag-" + ProfileGraph[i].Network_Name;

                        elementProp.ReferenceScale = pMxDoc.FocusMap.ReferenceScale;
                        gc.AddElement(element, 0);

                        if (pProfileElemFirst == null)
                            return;
                        else
                        {
                            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = null;
                            ESRI.ArcGIS.esriSystem.IAnimationProgressor animationProgressor = null;
                            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
                            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
                            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
                            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = null;

                            statusBar = app.StatusBar;
                            animationProgressor = statusBar.ProgressAnimation;

                            animationProgressor.Show();
                            animationProgressor.Play(0, -1, -1);

                            statusBar.set_Message(0, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_19a"));

                            // Create a CancelTracker
                            trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                            progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                            // Set the properties of the Step Progressor
                            System.Int32 int32_hWnd = app.hWnd;
                            stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                            stepProgressor.MinRange = 0;
                            stepProgressor.MaxRange = 3;
                            stepProgressor.StepValue = 1;
                            stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_19a");

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

                            // Set the properties of the ProgressDialog
                            progressDialog2.CancelEnabled = true;
                            progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_19a");
                            progressDialog2.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_19a");
                            progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;

                            // Step. Do your big process here.
                            System.Boolean boolean_Continue = false;
                            boolean_Continue = true;

                            stepProgressor.Step();

                            GeoNetTools.TracePath(new double[] { (pProfileElemFirst.Geometry as IPoint).X, (element.Geometry as IPoint).X },
                                new double[] { (pProfileElemFirst.Geometry as IPoint).Y, (element.Geometry as IPoint).Y },
                                ProfileGraph[i].Network_Name, app, pMxDoc.FocusMap, true, snapTol, true, out juncEIDs, out edgeEIDs, out gn);
                            boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                            {
                                return;
                            }
                            stepProgressor.Step();
                            stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_19a");
                            if (juncEIDs != null && edgeEIDs != null)
                            {
                                GeoNetTools.ProfileGetRelatedElevData(app, ProfileGraph, gn, edgeEIDs, juncEIDs, i, ref pManholeLayer, ref pMainLayer, ref pTapLayer);
                            }
                            else
                            {

                            }

                            //ProfileFindPath();

                            // unpress the UIToolControl button
                            app.CurrentTool = null;
                            app.RefreshWindow();
                            progressDialog2.HideDialog();
                            progressDialog2 = null;
                            return;
                        }

                    }
                    else//Next Layer in the config
                    {
                    }

                }

                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_19a"));

            }
            catch (Exception Ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + "AddFlagsForSewerProfile " + Ex.Message);
            }
            finally
            {
                if (pFeatCursor != null)
                {
                    Marshal.ReleaseComObject(pFeatCursor);

                }
                pMxDoc.ActiveView.Refresh();
                pFeatCursor = null;
                pMxDoc = null;

                pTracePoint = null;
                pSpatialFilter = null;
                // set the symbol for the flag, red circle
                pMarkerSym = null;
                pRGBColor = null;

                pManholeLayer = null;
                pMainLayer = null;
                pTapLayer = null;
                gc = null;

                pProfileElemFirst = null;
                pProfileElemPropFirst = null;

                element = null;
                elementProp = null;
                pTopoOp = null;

                pFeature = null;

                pBuffGeometry = null;
                markerelem = null;
                gn = null;

                juncEIDs = null;
                edgeEIDs = null;
            }
        }
        //public static void SplitLinesAtClick(IApplication app, string SplitSuspendAA, double SplitAtLocationSnap, double SkipDistance, IPoint SplitPoint, bool onlySelectedFeatures, bool ignoreTolerence, bool logEditOperation)
        //{
        //    ESRI.ArcGIS.Framework.ICommandItem pCmd = null;
        //    ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
        //    ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
        //    ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
        //    ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
        //    IMxDocument mxdoc = null;
        //    IEditor editor = null;
        //    IEditLayers eLayers = null;
        //    IMap map = null;
        //    IFeatureLayer fLayer = null;
        //    IFeatureSelection fSel = null;
        //    UID geoFeatureLayerID = null;
        //    IEnumLayer enumLayer = null;
        //    ILayer layer = null;
        //    List<IFeatureLayer> lineLayers = null;
        //    IHitTest hitTest = null;
        //    ISpatialFilter pSpatFilt = null;
        //    ICursor lineCursor = null;
        //    IFeatureCursor lineFCursor = null;
        //    ITopologicalOperator topoOp = null;
        //    IPolygon poly = null;
        //    IFeatureSelection lineSel = null;
        //    IFeature lineFeature = null;
        //    IFeatureEdit2 featureEdit = null;
        //    IPoint pHitPnt = null;
        //    ITopologicalOperator topoOpEndStart = null;
        //    IPolygon polyEndStart = null;
        //    IRelationalOperator relOp = null;
        //    ICurve curve = null;
        //    List<MergeSplitGeoNetFeatures> m_Config = null;
        //    ISet pSet = null;
        //    IFeature pSplitResFeat = null;
        //    try
        //    {
        //        m_Config = ConfigUtil.GetMergeSplitConfig();
        //        if (SplitSuspendAA.ToUpper() == "TRUE")
        //        {
        //            pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
        //            if (pCmd != null)
        //            {
        //                pCmd.Execute();
        //            }
        //        }
        //        mxdoc = (IMxDocument)app.Document;
        //        editor = Globals.getEditor(app);
        //        if (editor.EditState != esriEditState.esriStateEditing)
        //        {
        //            MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_4"));
        //            return;
        //        }
        //        //Get enumeration of editable layers
        //        eLayers = (IEditLayers)editor;
        //        map = editor.Map;
        //        int i = 0;
        //        //Get enumeration of feature layers
        //        geoFeatureLayerID = new UIDClass();
        //        geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
        //        enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);
        //        layer = enumLayer.Next();
        //        // Create list of visible, editable line layers
        //        lineLayers = new List<IFeatureLayer>();
        //        enumLayer.Reset();
        //        layer = enumLayer.Next();
        //        while (!(layer == null))
        //        {
        //            fLayer = (IFeatureLayer)layer;
        //            if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
        //               && (fLayer.Visible))
        //            {
        //                if (eLayers.IsEditable(fLayer))
        //                {
        //                    if (onlySelectedFeatures)
        //                    {
        //                        fSel = (IFeatureSelection)fLayer;
        //                        if (fSel.SelectionSet.Count > 0)
        //                            lineLayers.Add(fLayer);
        //                    }
        //                    else
        //                    {
        //                        lineLayers.Add(fLayer);
        //                    }
        //                }
        //            }
        //            layer = enumLayer.Next();
        //        }
        //        //ProgressBar
        //        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
        //        // Create a CancelTracker
        //        trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
        //        // Set the properties of the Step Progressor
        //        System.Int32 int32_hWnd = app.hWnd;
        //        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
        //        stepProgressor.MinRange = 1;
        //        stepProgressor.MaxRange = 1;
        //        stepProgressor.StepValue = 1;
        //        stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_7");
        //        // Create the ProgressDialog. This automatically displays the dialog
        //        progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast
        //        // Set the properties of the ProgressDialog
        //        progressDialog.CancelEnabled = true;
        //        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_8");
        //        progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_7");
        //        progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
        //        //Create an edit operation enabling undo/redo
        //        if (logEditOperation)
        //            editor.StartOperation();
        //        try
        //        {
        //            topoOp = SplitPoint as ITopologicalOperator;
        //            if (ignoreTolerence)
        //            {
        //                poly = topoOp.Buffer(Globals.ConvertFeetToMapUnits(1, app)) as IPolygon;
        //            }
        //            else
        //            {
        //                poly = topoOp.Buffer(Globals.ConvertFeetToMapUnits(SplitAtLocationSnap, app)) as IPolygon;
        //            }
        //            foreach (IFeatureLayer lineLayer in lineLayers)
        //            {
        //                if (onlySelectedFeatures)
        //                {
        //                    lineSel = lineLayer as IFeatureSelection;
        //                    lineSel.SelectionSet.Search(null, false, out lineCursor);
        //                    lineFCursor = lineCursor as IFeatureCursor;
        //                }
        //                else
        //                {
        //                    pSpatFilt = new SpatialFilter();
        //                    pSpatFilt.GeometryField = lineLayer.FeatureClass.ShapeFieldName;
        //                    pSpatFilt.Geometry = poly;
        //                    pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
        //                    lineFCursor = lineLayer.Search(pSpatFilt, false);
        //                    //lineFCursor = lineCursor as IFeatureCursor;
        //                }
        //                IList<MergeSplitFlds> pFldsNames = new List<MergeSplitFlds>();
        //                if (m_Config.Count > 0)
        //                {
        //                    foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields)
        //                    {
        //                        int idx = Globals.GetFieldIndex(lineLayer.FeatureClass.Fields, FldNam.Name);
        //                        if (idx > -1)
        //                            pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule, FldNam.SplitRule));
        //                    }
        //                }
        //                lineFeature = lineFCursor.NextFeature();
        //                while (!(lineFeature == null))
        //                {
        //                    featureEdit = lineFeature as IFeatureEdit2;
        //                    hitTest = lineFeature.ShapeCopy as IHitTest;
        //                    pHitPnt = new PointClass();
        //                    double pHitDist = -1;
        //                    int pHitPrt = -1;
        //                    int pHitSeg = -1;
        //                    bool pHitSide = false;
        //                    bool hit = hitTest.HitTest(SplitPoint, SplitAtLocationSnap, esriGeometryHitPartType.esriGeometryPartBoundary, pHitPnt, pHitDist, pHitPrt, pHitSeg, pHitSide);
        //                    if (hit)
        //                    {
        //                        if (ignoreTolerence == true && (pHitDist == 0.0 || pHitDist == -1.0))
        //                        {
        //                            //Split feature
        //                            topoOpEndStart = pHitPnt as ITopologicalOperator;
        //                            polyEndStart = topoOpEndStart.Buffer(SkipDistance) as IPolygon;
        //                            relOp = polyEndStart as IRelationalOperator;
        //                            curve = lineFeature.Shape as ICurve;
        //                            if (!(relOp.Contains(curve.FromPoint)) &&
        //                                !(relOp.Contains(curve.ToPoint)))
        //                            {
        //                                Globals.FlashGeometry(pHitPnt, Globals.GetColor(255, 0, 0), mxdoc.ActiveView.ScreenDisplay, 150);
        //                                double dblHighVal = 0;
        //                                double dblLowVal = 0;
        //                                int intHighIdx = -1;
        //                                int intLowIdx = -1;
        //                                foreach (MergeSplitFlds FldNam in pFldsNames)
        //                                {
        //                                    FldNam.Value = lineFeature.get_Value(FldNam.FieldIndex).ToString();
        //                                    if (FldNam.SplitType.ToUpper() == "MAX")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblHighVal = Convert.ToDouble(FldNam.Value);
        //                                                intHighIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                    else if (FldNam.SplitType.ToUpper() == "MIN")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblLowVal = Convert.ToDouble(FldNam.Value);
        //                                                intLowIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                                if (intHighIdx > -1 && intLowIdx > -1)
        //                                {
        //                                    double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;
        //                                    double splitDist = Globals.PointDistanceOnLine(pHitPnt, lineFeature.Shape as IPolyline, 2, out pHitPnt);
        //                                    double percentSplit = splitDist / len;
        //                                    double dblMidVal;
        //                                    if (m_Config[0].SplitFormatString == "")
        //                                    {
        //                                        dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
        //                                    }
        //                                    else
        //                                    {
        //                                        dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));
        //                                    }
        //                                    //Split feature
        //                                    pSet = featureEdit.SplitWithUpdate(pHitPnt);
        //                                    if (pSet.Count == 1)
        //                                    {
        //                                        while ((pSplitResFeat = pSet.Next() as IFeature) != null)
        //                                        {
        //                                            if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intHighIdx, dblMidVal);
        //                                            }
        //                                            else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intLowIdx, dblMidVal);
        //                                            }
        //                                        }
        //                                    }
        //                                    if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intHighIdx, dblMidVal);
        //                                    }
        //                                    else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intLowIdx, dblMidVal);
        //                                    }
        //                                }
        //                                else
        //                                    featureEdit.SplitWithUpdate(pHitPnt);
        //                                //mxdoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, hitTest, mxdoc.ActiveView.Extent);
        //                                mxdoc.ActiveView.Refresh();
        //                                //mxdoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, curve, mxdoc.ActiveView.Extent);
        //                            }
        //                            topoOpEndStart = null;
        //                            polyEndStart = null;
        //                            relOp = null;
        //                            curve = null;
        //                        }
        //                        else if (ignoreTolerence == false)
        //                        {
        //                            //Split feature
        //                            topoOpEndStart = pHitPnt as ITopologicalOperator;
        //                            polyEndStart = topoOpEndStart.Buffer(SkipDistance) as IPolygon;
        //                            relOp = polyEndStart as IRelationalOperator;
        //                            curve = lineFeature.ShapeCopy as ICurve;
        //                            if (!(relOp.Contains(curve.FromPoint)) &&
        //                                !(relOp.Contains(curve.ToPoint)))
        //                            {
        //                                //Split feature
        //                                Globals.FlashGeometry(pHitPnt, Globals.GetColor(255, 0, 0), mxdoc.ActiveView.ScreenDisplay, 150);
        //                                double dblHighVal = 0;
        //                                double dblLowVal = 0;
        //                                int intHighIdx = -1;
        //                                int intLowIdx = -1;
        //                                foreach (MergeSplitFlds FldNam in pFldsNames)
        //                                {
        //                                    FldNam.Value = lineFeature.get_Value(FldNam.FieldIndex).ToString();
        //                                    if (FldNam.SplitType.ToUpper() == "MAX")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblHighVal = Convert.ToDouble(FldNam.Value);
        //                                                intHighIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                    else if (FldNam.SplitType.ToUpper() == "MIN")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblLowVal = Convert.ToDouble(FldNam.Value);
        //                                                intLowIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                                if (intHighIdx > -1 && intLowIdx > -1)
        //                                {
        //                                    double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;
        //                                    double splitDist = Globals.PointDistanceOnLine(pHitPnt, lineFeature.Shape as IPolyline, 2, out pHitPnt);
        //                                    double percentSplit = splitDist / len;
        //                                    double dblMidVal;
        //                                    if (m_Config[0].SplitFormatString == "")
        //                                    {
        //                                        dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
        //                                    }
        //                                    else
        //                                    {
        //                                        dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));
        //                                    }
        //                                    //Split feature
        //                                    pSet = featureEdit.SplitWithUpdate(pHitPnt);
        //                                    if (pSet.Count == 1)
        //                                    {
        //                                        while ((pSplitResFeat = pSet.Next() as IFeature) != null)
        //                                        {
        //                                            if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intHighIdx, dblMidVal);
        //                                            }
        //                                            else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intLowIdx, dblMidVal);
        //                                            }
        //                                        }
        //                                    }
        //                                    if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intHighIdx, dblMidVal);
        //                                    }
        //                                    else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intLowIdx, dblMidVal);
        //                                    }
        //                                }
        //                                else
        //                                    featureEdit.SplitWithUpdate(pHitPnt);
        //                            }
        //                            topoOpEndStart = null;
        //                            polyEndStart = null;
        //                            relOp = null;
        //                            curve = null;
        //                        }
        //                    }
        //                    if (lineFeature != null)
        //                    {
        //                        System.Runtime.InteropServices.Marshal.ReleaseComObject(lineFeature);
        //                    }
        //                    lineFeature = lineFCursor.NextFeature();
        //                }
        //                if (lineCursor != null)
        //                {
        //                    System.Runtime.InteropServices.Marshal.ReleaseComObject(lineCursor);
        //                }
        //                System.Runtime.InteropServices.Marshal.ReleaseComObject(lineFCursor);
        //            }
        //            //Update progress bar
        //            i += 1;
        //            progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_8");
        //            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
        //            statusBar.set_Message(0, i.ToString());
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1"));
        //            if (logEditOperation)
        //                editor.AbortOperation();
        //            return;
        //        }
        //        finally
        //        {
        //            mxdoc.ActiveView.Refresh();
        //            progressDialog.HideDialog();
        //        }
        //        //Stop the edit operation
        //        if (logEditOperation)
        //            editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9"));
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1"));
        //        return;
        //    }
        //    finally
        //    {
        //        if (progressDialog != null)
        //            progressDialog.HideDialog();
        //        if (SplitSuspendAA.ToUpper() == "TRUE")
        //        {
        //            pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
        //            if (pCmd != null)
        //            {
        //                pCmd.Execute();
        //            }
        //        }
        //        pCmd = null;
        //        progressDialog = null;
        //        progressDialogFactory = null;
        //        trackCancel = null;
        //        stepProgressor = null;
        //        mxdoc = null;
        //        editor = null;
        //        eLayers = null;
        //        map = null;
        //        fLayer = null;
        //        fSel = null;
        //        geoFeatureLayerID = null;
        //        enumLayer = null;
        //        layer = null;
        //        lineLayers = null;
        //        hitTest = null;
        //        pSpatFilt = null;
        //        lineCursor = null;
        //        lineFCursor = null;
        //        topoOp = null;
        //        poly = null;
        //        lineSel = null;
        //        lineFeature = null;
        //        featureEdit = null;
        //        pHitPnt = null;
        //        topoOpEndStart = null;
        //        polyEndStart = null;
        //        relOp = null;
        //        curve = null;
        //    }
        //}
        //public static void SplitLines(IApplication app, string SplitSuspendAA, double SplitAtLocationSnap, double SkipDistance)
        //{
        //    IProgressDialogFactory progressDialogFactory = null;
        //    ITrackCancel trackCancel = null;
        //    IStepProgressor stepProgressor = null;
        //    IProgressDialog2 progressDialog = null;
        //    ICommandItem pCmd = null;
        //    IEditLayers eLayers = null;
        //    IEditor editor = null;
        //    IMxDocument mxdoc = null;
        //    IMap map = null;
        //    IFeatureLayer fLayer = null;
        //    IFeatureSelection fSel = null;
        //    UID geoFeatureLayerID = null;
        //    IEnumLayer enumLayer = null;
        //    List<IFeatureLayer> pointLayers = null;
        //    ILayer layer = null;
        //    List<IFeatureLayer> lineLayers;
        //    List<MergeSplitGeoNetFeatures> m_Config = null;
        //    IPoint pSplitPnt = null;
        //    ISet pSet = null;
        //    IFeature pSplitResFeat = null;
        //    try
        //    {
        //        m_Config = ConfigUtil.GetMergeSplitConfig();
        //        if (SplitSuspendAA.ToUpper() == "TRUE")
        //        {
        //            pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
        //            if (pCmd != null)
        //            {
        //                pCmd.Execute();
        //            }
        //        }
        //        editor = Globals.getEditor(app);
        //        if (editor.EditState != esriEditState.esriStateEditing)
        //        {
        //            MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
        //            return;
        //        }
        //        //Get enumeration of editable layers
        //        eLayers = (IEditLayers)editor;
        //        mxdoc = (IMxDocument)app.Document;
        //        map = editor.Map;
        //        int i = 0;
        //        int total = 0;
        //        //Get enumeration of feature layers
        //        geoFeatureLayerID = new UIDClass();
        //        geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
        //        enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);
        //        // Create list of visible point layers with selected feature(s)
        //        pointLayers = new List<IFeatureLayer>();
        //        lineLayers = new List<IFeatureLayer>();
        //        enumLayer.Reset();
        //        layer = enumLayer.Next();
        //        while (layer != null)
        //        {
        //            fLayer = (IFeatureLayer)layer;
        //            if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
        //               && (fLayer.Visible))
        //            {
        //                fSel = fLayer as IFeatureSelection;
        //                if (fSel.SelectionSet.Count > 0)
        //                {
        //                    total += fSel.SelectionSet.Count;
        //                    pointLayers.Add(fLayer);
        //                }
        //            }
        //            else if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
        //                && (fLayer.Visible))
        //            {
        //                if (eLayers.IsEditable(fLayer))
        //                    lineLayers.Add(fLayer);
        //            }
        //            layer = enumLayer.Next();
        //        }
        //        //ProgressBar
        //        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
        //        // Create a CancelTracker
        //        trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
        //        // Set the properties of the Step Progressor
        //        System.Int32 int32_hWnd = app.hWnd;
        //        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
        //        stepProgressor.MinRange = 0;
        //        stepProgressor.MaxRange = total;
        //        stepProgressor.StepValue = 1;
        //        stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_10");
        //        // Create the ProgressDialog. This automatically displays the dialog
        //        progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor;
        //        // Set the properties of the ProgressDialog
        //        progressDialog.CancelEnabled = true;
        //        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
        //        progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9");
        //        progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
        //        //Create an edit operation enabling undo/redo
        //        editor.StartOperation();
        //        ICursor pointCursor = null;
        //        IFeatureSelection pointSel = null;
        //        IFeature pointFeature = null;
        //        ISpatialFilter sFilter = null;
        //        IFeatureSelection lineSel = null;
        //        IFeatureCursor lineCursor = null;
        //        IFeature lineFeature = null;
        //        IFeatureEdit2 featureEdit = null;
        //        //Determine if point is at end of this line (if so skip)
        //        ITopologicalOperator topoOp = null;
        //        IPolygon poly = null;
        //        IRelationalOperator relOp = null;
        //        ICurve curve = null;
        //        try
        //        {
        //            // step through all points and split the lines that intersect them
        //            foreach (IFeatureLayer pointLayer in pointLayers)
        //            {
        //                pointSel = pointLayer as IFeatureSelection;
        //                pointSel.SelectionSet.Search(null, false, out pointCursor);
        //                pointFeature = pointCursor.NextRow() as IFeature;
        //                while (!(pointFeature == null))
        //                {
        //                    foreach (IFeatureLayer lineLayer in lineLayers)
        //                    {
        //                        sFilter = new SpatialFilterClass();
        //                        sFilter.Geometry = pointFeature.ShapeCopy;
        //                        sFilter.GeometryField = lineLayer.FeatureClass.ShapeFieldName;
        //                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
        //                        lineSel = lineLayer as IFeatureSelection;
        //                        lineCursor = lineLayer.Search(sFilter, false);
        //                        lineFeature = lineCursor.NextFeature();
        //                        IList<MergeSplitFlds> pFldsNames = new List<MergeSplitFlds>();
        //                        if (m_Config.Count > 0)
        //                        {
        //                            foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields)
        //                            {
        //                                int idx = Globals.GetFieldIndex(lineLayer.FeatureClass.Fields, FldNam.Name);
        //                                if (idx > -1)
        //                                    pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule,FldNam.SplitRule));
        //                            }
        //                        }
        //                        while (!(lineFeature == null))
        //                        {
        //                            featureEdit = lineFeature as IFeatureEdit2;
        //                            //Determine if point is at end of this line (if so skip)
        //                            topoOp = pointFeature.Shape as ITopologicalOperator;
        //                            poly = topoOp.Buffer(SkipDistance) as IPolygon;
        //                            relOp = poly as IRelationalOperator;
        //                            curve = lineFeature.Shape as ICurve;
        //                            if (!(relOp.Contains(curve.FromPoint)) &
        //                                !(relOp.Contains(curve.ToPoint)))
        //                            {
        //                                 pSplitPnt = pointFeature.ShapeCopy as IPoint;
        //                                 double dblHighVal = 0;
        //                                 double dblLowVal = 0;
        //                                 int intHighIdx = -1;
        //                                 int intLowIdx = -1;
        //                                foreach (MergeSplitFlds FldNam in pFldsNames)
        //                                {
        //                                    FldNam.Value= lineFeature.get_Value(FldNam.FieldIndex).ToString();
        //                                    if (FldNam.SplitType.ToUpper() == "MAX")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblHighVal = Convert.ToDouble(FldNam.Value);
        //                                                intHighIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                    else if (FldNam.SplitType.ToUpper() == "MIN")
        //                                    {
        //                                        if (FldNam.Value != null)
        //                                        {
        //                                            if (FldNam.Value != "")
        //                                            {
        //                                                dblLowVal = Convert.ToDouble(FldNam.Value);
        //                                                intLowIdx = FldNam.FieldIndex;
        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                                if (intHighIdx > -1 && intLowIdx > -1)
        //                                {
        //                                    double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;
        //                                    double splitDist = Globals.PointDistanceOnLine(pSplitPnt, lineFeature.Shape as IPolyline, 2, out pSplitPnt);
        //                                    double percentSplit = splitDist / len;
        //                                    double dblMidVal;
        //                                    if (m_Config[0].SplitFormatString == "")
        //                                    {
        //                                        dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
        //                                    }
        //                                    else
        //                                    {
        //                                        dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));
        //                                    }
        //                                    //Split feature
        //                                    pSet = featureEdit.SplitWithUpdate(pSplitPnt);
        //                                    if (pSet.Count == 1)
        //                                    {
        //                                        while ((pSplitResFeat = pSet.Next() as IFeature) != null)
        //                                        {
        //                                            if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intHighIdx, dblMidVal);
        //                                            }
        //                                            else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y)
        //                                            {
        //                                                pSplitResFeat.set_Value(intLowIdx, dblMidVal);
        //                                            }
        //                                        }
        //                                    }
        //                                    if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intHighIdx, dblMidVal);
        //                                    }
        //                                    else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y)
        //                                    {
        //                                        lineFeature.set_Value(intLowIdx, dblMidVal);
        //                                    }
        //                                }else
        //                                    pSet = featureEdit.SplitWithUpdate(pSplitPnt);
        //                                pSplitPnt = null;
        //                            }
        //                            lineFeature = lineCursor.NextFeature();
        //                        }
        //                        System.Runtime.InteropServices.Marshal.ReleaseComObject(lineCursor);
        //                    }
        //                    //Update progress bar
        //                    i += 1;
        //                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
        //                    stepProgressor.Step();
        //                    ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
        //                    statusBar.set_Message(0, i.ToString());
        //                    //Check if the cancel button was pressed. If so, stop process
        //                    if (!trackCancel.Continue())
        //                    {
        //                        break;
        //                    }
        //                    pointFeature = (IFeature)pointCursor.NextRow();
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            editor.AbortOperation();
        //            MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
        //            return;
        //        }
        //        finally
        //        {
        //            if (pointCursor != null)
        //            {
        //                System.Runtime.InteropServices.Marshal.ReleaseComObject(pointCursor);
        //            }
        //            pointCursor = null;
        //            pointSel = null;
        //            pointFeature = null;
        //            sFilter = null;
        //            lineSel = null;
        //            lineCursor = null;
        //            lineFeature = null;
        //            featureEdit = null;
        //            topoOp = null;
        //            poly = null;
        //            relOp = null;
        //            curve = null;
        //        }
        //        progressDialog.HideDialog();
        //        //Stop the edit operation
        //        editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9"));
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
        //        return;
        //    }
        //    finally
        //    {
        //        pSet = null;
        //        pSplitPnt = null;
        //        if (SplitSuspendAA.ToUpper() == "TRUE")
        //        {
        //            pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
        //            if (pCmd != null)
        //            {
        //                pCmd.Execute();
        //            }
        //            pCmd = null;
        //        }
        //        if (progressDialog != null)
        //            progressDialog.HideDialog();
        //        progressDialogFactory = null;
        //        trackCancel = null;
        //        stepProgressor = null;
        //        progressDialog = null;
        //        pCmd = null;
        //        eLayers = null;
        //        editor = null;
        //        mxdoc = null;
        //        map = null;
        //        fLayer = null;
        //        fSel = null;
        //        geoFeatureLayerID = null;
        //        enumLayer = null;
        //        pointLayers = null;
        //        layer = null;
        //        lineLayers = null;
        //        pSplitResFeat = null;
        //    }
        //}
        public static void SplitLinesAtClick(IApplication app, string SplitSuspendAA, double SplitAtLocationSnap, double SkipDistance, IPoint SplitPoint, bool onlySelectedFeatures, bool ignoreTolerence, bool logEditOperation)
        {
            ESRI.ArcGIS.Framework.ICommandItem pCmd = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            IMxDocument mxdoc = null;
            IEditor editor = null;
            IEditLayers eLayers = null;
            IMap map = null;
            IFeatureLayer fLayer = null;
            IFeatureSelection fSel = null;
            UID geoFeatureLayerID = null;
            IEnumLayer enumLayer = null;
            ILayer layer = null;
            List<IFeatureLayer> lineLayers = null;

            ISpatialFilter pSpatFilt = null;
            ICursor lineCursor = null;
            IFeatureCursor lineFCursor = null;
            ITopologicalOperator topoOp = null;

            IPolygon poly = null;
            IFeatureSelection lineSel = null;
            IFeature lineFeature = null;

            List<MergeSplitGeoNetFeatures> m_Config = null;

            //IHitTest hitTest = null;
            //IFeatureEdit2 featureEdit = null;

            //IPoint pHitPnt = null;
            //ITopologicalOperator topoOpEndStart = null;
            //IPolygon polyEndStart = null;
            //IRelationalOperator relOp = null;
            //ICurve curve = null;
            //ISet pSet = null;
            //IFeature pSplitResFeat = null;

            try
            {
                m_Config = ConfigUtil.GetMergeSplitConfig();

                if (SplitSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                }
                mxdoc = (IMxDocument)app.Document;
                editor = Globals.getEditor(app);

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_4"));
                    return;
                }

                //Get enumeration of editable layers
                eLayers = (IEditLayers)editor;

                map = editor.Map;

                int i = 0;

                //Get enumeration of feature layers
                geoFeatureLayerID = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                layer = enumLayer.Next();

                // Create list of visible, editable line layers
                lineLayers = new List<IFeatureLayer>();
                enumLayer.Reset();
                layer = enumLayer.Next();
                while (!(layer == null))
                {
                    fLayer = (IFeatureLayer)layer;
                    if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
                       && (fLayer.Visible))
                    {
                        if (eLayers.IsEditable(fLayer))
                        {
                            if (onlySelectedFeatures)
                            {
                                fSel = (IFeatureSelection)fLayer;
                                if (fSel.SelectionSet.Count > 0)
                                    lineLayers.Add(fLayer);
                            }
                            else
                            {
                                lineLayers.Add(fLayer);
                            }
                        }
                    }
                    layer = enumLayer.Next();
                }

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

                // Create a CancelTracker
                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = app.hWnd;
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                stepProgressor.MinRange = 1;
                stepProgressor.MaxRange = 1;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_7");

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

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_8");
                progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_7");
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;

                //Create an edit operation enabling undo/redo
                if (logEditOperation)
                    editor.StartOperation();

                try
                {

                    topoOp = SplitPoint as ITopologicalOperator;
                    if (ignoreTolerence)
                    {
                        poly = topoOp.Buffer(Globals.ConvertFeetToMapUnits(.1, app)) as IPolygon;
                    }
                    else
                    {
                        poly = topoOp.Buffer(Globals.ConvertFeetToMapUnits(SplitAtLocationSnap, app)) as IPolygon;
                    }
                    foreach (IFeatureLayer lineLayer in lineLayers)
                    {

                        if (onlySelectedFeatures)
                        {
                            lineSel = lineLayer as IFeatureSelection;
                            lineSel.SelectionSet.Search(null, false, out lineCursor);
                            lineFCursor = lineCursor as IFeatureCursor;

                        }
                        else
                        {
                            pSpatFilt = new SpatialFilter();
                            pSpatFilt.GeometryField = lineLayer.FeatureClass.ShapeFieldName;
                            pSpatFilt.Geometry = poly;
                            pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                            lineFCursor = lineLayer.Search(pSpatFilt, false);
                            //lineFCursor = lineCursor as IFeatureCursor;
                        }

                        IList<MergeSplitFlds> pFldsNames = new List<MergeSplitFlds>();
                        string strFormValu = "{0:0.##}";
                        if (m_Config.Count > 0)
                        {
                            foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields)
                            {
                                int idx = Globals.GetFieldIndex(lineLayer.FeatureClass.Fields, FldNam.Name);
                                if (idx > -1)
                                    pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule, FldNam.SplitRule));

                            }
                            strFormValu = m_Config[0].SplitFormatString;
                        }

                        lineFeature = lineFCursor.NextFeature();
                        while (!(lineFeature == null))
                        {
                            Globals.splitLineWithPoint(lineFeature, SplitPoint, SplitAtLocationSnap, pFldsNames, strFormValu,app);
                            //featureEdit = lineFeature as IFeatureEdit2;
                            //hitTest = lineFeature.ShapeCopy as IHitTest;
                            //pHitPnt = new PointClass();
                            //double pHitDist = -1;
                            //int pHitPrt = -1;
                            //int pHitSeg = -1;
                            //bool pHitSide = false;
                            //bool hit = hitTest.HitTest(SplitPoint, SplitAtLocationSnap, esriGeometryHitPartType.esriGeometryPartBoundary, pHitPnt, pHitDist, pHitPrt, pHitSeg, pHitSide);

                            //if (hit)
                            //{
                            //    if (ignoreTolerence == true && (pHitDist == 0.0 || pHitDist == -1.0))
                            //    {

                            //        //Split feature
                            //        topoOpEndStart = pHitPnt as ITopologicalOperator;
                            //        polyEndStart = topoOpEndStart.Buffer(SkipDistance) as IPolygon;
                            //        relOp = polyEndStart as IRelationalOperator;
                            //        curve = lineFeature.Shape as ICurve;
                            //        if (!(relOp.Contains(curve.FromPoint)) &&
                            //            !(relOp.Contains(curve.ToPoint)))
                            //        {
                            //            Globals.FlashGeometry(pHitPnt, Globals.GetColor(255, 0, 0), mxdoc.ActiveView.ScreenDisplay, 150);

                            //            double dblHighVal = 0;
                            //            double dblLowVal = 0;
                            //            int intHighIdx = -1;
                            //            int intLowIdx = -1;
                            //            foreach (MergeSplitFlds FldNam in pFldsNames)
                            //            {
                            //                FldNam.Value = lineFeature.get_Value(FldNam.FieldIndex).ToString();
                            //                if (FldNam.SplitType.ToUpper() == "MAX")
                            //                {
                            //                    if (FldNam.Value != null)
                            //                    {
                            //                        if (FldNam.Value != "")
                            //                        {

                            //                            dblHighVal = Convert.ToDouble(FldNam.Value);
                            //                            intHighIdx = FldNam.FieldIndex;
                            //                        }
                            //                    }
                            //                }
                            //                else if (FldNam.SplitType.ToUpper() == "MIN")
                            //                {
                            //                    if (FldNam.Value != null)
                            //                    {
                            //                        if (FldNam.Value != "")
                            //                        {

                            //                            dblLowVal = Convert.ToDouble(FldNam.Value);
                            //                            intLowIdx = FldNam.FieldIndex;
                            //                        }
                            //                    }
                            //                }

                            //            }
                            //            if (intHighIdx > -1 && intLowIdx > -1)
                            //            {
                            //                double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;

                            //                double splitDist = Globals.PointDistanceOnLine(pHitPnt, lineFeature.Shape as IPolyline, 2, out pHitPnt);
                            //                double percentSplit = splitDist / len;
                            //                double dblMidVal;
                            //                if (m_Config[0].SplitFormatString == "")
                            //                {
                            //                    dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
                            //                }
                            //                else
                            //                {
                            //                    dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));

                            //                }

                            //                //Split feature
                            //                pSet = featureEdit.SplitWithUpdate(pHitPnt);

                            //                if (pSet.Count == 1)
                            //                {
                            //                    while ((pSplitResFeat = pSet.Next() as IFeature) != null)
                            //                    {
                            //                        if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
                            //                        {
                            //                            pSplitResFeat.set_Value(intHighIdx, dblMidVal);
                            //                        }
                            //                        else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
                            //                        {
                            //                            pSplitResFeat.set_Value(intLowIdx, dblMidVal);

                            //                        }
                            //                    }

                            //                }
                            //                if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
                            //                {
                            //                    lineFeature.set_Value(intHighIdx, dblMidVal);
                            //                }
                            //                else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
                            //                {
                            //                    lineFeature.set_Value(intLowIdx, dblMidVal);

                            //                }
                            //            }
                            //            else
                            //                featureEdit.SplitWithUpdate(pHitPnt);

                            //            //mxdoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, hitTest, mxdoc.ActiveView.Extent);
                            //            mxdoc.ActiveView.Refresh();

                            //            //mxdoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, curve, mxdoc.ActiveView.Extent);
                            //        }

                            //        topoOpEndStart = null;
                            //        polyEndStart = null;
                            //        relOp = null;
                            //        curve = null;

                            //    }
                            //    else if (ignoreTolerence == false)
                            //    {

                            //        //Split feature
                            //        topoOpEndStart = pHitPnt as ITopologicalOperator;
                            //        polyEndStart = topoOpEndStart.Buffer(SkipDistance) as IPolygon;
                            //        relOp = polyEndStart as IRelationalOperator;
                            //        curve = lineFeature.ShapeCopy as ICurve;
                            //        if (!(relOp.Contains(curve.FromPoint)) &&
                            //            !(relOp.Contains(curve.ToPoint)))
                            //        {
                            //            //Split feature
                            //            Globals.FlashGeometry(pHitPnt, Globals.GetColor(255, 0, 0), mxdoc.ActiveView.ScreenDisplay, 150);

                            //            double dblHighVal = 0;
                            //            double dblLowVal = 0;
                            //            int intHighIdx = -1;
                            //            int intLowIdx = -1;
                            //            foreach (MergeSplitFlds FldNam in pFldsNames)
                            //            {
                            //                FldNam.Value = lineFeature.get_Value(FldNam.FieldIndex).ToString();
                            //                if (FldNam.SplitType.ToUpper() == "MAX")
                            //                {
                            //                    if (FldNam.Value != null)
                            //                    {
                            //                        if (FldNam.Value != "")
                            //                        {

                            //                            dblHighVal = Convert.ToDouble(FldNam.Value);
                            //                            intHighIdx = FldNam.FieldIndex;
                            //                        }
                            //                    }
                            //                }
                            //                else if (FldNam.SplitType.ToUpper() == "MIN")
                            //                {
                            //                    if (FldNam.Value != null)
                            //                    {
                            //                        if (FldNam.Value != "")
                            //                        {

                            //                            dblLowVal = Convert.ToDouble(FldNam.Value);
                            //                            intLowIdx = FldNam.FieldIndex;
                            //                        }
                            //                    }
                            //                }

                            //            }
                            //            if (intHighIdx > -1 && intLowIdx > -1)
                            //            {
                            //                double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;

                            //                double splitDist = Globals.PointDistanceOnLine(pHitPnt, lineFeature.Shape as IPolyline, 2, out pHitPnt);
                            //                double percentSplit = splitDist / len;
                            //                double dblMidVal;
                            //                if (m_Config[0].SplitFormatString == "")
                            //                {
                            //                    dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
                            //                }
                            //                else
                            //                {
                            //                    dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));

                            //                }

                            //                //Split feature
                            //                pSet = featureEdit.SplitWithUpdate(pHitPnt);

                            //                if (pSet.Count == 1)
                            //                {
                            //                    while ((pSplitResFeat = pSet.Next() as IFeature) != null)
                            //                    {
                            //                        if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
                            //                        {
                            //                            pSplitResFeat.set_Value(intHighIdx, dblMidVal);
                            //                        }
                            //                        else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
                            //                        {
                            //                            pSplitResFeat.set_Value(intLowIdx, dblMidVal);

                            //                        }
                            //                    }

                            //                }
                            //                if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pHitPnt.Y)
                            //                {
                            //                    lineFeature.set_Value(intHighIdx, dblMidVal);
                            //                }
                            //                else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pHitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pHitPnt.Y)
                            //                {
                            //                    lineFeature.set_Value(intLowIdx, dblMidVal);

                            //                }
                            //            }
                            //            else
                            //                featureEdit.SplitWithUpdate(pHitPnt);
                            //        }

                            //        topoOpEndStart = null;
                            //        polyEndStart = null;
                            //        relOp = null;
                            //        curve = null;

                            //    }
                            //}
                            if (lineFeature != null)
                            {
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(lineFeature);
                            }
                            lineFeature = lineFCursor.NextFeature();
                        }
                        if (lineCursor != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(lineCursor);
                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(lineFCursor);

                    }

                    //Update progress bar
                    i += 1;
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_8");
                    ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
                    statusBar.set_Message(0, i.ToString());
                }
                catch (Exception ex)
                {

                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1"));
                    if (logEditOperation)
                        editor.AbortOperation();

                    return;
                }
                finally
                {
                    progressDialog.HideDialog();

                }

                //Stop the edit operation
                if (logEditOperation)
                    editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9"));

            }
            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsRealName_1"));
                return;
            }
            finally
            {

                if (progressDialog != null)
                    progressDialog.HideDialog();
                if (SplitSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                }
                pCmd = null;
                progressDialog = null;
                progressDialogFactory = null;
                trackCancel = null;
                stepProgressor = null;
                mxdoc = null;
                editor = null;
                eLayers = null;
                map = null;
                fLayer = null;
                fSel = null;
                geoFeatureLayerID = null;
                enumLayer = null;
                layer = null;
                lineLayers = null;

                pSpatFilt = null;
                lineCursor = null;
                lineFCursor = null;
                topoOp = null;

                poly = null;
                lineSel = null;
                lineFeature = null;
                //featureEdit = null;
                //hitTest = null;
                //pHitPnt = null;
                //topoOpEndStart = null;
                //polyEndStart = null;
                //relOp = null;
                //curve = null;

            }
        }
        private void btnSelect_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ISpatialFilter pSpatFilt = null;
            IFeatureLayer pFL = null;
              IFeatureCursor pFCurs = null;
              IFeature pFeat = null;
              ISimpleJunctionFeature pSimpFeat = null;
            // Create an edit operation enabling undo/redo
            try
            {
                (_app.Document as IMxDocument).FocusMap.ClearSelection();

                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;
                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                stepProgressor.MinRange = 0;
                stepProgressor.MaxRange = lstJunctionLayers.Items.Count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                for (int i = 0; i < lstJunctionLayers.Items.Count; i++)
                {
                    bool boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_2") + lstJunctionLayers.Items[i].ToString();
                    if (lstJunctionLayers.GetItemCheckState(i) == CheckState.Checked)
                    {
                        bool FCorLayer = true;
                        pFL = (IFeatureLayer)Globals.FindLayer(_app, lstJunctionLayers.Items[i].ToString(), ref FCorLayer);
                        if (pFL != null)
                        {
                            pSpatFilt = new SpatialFilterClass();
                            pSpatFilt.Geometry = _env as IGeometry;
                            pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                            pSpatFilt.GeometryField = pFL.FeatureClass.ShapeFieldName;
                            int featCnt = pFL.FeatureClass.FeatureCount(pSpatFilt);

                            if (featCnt > 0)
                            {
                                pFCurs = pFL.Search(pSpatFilt, true);
                                 pFeat = pFCurs.NextFeature();
                                int loopCnt = 1;

                                while (pFeat != null)
                                {
                                     boolean_Continue = trackCancel.Continue();
                                    if (!boolean_Continue)
                                    {
                                        return;
                                    }
                                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_3") + loopCnt + A4LGSharedFunctions.Localizer.GetString("Of") + featCnt;

                                    if (pFeat is SimpleJunctionFeature)
                                    {

                                        pSimpFeat = (ISimpleJunctionFeature)pFeat;
                                        if (pSimpFeat.EdgeFeatureCount >= numMinEdge.Value && pSimpFeat.EdgeFeatureCount <= numMaxEdge.Value)
                                        {
                                            (_app.Document as IMxDocument).FocusMap.SelectFeature(pFL as ILayer, pFeat);

                                        }
                                    }
                                    loopCnt++;
                                    pFeat = pFCurs.NextFeature();
                                }
                            }
                        }
                    }
                    stepProgressor.Step();

                }

            }
            catch (Exception Ex)

            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("SltByJctCountLbl_22") + "\r\n" + Ex.Message);

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

                }

                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                trackCancel = null;
                pSpatFilt = null;
                pFL = null;
                if (pFCurs != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFCurs);
                }
                pFCurs = null;
                pFeat = null;
                pSimpFeat = null;
                this.Hide();
                (_app.Document as IMxDocument).ActiveView.Refresh();

                MessageBox.Show((_app.Document as IMxDocument).FocusMap.SelectionCount + A4LGSharedFunctions.Localizer.GetString("SltByJctCountMess_1"));

            }
        }
Exemple #8
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor       stepProgressor        = null;
            ESRI.ArcGIS.Framework.IProgressDialog2       progressDialog        = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ISpatialFilter         pSpatFilt = null;
            IFeatureLayer          pFL       = null;
            IFeatureCursor         pFCurs    = null;
            IFeature               pFeat     = null;
            ISimpleJunctionFeature pSimpFeat = null;

            // Create an edit operation enabling undo/redo
            try
            {
                (_app.Document as IMxDocument).FocusMap.ClearSelection();


                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;
                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor        = progressDialogFactory.Create(trackCancel, int32_hWnd);

                stepProgressor.MinRange  = 0;
                stepProgressor.MaxRange  = lstJunctionLayers.Items.Count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description   = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Title         = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();


                for (int i = 0; i < lstJunctionLayers.Items.Count; i++)
                {
                    bool boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_2") + lstJunctionLayers.Items[i].ToString();
                    if (lstJunctionLayers.GetItemCheckState(i) == CheckState.Checked)
                    {
                        bool FCorLayer = true;
                        pFL = (IFeatureLayer)Globals.FindLayer(_app, lstJunctionLayers.Items[i].ToString(), ref FCorLayer);
                        if (pFL != null)
                        {
                            pSpatFilt               = new SpatialFilterClass();
                            pSpatFilt.Geometry      = _env as IGeometry;
                            pSpatFilt.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects;
                            pSpatFilt.GeometryField = pFL.FeatureClass.ShapeFieldName;
                            int featCnt = pFL.FeatureClass.FeatureCount(pSpatFilt);

                            if (featCnt > 0)
                            {
                                pFCurs = pFL.Search(pSpatFilt, true);
                                pFeat  = pFCurs.NextFeature();
                                int loopCnt = 1;

                                while (pFeat != null)
                                {
                                    boolean_Continue = trackCancel.Continue();
                                    if (!boolean_Continue)
                                    {
                                        return;
                                    }
                                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_3") + loopCnt + A4LGSharedFunctions.Localizer.GetString("Of") + featCnt;

                                    if (pFeat is SimpleJunctionFeature)
                                    {
                                        pSimpFeat = (ISimpleJunctionFeature)pFeat;
                                        if (pSimpFeat.EdgeFeatureCount >= numMinEdge.Value && pSimpFeat.EdgeFeatureCount <= numMaxEdge.Value)
                                        {
                                            (_app.Document as IMxDocument).FocusMap.SelectFeature(pFL as ILayer, pFeat);
                                        }
                                    }
                                    loopCnt++;
                                    pFeat = pFCurs.NextFeature();
                                }
                            }
                        }
                    }
                    stepProgressor.Step();
                }
            }
            catch (Exception Ex)

            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("SltByJctCountLbl_22") + "\r\n" + Ex.Message);
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }

                progressDialogFactory = null;
                stepProgressor        = null;
                progressDialog        = null;
                trackCancel           = null;
                pSpatFilt             = null;
                pFL = null;
                if (pFCurs != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFCurs);
                }
                pFCurs    = null;
                pFeat     = null;
                pSimpFeat = null;
                this.Hide();
                (_app.Document as IMxDocument).ActiveView.Refresh();

                MessageBox.Show((_app.Document as IMxDocument).FocusMap.SelectionCount + A4LGSharedFunctions.Localizer.GetString("SltByJctCountMess_1"));
            }
        }
Exemple #9
0
        public void ExportSelectedRecordsToExcel()
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor       stepProgressor        = null;
            ESRI.ArcGIS.Framework.IProgressDialog2       progressDialog        = null;
            IMxDocument mxdoc = null;
            IMap        map   = null;
            IStandaloneTableCollection standTabColl = null;
            IStandaloneTable           standTable   = null;
            ITableSelection            tableSel     = null;
            IEnumFeature      enumFeat  = null;
            IFeature          feat      = null;
            IFeatureSelection featSel   = null;
            ITable            openTable = null;
            object            missing   = null;
            //object fileName = null;
            object newTemplate = null;
            object docType     = null;
            object isVisible   = null;


            UID geoFeatureLayerID = null;

            IEnumLayer    enumLayer = null;
            IFeatureLayer featlayer = null;

            try
            {
                mxdoc = (IMxDocument)_app.Document;
                map   = mxdoc.FocusMap;

                long standTableCnt;
                int  i = 0;
                bool selectionInTable = false;


                missing = System.Reflection.Missing.Value;
                // fileName = "normal.dot";
                newTemplate = false;
                docType     = 0;
                isVisible   = true;

                //Get enumeration of feature layers
                geoFeatureLayerID       = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(geoFeatureLayerID, true);

                enumLayer.Reset();

                standTabColl  = (IStandaloneTableCollection)map;
                standTableCnt = standTabColl.StandaloneTableCount;

                enumFeat = (IEnumFeature)map.FeatureSelection;
                enumFeat.Reset();
                feat = enumFeat.Next();



                if (standTableCnt > 0)
                {
                    for (int j = 0; j < standTableCnt; j++)
                    {
                        standTable = standTabColl.get_StandaloneTable(j);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                selectionInTable = true;
                                break;
                            }
                        }
                    }
                }

                if ((selectionInTable == false) && (feat == null))
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("DataToolsMess_1") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("DataToolsMess_2"), messageBoxHeader);
                    return;
                }
                // Create a CancelTracker
                ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;

                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor        = progressDialogFactory.Create(trackCancel, int32_hWnd);



                stepProgressor.MinRange  = 0;
                stepProgressor.MaxRange  = mxdoc.FocusMap.SelectionCount;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description   = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + "1" + A4LGSharedFunctions.Localizer.GetString("Of") + mxdoc.FocusMap.SelectionCount.ToString() + ".";
                progressDialog.Title         = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                if ((feat != null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();


                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }

                    featlayer = (IFeatureLayer)enumLayer.Next();
                    while (featlayer != null)
                    {
                        if ((featlayer.Valid) && (featlayer.Selectable))
                        {
                            featSel = (IFeatureSelection)featlayer;
                            if (featSel.SelectionSet.Count > 0)
                            {
                                if (ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                        featlayer = (IFeatureLayer)enumLayer.Next();
                    }

                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                if (ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
                else if ((feat != null) && (selectionInTable == false))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }


                    ILayer pTLay = enumLayer.Next();
                    while (pTLay != null)
                    {
                        if (pTLay is IFeatureLayer)
                        {
                            featlayer = (IFeatureLayer)pTLay;
                            if ((featlayer.Valid))
                            {
                                featSel = (IFeatureSelection)featlayer;
                                if (featSel.SelectionSet.Count > 0)
                                {
                                    if (ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                        pTLay = enumLayer.Next();
                    }
                    pTLay = null;
                }
                else if ((feat == null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }
                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                if (ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }


                if (objBook.Sheets.Count > 1)
                {
                    objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1);
                    objSheet.Delete();
                }
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet2"];
                //objSheet.Delete();
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet3"];
                //objSheet.Delete();
                ExcelApp.DisplayAlerts = true;

                //Make the first sheet active
                objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1) as Excel.Worksheet;
                (objSheet as Microsoft.Office.Interop.Excel._Worksheet).Activate();

                //Make Excel visible
                ExcelApp.Visible = true;
                return;
            }
            catch (Exception ex)
            {
                if (ExcelApp != null)
                {
                    ExcelApp = null;
                }

                //ExcelApp.Visible = true;
                MessageBox.Show("ExportSelectedRecordsToExcel\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }

                progressDialogFactory = null;
                stepProgressor        = null;
                progressDialog        = null;
                mxdoc        = null;
                map          = null;
                standTabColl = null;
                standTable   = null;
                tableSel     = null;
                enumFeat     = null;
                feat         = null;
                featSel      = null;
                openTable    = null;
                missing      = null;
                //fileName = null;
                newTemplate = null;
                docType     = null;
                isVisible   = null;


                geoFeatureLayerID = null;

                enumLayer = null;
                featlayer = null;
            }
        }
        public static void ConnectSelected(IApplication app)
        {
            IEditor editor = null;
            IEditLayers eLayers = null;

            IMap pMap = null;
            IActiveView av = null;
            try
            {
                editor = Globals.getEditor(ref app);

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show("Must be editing.", "Desktop Tools");
                    return;
                }
                eLayers = (IEditLayers)editor;

                pMap = editor.Map;
                av = pMap as IActiveView;

                if (pMap.SelectionCount > 0)
                {
                    ////If above threshold, prompt to cancel
                    //if ((map.SelectionCount > 1) &&
                    //   (MessageBox.Show("Are you sure you wish to connect the selected " + map.SelectionCount + " features?", "Confirm", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No))
                    //  return;

                    bool test = false;
                    ESRI.ArcGIS.esriSystem.IStatusBar statusBar = null;
                    ESRI.ArcGIS.esriSystem.IAnimationProgressor animationProgressor = null;
                    ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
                    ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
                    ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
                    ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = null;
                    IEnumLayer enumLayer = null;
                    IFeatureLayer fLayer = null;
                    IFeatureSelection fSel = null;
                    ILayer layer = null;
                    ICursor cursor = null;
                    IFeatureCursor fCursor = null;
                    UID geoFeatureLayerID = null;
                    INetworkClass netClass = null;
                    INetworkFeature netFeature = null;
                    IFeature feat = null;
                    int lyrCnt = 0;
                    try
                    {
                        // Create an edit operation enabling undo/redo
                        editor.StartOperation();

                        //Get list of feature layers
                        geoFeatureLayerID = new UIDClass();
                        geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                        enumLayer = pMap.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                        while ((layer = enumLayer.Next()) != null)
                        {
                            lyrCnt = lyrCnt + 1;

                        }
                        enumLayer.Reset();

                        statusBar = app.StatusBar;
                        animationProgressor = statusBar.ProgressAnimation;

                        animationProgressor.Show();
                        animationProgressor.Play(0, -1, -1);

                        statusBar.set_Message(0, "Connecting Features");

                        // Create a CancelTracker
                        trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                        // Set the properties of the Step Progressor
                        System.Int32 int32_hWnd = app.hWnd;
                        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                        stepProgressor.MinRange = 0;
                        stepProgressor.MaxRange = lyrCnt - 1;
                        stepProgressor.StepValue = 1;
                        stepProgressor.Message = "Connecting Features";

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

                        // Set the properties of the ProgressDialog
                        progressDialog2.CancelEnabled = true;
                        progressDialog2.Description = "Connecting Assets to the geometric network.";
                        progressDialog2.Title = "Connecting";
                        progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;

                        // Step. Do your big process here.
                        bool boolean_Continue = false;
                        boolean_Continue = true;

                        // Step through each geofeature layer in the map
                        enumLayer.Reset();
                        while ((layer = enumLayer.Next()) != null)
                        {

                            // Verify that this is a valid, visible point layer and that this layer is editable
                            fLayer = (IFeatureLayer)layer;
                            if (fLayer.Valid && fLayer.Visible && eLayers.IsEditable(fLayer))
                            {
                                stepProgressor.Message = "Connecting Features from " + fLayer.Name;
                                // Verify selected features and network
                                netClass = fLayer.FeatureClass as INetworkClass;
                                fSel = (IFeatureSelection)fLayer;
                                if ((netClass != null) && (fSel.SelectionSet.Count > 0))
                                {
                                    test = true;

                                    fSel.SelectionSet.Search(null, false, out cursor);
                                    fCursor = cursor as IFeatureCursor;

                                    while ((netFeature = (INetworkFeature)fCursor.NextFeature()) != null)
                                    {
                                        try
                                        {
                                            netFeature.Connect();
                                        }
                                        catch
                                        { }
                                        //feat = (IFeature)netFeature;
                                        //int fieldPos = feat.Fields.FindField("ENABLED");

                                        //if (fieldPos > -1)
                                        //{
                                        //    feat.set_Value(fieldPos, feat.get_Value(fieldPos));
                                        //    feat.Store();
                                        //}
                                    }

                                    Marshal.ReleaseComObject(cursor);
                                    Marshal.ReleaseComObject(fCursor);
                                }
                            }
                            stepProgressor.Step();

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

                        }

                        // Stop the edit operation
                        editor.StopOperation("Connect Selected");
                    }

                    catch (Exception ex)
                    {
                        editor.AbortOperation();
                        MessageBox.Show("ConnectSelected\n" + ex.Message, ex.Source);
                        return;
                    }
                    finally
                    {
                        if (animationProgressor != null)
                        {
                            animationProgressor.Stop();
                            animationProgressor.Hide();
                        }
                        // Done
                        trackCancel = null;
                        stepProgressor = null;
                        if (progressDialog2 != null)
                        {
                            progressDialog2.HideDialog();
                        }

                        progressDialog2 = null;

                        statusBar = null;
                        animationProgressor = null;

                        progressDialogFactory = null;

                        enumLayer = null;
                        fLayer = null;
                        fSel = null;
                        layer = null;
                        if (cursor != null)
                            Marshal.ReleaseComObject(cursor);
                        if (fCursor != null)
                            Marshal.ReleaseComObject(fCursor);
                        cursor = null;
                        fCursor = null;
                        geoFeatureLayerID = null;
                        netClass = null;
                        netFeature = null;
                        feat = null;

                    }

                    //Alert the user know if no work was performed
                    if (!(test))
                        MessageBox.Show("None of the layers with selected features are editable network features.", "Nothing To Connect");
                    else
                        av.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ConnectSelected\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {

                editor = null;
                eLayers = null;

                pMap = null;
                av = null;
            }
        }
Exemple #11
0
        protected override void OnClick()
        {
            // Get the min/max zoom from user input
            int minzoom = 0;
            int maxzoom = 6;
            Ecotrust.Form1 form1 = new Ecotrust.Form1();
            if (form1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                minzoom = (int)form1.numericUpDown1.Value;
                maxzoom = (int)form1.numericUpDown2.Value;
            }
            else
            {
                return; //TODO
            }

            // Use the FolderBrowserDialog Class to choose export folder
            System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog();
            folderDialog.Description = "Select output folder for map tiles...";
            string exportDir = "";
            if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp"
                exportDir = folderDialog.SelectedPath;
                if (exportDir == "")
                    return;  // TODO raise error
            }
            else
            {
                return; //TODO
            }

            ESRI.ArcGIS.ArcMapUI.IMxDocument mxDocument = ArcMap.Application.Document as ESRI.ArcGIS.ArcMapUI.IMxDocument; // Dynamic Cast
            ESRI.ArcGIS.Carto.IActiveView activeView = mxDocument.ActiveView;
            ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;

            ESRI.ArcGIS.Geometry.IEnvelope mapaoi = activeView.Extent;

            // Set up export object and tile pixel coordinates
            int tileSizeX = 256;
            int tileSizeY = 256;

            // set up exporter with transparent background
            ESRI.ArcGIS.Output.IExportPNG pngexport = new ESRI.ArcGIS.Output.ExportPNGClass();
            ESRI.ArcGIS.Display.IColor tcolor = new ESRI.ArcGIS.Display.RgbColorClass();
            // Warning: 254,254,254 will be set to transparent; don't use in any of map styling
            ((IRgbColor)tcolor).Red = 254;
            ((IRgbColor)tcolor).Green = 254;
            ((IRgbColor)tcolor).Blue = 254;
            ((ExportPNG)pngexport).BackgroundColor = tcolor;
            pngexport.TransparentColor = tcolor;
            ESRI.ArcGIS.Output.IExport export = (ESRI.ArcGIS.Output.IExport)pngexport;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left = 0;
            exportRECT.top = 0;
            exportRECT.right = tileSizeX;
            exportRECT.bottom = tileSizeY;
            ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            export.PixelBounds = envelope;

            map.DelayDrawing(true);

            // Turn off all layers
            for (int i = 0; i < map.LayerCount; i++)
                map.get_Layer(i).Visible = false;

            // Calculate total number of tiles needed
            GlobalMercator mercator = new GlobalMercator();
            GlobalMercator.Coords tempmins;
            GlobalMercator.Coords tempmaxs;
            Double numTiles = 0;
            for (int tz = minzoom; tz <= maxzoom; tz++)
            {
                tempmins = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                tempmaxs = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);
                numTiles += ((tempmaxs.y - tempmins.y)+1) * ((tempmaxs.x - tempmins.x)+1);
            }
            numTiles *= map.LayerCount;

            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = ArcMap.Application.StatusBar;
            statusBar.set_Message(0, "Rendering " + numTiles.ToString() + " tiles");

            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

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

            // Set the properties of the Step Progressor
            System.Int32 int32_hWnd = ArcMap.Application.hWnd;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
            stepProgressor.MinRange = 0;
            stepProgressor.MaxRange = (int)numTiles;
            stepProgressor.StepValue = 1;
            stepProgressor.Message = "Calculating " + numTiles.ToString() + " tiles";

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

            // Set the properties of the ProgressDialog
            progressDialog2.CancelEnabled = true;
            progressDialog2.Description = "Rendering " + numTiles.ToString() + " map tiles";
            progressDialog2.Title = "Creating map tiles...";
            progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
            System.Boolean boolean_Continue = true;

            int tileCount = 0;

            for (int lyrnum = 0; lyrnum < map.LayerCount; lyrnum++)
            {
                // Turn on the layer of interest
                ESRI.ArcGIS.Carto.ILayer layer = map.get_Layer(lyrnum);
                layer.Visible = true;

                // Set extents
                //ESRI.ArcGIS.Geometry.IEnvelope layeraoi = layer.AreaOfInterest;
                ESRI.ArcGIS.Geometry.IEnvelope aoi = new ESRI.ArcGIS.Geometry.EnvelopeClass();

                // Create layer directory if it doesn't exist
                DirectoryInfo dir = new DirectoryInfo(exportDir  + "\\" + layer.Name);
                if (!dir.Exists)
                    dir.Create();

                DateTime startTime = DateTime.Now;

                // Loop through zoom levels, rows, cols
                for (int tz = minzoom; tz <= maxzoom; tz++)
                {
                    GlobalMercator.Coords mins = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                    GlobalMercator.Coords maxs = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);

                    // Create zoom directory if it doesn't exist
                    DirectoryInfo dir2 = new DirectoryInfo(dir.FullName + "\\" + tz);
                    if (!dir2.Exists)
                        dir2.Create();

                    for (int tx = (int)mins.x; tx <= (int)maxs.x; tx++)
                    {
                        // Create X directory if it doesn't exist
                        DirectoryInfo dir3 = new DirectoryInfo(dir2.FullName + "\\" + tx);
                        if (!dir3.Exists)
                            dir3.Create();

                        for (int ty = (int)mins.y; ty <= (int)maxs.y; ty++)
                        {

                            // Flip y-axis for output tile name
                            int invertTy = (int) ((Math.Pow(2, tz) - 1) - ty);

                            tileCount += 1;

                            // TODO Calculate time and set new message
                            // TimeSpan timeElapsed = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks); // * ((double)tileCount - (numTiles + 1)) / (numTiles + 1));
                            // double timeRemaining = (timeElapsed.TotalSeconds / (tileCount / numTiles)) - timeElapsed.TotalSeconds;
                            //(" + ((int)timeRemaining).ToString() +" remaining)";

                            stepProgressor.Message = layer.Name + "\\" + tz + "\\" + tx + "\\" + invertTy +
                                ".png (" + tileCount + " of " + numTiles + ")";

                            export.ExportFileName = dir3.FullName + "\\" + invertTy + ".png";

                            GlobalMercator.Bounds bnd = mercator.TileBounds(tx, ty, tz);
                            aoi.PutCoords(bnd.minx, bnd.miny, bnd.maxx, bnd.maxy);
                            aoi.SpatialReference = map.SpatialReference; // TODO aoi spatial reference == mercator?
                            // Use FullExtent instead of Extent to make the extent independent of the activeView ratio
                            activeView.FullExtent = aoi;

                            // Export
                            System.Int32 hDC = export.StartExporting();
                            activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Explicit Cast and 'ref' keyword needed
                            export.FinishExporting();
                            export.Cleanup();

                            stepProgressor.Position = tileCount;

                            //Check if the cancel button was pressed. If so, break out of row
                            boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                                break;
                        }
                        //Check if the cancel button was pressed. If so, break out of col
                        boolean_Continue = trackCancel.Continue();
                        if (!boolean_Continue)
                            break;
                    }
                    //Check if the cancel button was pressed. If so, break out of layers
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                        break;

                    // Write log
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter( exportDir + "\\log.txt", true))
                    {
                        file.WriteLine(layer.Name + ", zoom " + tz + ", numtiles " + tileCount + ":" +
                          mins.x + " " + mins.y + " " + maxs.x + " " + maxs.y);
                    }

                }
                // Turn it off
                layer.Visible = false;
            }

            map.DelayDrawing(false);

            // Turn ON all layers
            for (int i = 0; i < map.LayerCount; i++)
                map.get_Layer(i).Visible = true;

            // restore extent
            activeView.FullExtent = mapaoi;
            activeView.Refresh();

            // Done
            trackCancel = null;
            stepProgressor = null;
            progressDialog2.HideDialog();
            progressDialog2 = null;
        }
        public void ExportSelectedRecordsToExcel()
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            IMxDocument mxdoc = null;
            IMap map = null;
            IStandaloneTableCollection standTabColl = null;
            IStandaloneTable standTable = null;
            ITableSelection tableSel = null;
            IEnumFeature enumFeat = null;
            IFeature feat = null;
            IFeatureSelection featSel = null;
            ITable openTable = null;
            object missing = null;
            //object fileName = null;
            object newTemplate = null;
            object docType = null;
            object isVisible = null;

            UID geoFeatureLayerID = null;

            IEnumLayer enumLayer = null;
            IFeatureLayer featlayer = null;
            try
            {

                mxdoc = (IMxDocument)_app.Document;
                map = mxdoc.FocusMap;

                long standTableCnt;
                int i = 0;
                bool selectionInTable = false;

                missing = System.Reflection.Missing.Value;
                // fileName = "normal.dot";
                newTemplate = false;
                docType = 0;
                isVisible = true;

                //Get enumeration of feature layers
                geoFeatureLayerID = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(geoFeatureLayerID, true);

                enumLayer.Reset();

                standTabColl = (IStandaloneTableCollection)map;
                standTableCnt = standTabColl.StandaloneTableCount;

                enumFeat = (IEnumFeature)map.FeatureSelection;
                enumFeat.Reset();
                feat = enumFeat.Next();

                if (standTableCnt > 0)
                {
                    for (int j = 0; j < standTableCnt; j++)
                    {
                        standTable = standTabColl.get_StandaloneTable(j);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                selectionInTable = true;
                                break;
                            }
                        }
                    }
                }

                if ((selectionInTable == false) && (feat == null))
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("DataToolsMess_1") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("DataToolsMess_2"), messageBoxHeader);
                    return;
                }
                // Create a CancelTracker
                ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;

                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                stepProgressor.MinRange = 0;
                stepProgressor.MaxRange = mxdoc.FocusMap.SelectionCount;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + "1" + A4LGSharedFunctions.Localizer.GetString("Of") + mxdoc.FocusMap.SelectionCount.ToString() + ".";
                progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                if ((feat != null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {

                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();

                    }

                    featlayer = (IFeatureLayer)enumLayer.Next();
                    while (featlayer != null)
                    {
                        if ((featlayer.Valid) && (featlayer.Selectable))
                        {
                            featSel = (IFeatureSelection)featlayer;
                            if (featSel.SelectionSet.Count > 0)
                            {
                                ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor);
                            }
                        }
                        featlayer = (IFeatureLayer)enumLayer.Next();
                    }

                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor);
                            }
                        }
                    }
                }
                else if ((feat != null) && (selectionInTable == false))
                {

                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {

                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();

                    }

                    ILayer pTLay = enumLayer.Next();
                    while (pTLay != null)
                    {
                        if (pTLay is IFeatureLayer)
                        {
                            featlayer = (IFeatureLayer)pTLay;
                            if ((featlayer.Valid) )
                            {
                                featSel = (IFeatureSelection)featlayer;
                                if (featSel.SelectionSet.Count > 0)
                                {
                                    ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor);
                                }
                            }
                        }
                        pTLay = enumLayer.Next();

                    }
                    pTLay = null;

                }
                else if ((feat == null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {

                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();

                    }
                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor);
                            }
                        }
                    }
                }

                if (objBook.Sheets.Count > 1)
                {
                    objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1);
                    objSheet.Delete();
                }
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet2"];
                //objSheet.Delete();
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet3"];
                //objSheet.Delete();
                ExcelApp.DisplayAlerts = true;

                //Make the first sheet active
                objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1) as Excel.Worksheet;
                (objSheet as Microsoft.Office.Interop.Excel._Worksheet).Activate();

                //Make Excel visible
                ExcelApp.Visible = true;
                return;
            }
            catch (Exception ex)
            {
                if (ExcelApp != null)
                    ExcelApp = null;

                //ExcelApp.Visible = true;
                MessageBox.Show("ExportSelectedRecordsToExcel\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {
                if (progressDialog != null)
                    progressDialog.HideDialog();

                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                mxdoc = null;
                map = null;
                standTabColl = null;
                standTable = null;
                tableSel = null;
                enumFeat = null;
                feat = null;
                featSel = null;
                openTable = null;
                missing = null;
                //fileName = null;
                newTemplate = null;
                docType = null;
                isVisible = null;

                geoFeatureLayerID = null;

                enumLayer = null;
                featlayer = null;
            }
        }
Exemple #13
0
        protected override void OnClick()
        {
            // Get the min/max zoom from user input
            int minzoom = 0;
            int maxzoom = 6;

            Ecotrust.Form1 form1 = new Ecotrust.Form1();
            if (form1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                minzoom = (int)form1.numericUpDown1.Value;
                maxzoom = (int)form1.numericUpDown2.Value;
            }
            else
            {
                return; //TODO
            }

            // Use the FolderBrowserDialog Class to choose export folder
            System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog();
            folderDialog.Description = "Select output folder for map tiles...";
            string exportDir = "";

            if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp"
                exportDir = folderDialog.SelectedPath;
                if (exportDir == "")
                {
                    return;  // TODO raise error
                }
            }
            else
            {
                return; //TODO
            }

            ESRI.ArcGIS.ArcMapUI.IMxDocument mxDocument = ArcMap.Application.Document as ESRI.ArcGIS.ArcMapUI.IMxDocument; // Dynamic Cast
            ESRI.ArcGIS.Carto.IActiveView    activeView = mxDocument.ActiveView;
            ESRI.ArcGIS.Carto.IMap           map        = activeView.FocusMap;

            ESRI.ArcGIS.Geometry.IEnvelope mapaoi = activeView.Extent;

            // Set up export object and tile pixel coordinates
            int tileSizeX = 256;
            int tileSizeY = 256;

            // set up exporter with transparent background
            ESRI.ArcGIS.Output.IExportPNG pngexport = new ESRI.ArcGIS.Output.ExportPNGClass();
            ESRI.ArcGIS.Display.IColor    tcolor    = new ESRI.ArcGIS.Display.RgbColorClass();
            // Warning: 254,254,254 will be set to transparent; don't use in any of map styling
            ((IRgbColor)tcolor).Red   = 254;
            ((IRgbColor)tcolor).Green = 254;
            ((IRgbColor)tcolor).Blue  = 254;
            ((ExportPNG)pngexport).BackgroundColor = tcolor;
            pngexport.TransparentColor             = tcolor;
            ESRI.ArcGIS.Output.IExport export = (ESRI.ArcGIS.Output.IExport)pngexport;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = tileSizeX;
            exportRECT.bottom = tileSizeY;
            ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            export.PixelBounds = envelope;

            map.DelayDrawing(true);

            // Turn off all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = false;
            }

            // Calculate total number of tiles needed
            GlobalMercator mercator = new GlobalMercator();

            GlobalMercator.Coords tempmins;
            GlobalMercator.Coords tempmaxs;
            Double numTiles = 0;

            for (int tz = minzoom; tz <= maxzoom; tz++)
            {
                tempmins  = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                tempmaxs  = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);
                numTiles += ((tempmaxs.y - tempmins.y) + 1) * ((tempmaxs.x - tempmins.x) + 1);
            }
            numTiles *= map.LayerCount;

            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = ArcMap.Application.StatusBar;
            statusBar.set_Message(0, "Rendering " + numTiles.ToString() + " tiles");

            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

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

            // Set the properties of the Step Progressor
            System.Int32 int32_hWnd = ArcMap.Application.hWnd;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
            stepProgressor.MinRange  = 0;
            stepProgressor.MaxRange  = (int)numTiles;
            stepProgressor.StepValue = 1;
            stepProgressor.Message   = "Calculating " + numTiles.ToString() + " tiles";

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

            // Set the properties of the ProgressDialog
            progressDialog2.CancelEnabled = true;
            progressDialog2.Description   = "Rendering " + numTiles.ToString() + " map tiles";
            progressDialog2.Title         = "Creating map tiles...";
            progressDialog2.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
            System.Boolean boolean_Continue = true;

            int tileCount = 0;

            for (int lyrnum = 0; lyrnum < map.LayerCount; lyrnum++)
            {
                // Turn on the layer of interest
                ESRI.ArcGIS.Carto.ILayer layer = map.get_Layer(lyrnum);
                layer.Visible = true;

                // Set extents
                //ESRI.ArcGIS.Geometry.IEnvelope layeraoi = layer.AreaOfInterest;
                ESRI.ArcGIS.Geometry.IEnvelope aoi = new ESRI.ArcGIS.Geometry.EnvelopeClass();

                // Create layer directory if it doesn't exist
                DirectoryInfo dir = new DirectoryInfo(exportDir + "\\" + layer.Name);
                if (!dir.Exists)
                {
                    dir.Create();
                }

                DateTime startTime = DateTime.Now;

                // Loop through zoom levels, rows, cols
                for (int tz = minzoom; tz <= maxzoom; tz++)
                {
                    GlobalMercator.Coords mins = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                    GlobalMercator.Coords maxs = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);

                    // Create zoom directory if it doesn't exist
                    DirectoryInfo dir2 = new DirectoryInfo(dir.FullName + "\\" + tz);
                    if (!dir2.Exists)
                    {
                        dir2.Create();
                    }

                    for (int tx = (int)mins.x; tx <= (int)maxs.x; tx++)
                    {
                        // Create X directory if it doesn't exist
                        DirectoryInfo dir3 = new DirectoryInfo(dir2.FullName + "\\" + tx);
                        if (!dir3.Exists)
                        {
                            dir3.Create();
                        }

                        for (int ty = (int)mins.y; ty <= (int)maxs.y; ty++)
                        {
                            // Flip y-axis for output tile name
                            int invertTy = (int)((Math.Pow(2, tz) - 1) - ty);

                            tileCount += 1;

                            // TODO Calculate time and set new message
                            // TimeSpan timeElapsed = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks); // * ((double)tileCount - (numTiles + 1)) / (numTiles + 1));
                            // double timeRemaining = (timeElapsed.TotalSeconds / (tileCount / numTiles)) - timeElapsed.TotalSeconds;
                            //(" + ((int)timeRemaining).ToString() +" remaining)";

                            stepProgressor.Message = layer.Name + "\\" + tz + "\\" + tx + "\\" + invertTy +
                                                     ".png (" + tileCount + " of " + numTiles + ")";


                            export.ExportFileName = dir3.FullName + "\\" + invertTy + ".png";

                            GlobalMercator.Bounds bnd = mercator.TileBounds(tx, ty, tz);
                            aoi.PutCoords(bnd.minx, bnd.miny, bnd.maxx, bnd.maxy);
                            aoi.SpatialReference = map.SpatialReference; // TODO aoi spatial reference == mercator?
                            // Use FullExtent instead of Extent to make the extent independent of the activeView ratio
                            activeView.FullExtent = aoi;

                            // Export
                            System.Int32 hDC = export.StartExporting();
                            activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Explicit Cast and 'ref' keyword needed
                            export.FinishExporting();
                            export.Cleanup();

                            stepProgressor.Position = tileCount;

                            //Check if the cancel button was pressed. If so, break out of row
                            boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                            {
                                break;
                            }
                        }
                        //Check if the cancel button was pressed. If so, break out of col
                        boolean_Continue = trackCancel.Continue();
                        if (!boolean_Continue)
                        {
                            break;
                        }
                    }
                    //Check if the cancel button was pressed. If so, break out of layers
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        break;
                    }

                    // Write log
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportDir + "\\log.txt", true))
                    {
                        file.WriteLine(layer.Name + ", zoom " + tz + ", numtiles " + tileCount + ":" +
                                       mins.x + " " + mins.y + " " + maxs.x + " " + maxs.y);
                    }
                }
                // Turn it off
                layer.Visible = false;
            }

            map.DelayDrawing(false);

            // Turn ON all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = true;
            }

            // restore extent
            activeView.FullExtent = mapaoi;
            activeView.Refresh();

            // Done
            trackCancel    = null;
            stepProgressor = null;
            progressDialog2.HideDialog();
            progressDialog2 = null;
        }
        public void SetDynamicValues(IObject inObject, string mode)
        {
            IFeature inFeature = null;
            // IRow inRow = null;

            IMSegmentation mseg = null;
            INetworkFeature netFeat = null;
            IEdgeFeature edgeFeat = null;
            IFeature juncFeat;
            IJunctionFeature iJuncFeat;
            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

            try
            {
                if (AAState._PerformUpdates && AAState._dv == null)
                {

                    AAState.WriteLine("Dynamic Value Table is missing - Name in Config:" + AAState._defaultsTableName);

                    //    MessageBox.Show("The Attribute Assistant is turned on, but the Dynamic Value table is missing, please add the table and toggle the extension on");
                    AAState._PerformUpdates = false;
                    return;
                }
                if (AAState._PerformUpdates && AAState._dv != null)
                {
                    if (inObject == null)
                        return;
                    //Convert row to feature (test for feature is null before using - this could be a table update)
                    inFeature = inObject as IFeature;
                    // inRow = inObject as IRow;
                    string modeVal;

                    if (AAState._dv.Table.Columns[mode].DataType == System.Type.GetType("System.String"))
                    {
                        modeVal = "(" + mode + " = '1' or " + mode + " = 'Yes' or " + mode + " = 'YES' or " + mode + " = 'True' or " + mode + " = 'TRUE')";

                    }
                    else
                    {
                        modeVal = mode + " = 1";
                    }
                    System.Int32 int32_hWnd = ArcMap.Application.hWnd;

                    progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = inObject.Fields.FieldCount;
                    stepProgressor.StepValue = 1;
                    stepProgressor.Message = "Attribute Assistant Progress";
                    // Create the ProgressDialog. This automatically displays the dialog
                    progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                    // Set the properties of the ProgressDialog
                    progressDialog.CancelEnabled = true;
                    progressDialog.Description = "Checking rules for " + inObject.Class.AliasName;
                    progressDialog.Title = "Attribute Assistant Progress";
                    progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                    progressDialog.ShowDialog();
                    //for each field in this row/feature
                    // Skip orphan junctions (saves time)

                    if (Globals.isOrpanJunction(inFeature))
                        return;
                    //Get table name for this feature
                    _currentDataset = inObject.Class as IDataset;
                    _currentDatasetNameItems = _currentDataset.Name.Split('.');
                    tableName = _currentDatasetNameItems[_currentDatasetNameItems.GetLength(0) - 1];

                    for (int fieldNum = 0; fieldNum <= inObject.Fields.FieldCount; fieldNum++)
                    {

                        stepProgressor.Step();
                        bool editable = true;
                        if (fieldNum == inObject.Fields.FieldCount)
                        {
                            fieldObj = null;

                            fieldName = "";
                            stepProgressor.Message = "Checking rules for field null fields in" + inObject.Class.AliasName;
                            progressDialog.Description = "Checking rules for field null fields in" + inObject.Class.AliasName;
                            AAState.WriteLine("***********************************************************");
                            AAState.WriteLine("");

                            AAState.WriteLine("############ " + DateTime.Now + " ################");
                            editable = true;
                            //  fieldNum++;

                        }
                        else
                        {
                            fieldObj = inObject.Fields.get_Field(fieldNum);

                            fieldName = fieldObj.Name;
                            stepProgressor.Message = "Checking rules for field " + fieldName + " in " + inObject.Class.AliasName;
                            progressDialog.Description = "Checking rules for field " + fieldName + " in " + inObject.Class.AliasName;
                            AAState.WriteLine("***********************************************************");
                            AAState.WriteLine("");
                            AAState.WriteLine("############ " + fieldName + " ################");
                            AAState.WriteLine("############ " + DateTime.Now + " ################");
                            AAState.WriteLine("Is field -  " + fieldName + " Editable = " + fieldObj.Editable);
                            editable = fieldObj.Editable;
                        }
                        bool proc = false;
                        if (editable == true && fieldObj != null)
                        {
                            AAState.WriteLine("Checking rules for field " + fieldName + " in " + inObject.Class.AliasName);

                            AAState._dv.RowFilter = "(TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And FIELDNAME = '" + fieldName + "' and " + modeVal;
                            //AAState._dv.rw
                            AAState.WriteLine("    Row Query: " + "TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And FIELDNAME = '" + fieldName + "' and " + modeVal);
                            if (AAState._dv.Count == 0)
                            {
                                AAState._dv.RowFilter = "TABLENAME = '*' And FIELDNAME = '" + fieldName + "' and " + modeVal;

                                AAState.WriteLine("    Query using " + fieldName + " did not produce any results, trying all fields");
                                AAState.WriteLine("    Row Query: " + "TABLENAME = '*' And FIELDNAME = '" + fieldName + "' and " + modeVal);
                            }
                            if (AAState._dv.Count == 0)
                            {
                                AAState.WriteLine("    No entries found");
                                proc = false;
                            }
                            else
                            {
                                proc = true;
                            }

                        }
                        //   else if (editable == false )
                        //{
                        //    AAState.WriteLine("Checking rules for field " + fieldName + " in " + inObject.Class.AliasName);

                        //    AAState._dv.RowFilter = "(TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And FIELDNAME = '" + fieldName + "' and " + modeVal;
                        //    //AAState._dv.rw
                        //    AAState.WriteLine("    Row Query: " + "TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And FIELDNAME = '" + fieldName + "' and " + modeVal);
                        //    if (AAState._dv.Count == 0)
                        //    {
                        //        AAState._dv.RowFilter = "TABLENAME = '*' And FIELDNAME = '" + fieldName + "' and " + modeVal;

                        //        AAState.WriteLine("    Query using " + fieldName + " did not produce any results, trying all fields");
                        //        AAState.WriteLine("    Row Query: " + "TABLENAME = '*' And FIELDNAME = '" + fieldName + "' and " + modeVal);
                        //    }
                        //    if (AAState._dv.Count == 0)
                        //    {
                        //        AAState.WriteLine("    No entries found");
                        //        proc = false;
                        //    }
                        //    else
                        //    {
                        //        proc = true;
                        //    }

                        //}
                        else if (editable && fieldObj == null)
                        {
                            fieldName = "";
                            AAState._dv.RowFilter = "(TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And (FIELDNAME = '" + fieldName + "' or FIELDNAME IS NULL) and " + modeVal;
                            //AAState._dv.rw
                            AAState.WriteLine("    Row Query: " + "TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') And (FIELDNAME = '" + fieldName + "' or FIELDNAME IS NULL) and " + modeVal);
                            if (AAState._dv.Count == 0)
                            {
                                AAState._dv.RowFilter = "TABLENAME = '*' And (FIELDNAME = '" + fieldName + "' or FIELDNAME IS NULL) and " + modeVal;

                                AAState.WriteLine("    Query using " + fieldName + " did not produce any results, trying all fields");
                                AAState.WriteLine("    Row Query: " + "TABLENAME = '*' And And (FIELDNAME = '" + fieldName + "' or FIELDNAME IS NULL) and " + modeVal);
                            }
                            if (AAState._dv.Count == 0)
                            {
                                AAState.WriteLine("    No entries found");
                                proc = false;
                            }
                            else
                            {
                                proc = true;
                            }
                        }
                        if (proc)
                        {

                            AAState.WriteLine("          Value Entry Rows found: " + AAState._dv.Count);
                            AAState.WriteLine("          ----------------------------------------------");
                            // Get requested method and any data parameters
                            AAState.WriteLine("          Looping through Value Methods");
                            AAState.WriteLine("                  ------------------------");
                            foreach (DataRowView drv in AAState._dv)
                            {

                                AAState.WriteLine("                  Checking for Subtype Restriction");
                                valFC = drv["TABLENAME"].ToString().Trim();
                                if (valFC.Contains("|"))
                                {
                                    AAState.WriteLine("                  Subtype restriction Found");
                                    string[] spliVal = valFC.Split('|');

                                    if (Globals.IsInteger(spliVal[1]))
                                    {
                                        int SubVal = Convert.ToInt32(spliVal[1]);
                                        ISubtypes pSub = inObject.Class as ISubtypes;
                                        if (pSub != null)
                                        {
                                            if (pSub.HasSubtype)
                                            {
                                                int obSubVal = (int)inObject.get_Value(pSub.SubtypeFieldIndex);
                                                if (obSubVal == SubVal)
                                                {
                                                    AAState.WriteLine("                  Subtypes match");
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  Skipping, not the subtype defined");
                                                    continue;
                                                }
                                            }
                                            else
                                            {
                                                AAState.WriteLine("                  ERROR: Layer does not have subtypes");
                                            }
                                        }
                                        else
                                        {
                                            AAState.WriteLine("                  ERROR: Layer does not have subtypes");
                                        }
                                    }
                                    else
                                    {
                                        AAState.WriteLine("                  ERROR: Subtype not an integar");
                                    }
                                }
                                valMethod = drv["VALUEMETHOD"].ToString().ToUpper().Trim();
                                valData = drv["VALUEINFO"].ToString().Trim();

                                AAState.WriteLine("                  VALUEMETHOD: " + valMethod);
                                AAState.WriteLine("                  VALUEINFO: " + valData);
                                AAState.WriteLine("                  ------------------------");
                                //set field value based on specified method
                                try
                                {
                                    switch (valMethod)
                                    {
                                        case "SPLIT_INTERSECTING_FEATURE":
                                            {
                                                AAState.WriteLine("                  Trying: SPLIT_INTERSECTING_FEATURE");

                                                try
                                                {
                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        intersectLayerName = "";
                                                        intersectLayer = null;
                                                        args = valData.Split('|');
                                                        if (args.Length > 0)
                                                        {
                                                            AAState.WriteLine("                  " + args.Length + " Layers listed ");

                                                            for (int i = 0; i < args.Length; i++)
                                                            {

                                                                intersectLayerName = args[i].Trim();
                                                                AAState.WriteLine("                  Searching for " + intersectLayerName);

                                                                intersectLayer = Globals.FindLayer(AAState._editor.Map, intersectLayerName) as IFeatureLayer;

                                                                if (intersectLayer != null)
                                                                {
                                                                    AAState.WriteLine("                  Layer Found " + intersectLayerName);
                                                                    if (intersectLayer.FeatureClass != null)
                                                                    {
                                                                        AAState.WriteLine("                  Datasource is valid for " + intersectLayerName);

                                                                        sFilter = new SpatialFilterClass();
                                                                        AAState.WriteLine("                  Checking source Geometry Type");

                                                                        if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                                        {
                                                                            // esriSpatialRelIntersects does not work properly for point intersecting line.
                                                                            // hence expand point envelope (code cribbed from below)
                                                                            try
                                                                            {
                                                                                ISpatialReferenceResolution pSRResolution;

                                                                                pSRResolution = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference) as ISpatialReferenceResolution;

                                                                                //  sFilter = new SpatialFilterClass();
                                                                                double intTol = pSRResolution.get_XYResolution(false);
                                                                                bool hasXY = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference).HasXYPrecision();

                                                                                searchEnvelope = new EnvelopeClass();
                                                                                searchEnvelope.XMin = 0 - intTol;
                                                                                searchEnvelope.YMin = 0 - intTol;
                                                                                searchEnvelope.XMax = 0 + intTol;
                                                                                searchEnvelope.YMax = 0 + intTol;
                                                                                searchEnvelope.CenterAt(inFeature.ShapeCopy as IPoint);

                                                                                //searchEnvelope.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                searchEnvelope.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                searchEnvelope.SnapToSpatialReference();
                                                                                searchEnvelope.Project(AAState._editor.Map.SpatialReference);

                                                                                sFilter.Geometry = Globals.Env2Polygon(searchEnvelope);

                                                                            }
                                                                            catch
                                                                            {
                                                                                sFilter.Geometry = inFeature.ShapeCopy;
                                                                            }

                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Geoemetry is not a point, using shape envelope");

                                                                            sFilter.Geometry = inFeature.ShapeCopy;
                                                                        }
                                                                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                                                        sFilter.GeometryField = intersectLayer.FeatureClass.ShapeFieldName;
                                                                        AAState.WriteLine("                  Searching " + intersectLayerName + "for intersected feature");

                                                                        fCursor = intersectLayer.FeatureClass.Search(sFilter, true);
                                                                        IFeature intsersectFeature;
                                                                        int idx = 1;
                                                                        while ((intsersectFeature = fCursor.NextFeature()) != null)
                                                                        {
                                                                            AAState.WriteLine("                  Splitting Intersected Feature number: " + idx);
                                                                            idx++;

                                                                            IFeatureEdit featureEdit = intsersectFeature as IFeatureEdit;
                                                                            ISet featset = featureEdit.Split(inFeature.Shape);
                                                                            AAState.WriteLine("                  Adding split features to array to call the AA ext");

                                                                            if (featset.Count > 0)
                                                                            {
                                                                                if (newFeatureList == null)
                                                                                {
                                                                                    newFeatureList = new List<IObject>();
                                                                                }
                                                                                object featobj;
                                                                                while ((featobj = featset.Next()) != null)
                                                                                {
                                                                                    IFeature feature = featobj as IFeature;
                                                                                    if (feature != null)
                                                                                    {
                                                                                        newFeatureList.Add(feature as IObject);
                                                                                    }
                                                                                }
                                                                            }
                                                                            AAState.WriteLine("                  Split feature " + intersectLayerName + " into " + featset.Count);
                                                                            if (intsersectFeature != null)
                                                                            {
                                                                                Marshal.ReleaseComObject(intsersectFeature);
                                                                            }

                                                                        }
                                                                    }
                                                                }

                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Warning: Can't find intersecting layer: " + intersectLayerName);
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Unsupported Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: not a feature or no Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: SPLIT_INTERSECTING_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: SPLIT_INTERSECTING_FEATURE");
                                                }
                                                break;
                                            }

                                        case "NEAREST_FEATURE_ATTRIBUTES":
                                            {
                                                AAState.WriteLine("                  Trying NEAREST_FEATURE_ATTRIBUTES");
                                                try
                                                {
                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        sourceLayerName = "";
                                                        string[] sourceFieldNames = null;
                                                        string[] destFieldNames = null;
                                                        searchDistance = 0;

                                                        // Parse arguments
                                                        args = valData.Split('|');
                                                        if (args.Length == 3)
                                                        {
                                                            sourceLayerName = args[0].ToString().Trim();
                                                            sourceFieldNames = args[1].ToString().Split(',');
                                                            destFieldNames = args[2].ToString().Split(',');
                                                            AAState.WriteLine("                  WARNING:  search distance as not specified, defaulting to 0");

                                                        }
                                                        else if (args.Length == 4)
                                                        {
                                                            sourceLayerName = args[0].ToString().Trim();
                                                            sourceFieldNames = args[1].ToString().Split(',');
                                                            destFieldNames = args[2].ToString().Split(',');
                                                            Double.TryParse(args[3], out searchDistance);
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR:  the valuemethod is not defined properly for this rule");
                                                            continue;

                                                        }

                                                        if ((sourceFieldNames != null) && (destFieldNames != null) &&
                                                            (sourceFieldNames.Length > 0) && (destFieldNames.Length > 0) &&
                                                            (sourceFieldNames.Length == destFieldNames.Length))
                                                        {
                                                            AAState.WriteLine("                  Looking for layer: " + sourceLayerName);

                                                            sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName) as IFeatureLayer;
                                                            if (sourceLayer != null)
                                                            {
                                                                if (sourceLayer.FeatureClass != null)
                                                                {
                                                                    AAState.WriteLine("                  layer Found: " + sourceLayerName);

                                                                    string missingFieldMess = null;
                                                                    int[] sourceFieldNums = new int[sourceFieldNames.Length];
                                                                    int[] destFieldNums = new int[destFieldNames.Length];
                                                                    AAState.WriteLine("                  Checking Field Mapping");

                                                                    for (int i = 0; i < sourceFieldNums.Length; i++)
                                                                    {
                                                                        int fnum = sourceLayer.FeatureClass.FindField(sourceFieldNames[i].Trim());
                                                                        if (fnum < 0)
                                                                        {
                                                                            missingFieldMess = sourceFieldNames[i].Trim() + " in table " + sourceLayerName;
                                                                            break;
                                                                        }
                                                                        sourceFieldNums[i] = fnum;
                                                                    }
                                                                    if (missingFieldMess == null)
                                                                    {
                                                                        for (int i = 0; i < destFieldNums.Length; i++)
                                                                        {
                                                                            int fnum = inFeature.Fields.FindField(destFieldNames[i].Trim());
                                                                            if (fnum < 0)
                                                                            {
                                                                                missingFieldMess = destFieldNames[i].Trim() + " in table " + tableName;
                                                                                break;
                                                                            }
                                                                            destFieldNums[i] = fnum;
                                                                        }
                                                                    }
                                                                    if (missingFieldMess == null)
                                                                    {
                                                                        AAState.WriteLine("                  Field Mapping verified");

                                                                        // found source and destination fields.
                                                                        sFilter = new SpatialFilterClass();

                                                                        if (searchDistance > 0)
                                                                        {
                                                                            searchEnvelope = inFeature.ShapeCopy.Envelope;
                                                                            searchEnvelope.Expand(searchDistance, searchDistance, false);
                                                                            sFilter.Geometry = searchEnvelope;
                                                                        }
                                                                        else
                                                                            sFilter.Geometry = inFeature.ShapeCopy;

                                                                        sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                                                        AAState.WriteLine("                  Searching for Nearest Feature");

                                                                        fCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                        sourceFeature = fCursor.NextFeature();
                                                                        nearestFeature = null;

                                                                        proxOp = (IProximityOperator)inFeature.Shape;
                                                                        lastDistance = searchDistance;
                                                                        if (sourceFeature != null)
                                                                        {
                                                                            AAState.WriteLine("                  Features Found, looping for closest");

                                                                            while (sourceFeature != null)
                                                                            {

                                                                                distance = proxOp.ReturnDistance(sourceFeature.Shape);
                                                                                if (distance <= lastDistance)
                                                                                {
                                                                                    nearestFeature = sourceFeature;
                                                                                    lastDistance = distance;
                                                                                }
                                                                                sourceFeature = fCursor.NextFeature();
                                                                            }
                                                                        }
                                                                        if (nearestFeature != null)
                                                                        {
                                                                            AAState.WriteLine("                  Closest Feature is " + lastDistance + " Away with OID of " + nearestFeature.OID);

                                                                            for (int i = 0; i < sourceFieldNums.Length; i++)
                                                                            {
                                                                                try
                                                                                {
                                                                                    AAState.WriteLine("                  Trying to copy " + sourceFieldNums[i] + " to " + destFieldNums[i]);

                                                                                    inObject.set_Value(destFieldNums[i], nearestFeature.get_Value(sourceFieldNums[i]));
                                                                                }
                                                                                catch
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: copying " + sourceFieldNums[i] + " to " + destFieldNums[i]);

                                                                                }
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  No Feature was found, default fields");

                                                                            for (int i = 0; i < destFieldNums.Length; i++)
                                                                            {
                                                                                IField field = inObject.Fields.get_Field(destFieldNums[i]);
                                                                                object newval = field.DefaultValue;
                                                                                if (newval == null)
                                                                                {
                                                                                    if (field.IsNullable)
                                                                                    {
                                                                                        inObject.set_Value(destFieldNums[i], null);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    inObject.set_Value(destFieldNums[i], newval);
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: Cant find field " + missingFieldMess);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayerName + " data source is not set");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: " + sourceLayerName + " was not found");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Invalid Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Not a feature or missing Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: EUK_NEAREST_FEATURE_ATTRIBUTES" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: EUK_NEAREST_FEATURE_ATTRIBUTES");
                                                }
                                                break;
                                            }
                                        case "MINIMUM_LENGTH":
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying MINIMUM_LENGTH");

                                                    double minlength;
                                                    AAState.WriteLine("                  Evaluating Minimum length value");

                                                    if (Double.TryParse(valData, out minlength))
                                                    {
                                                        if (inFeature != null)
                                                        {
                                                            ICurve curve = inFeature.Shape as ICurve;
                                                            if (curve != null)
                                                            {
                                                                if (curve.Length < minlength)
                                                                {
                                                                    String mess = "Line is shorter than " +
                                                                        String.Format("{0:0.00}", minlength) + " " + Globals.GetSpatRefUnitName(inFeature.Shape.SpatialReference, true) +
                                                                        ", aborting edit.";
                                                                    AAState.WriteLine("                  " + mess);

                                                                    MessageBox.Show(mess, "Line too short");
                                                                    AAState._editor.AbortOperation();
                                                                    return;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR:  Feature is not a Line");

                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  Error MINIMUM_LENGTH \n" + ex.Message);
                                                }
                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished MINIMUM_LENGTH");

                                                }

                                                break;
                                            }
                                        case "LINK_TABLE_ASSET":
                                            try
                                            {
                                                intersectLayerName = "";
                                                intersectTable = null;
                                                intersectLayer = null;
                                                intersectLayerFieldName = "";
                                                AAState.WriteLine("                  Trying LINK_TABLE_ASSET");
                                                args = valData.Split('|');
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:  // Feature Layer only
                                                        intersectLayerName = args[0].ToString();
                                                        break;
                                                    case 2:  // Feature Layer| Field to copy
                                                        intersectLayerName = args[0].ToString();
                                                        intersectLayerFieldName = args[1].ToString();

                                                        break;
                                                    case 3:  // Feature Layer| Field to copy | for future
                                                        intersectLayerName = args[0].ToString();
                                                        intersectLayerFieldName = args[1].ToString();
                                                        //sequenceColumnName = args[2].ToString();
                                                        break;
                                                    default:
                                                        AAState.WriteLine("                  ERROR: Unsupported Value Method: " + valData);
                                                        break;
                                                }
                                                intersectLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, intersectLayerName);
                                                intersectTable = Globals.FindStandAloneTable(AAState._editor.Map, intersectLayerName);
                                                ICursor cCurs = null;
                                                if (intersectLayer != null)
                                                {
                                                    //Find Area Field
                                                    intersectFieldPos = intersectLayer.FeatureClass.Fields.FindField(intersectLayerFieldName);
                                                    if (intersectFieldPos < 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Asset feature Layer Field(" + intersectLayerFieldName + ") not found");
                                                        break;
                                                    }
                                                    intersectLayerSelection = (IFeatureSelection)intersectLayer;
                                                    if (intersectLayerSelection.SelectionSet.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: No assests selected in " + intersectLayerName);

                                                        break;
                                                    }
                                                    if (intersectLayerSelection.SelectionSet.Count > 1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: To many assests are selected in " + intersectLayerName);

                                                        break;
                                                    }

                                                    intersectLayerSelection.SelectionSet.Search(null, true, out cCurs);
                                                }
                                                else if (intersectTable != null)
                                                {
                                                    if (intersectTable.Table == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Asset  Layer(" + intersectLayerName + ") not found");
                                                        break;
                                                    }
                                                    //Find Area Field
                                                    intersectFieldPos = intersectTable.Table.Fields.FindField(intersectLayerFieldName);
                                                    if (intersectFieldPos < 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Asset Layer Field(" + intersectLayerFieldName + ") not found");
                                                        break;
                                                    }
                                                    intersectTableSelection = (ITableSelection)intersectTable;
                                                    if (intersectTableSelection.SelectionSet.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: No assests selected in " + intersectLayerName);

                                                        break;
                                                    }
                                                    if (intersectTableSelection.SelectionSet.Count > 1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: To many assests are selected in " + intersectLayerName);

                                                        break;
                                                    }

                                                    intersectTableSelection.SelectionSet.Search(null, true, out cCurs);
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: Asset  Layer(" + intersectLayerName + ") not found");
                                                    break;
                                                }

                                                IRow row;

                                                while ((row = cCurs.NextRow()) != null)
                                                {
                                                    string val = row.get_Value(intersectFieldPos).ToString();

                                                    if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeString)
                                                        inObject.set_Value(fieldNum, val);
                                                    else
                                                    {
                                                        if (Globals.IsNumeric(val))
                                                        {

                                                            inObject.set_Value(fieldNum, row.get_Value(intersectFieldPos));
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field is a number and ID from Asset is not - ID:" + val);

                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LINK_TABLE_ASSET" + Environment.NewLine + ex.Message);
                                            }

                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LINK_TABLE_ASSET");
                                            }
                                            break;

                                        case "GET_ADDRESS_USING_GEOCODER":
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying GET_ADDRESS_USING_GEOCODER");

                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 2)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    AAState.WriteLine("                  Trying to get address locator");
                                                    IReverseGeocoding reverseGeocoding = Globals.OpenLocator(args[0], args[1]);

                                                    if (reverseGeocoding == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Reverse Address not locator found");
                                                        break;
                                                    }
                                                    AAState.WriteLine("                  Reverse Address locator found");
                                                    AAState.WriteLine("                  Retrieving Location to reverse geocode");
                                                    IPoint revGCLoc = Globals.GetGeomCenter(inFeature);
                                                    AAState.WriteLine("                  Location retrieved");
                                                    // Create a Point at which to find the address.
                                                    IAddressGeocoding addressGeocoding = (IAddressGeocoding)reverseGeocoding;

                                                    IFields matchFields = addressGeocoding.MatchFields;
                                                    int shpFld = matchFields.FindField("Shape");

                                                    IField shapeField = matchFields.get_Field(shpFld);
                                                    AAState.WriteLine("                  Setting distance");
                                                    // Set the search tolerance for reverse geocoding.
                                                    IReverseGeocodingProperties reverseGeocodingProperties =
                                                        (IReverseGeocodingProperties)reverseGeocoding;
                                                    reverseGeocodingProperties.SearchDistance = 100;
                                                    reverseGeocodingProperties.SearchDistanceUnits = esriUnits.esriFeet;

                                                    // Find the address nearest the Point.
                                                    IPropertySet addressProperties = reverseGeocoding.ReverseGeocode(revGCLoc, false);

                                                    // Print the address properties.
                                                    IAddressInputs addressInputs = (IAddressInputs)reverseGeocoding;
                                                    IFields addressFields = addressInputs.AddressFields;
                                                    object key, value;
                                                    addressProperties.GetAllProperties(out key, out value);

                                                    //object[] keyArray = key as object[];
                                                    //object[] valueArray = value as object[];

                                                    //for (int i = 0; i < keyArray.Length; i++)
                                                    //{
                                                    //    if (keyArray[i].ToString() == "Shape")
                                                    //    {
                                                    //        IPoint addressPoint = valueArray[i] as IPoint;
                                                    //        Console.WriteLine(keyArray[i] + " = " + addressPoint.X + ", " +
                                                    //            addressPoint.Y);
                                                    //    }
                                                    //    else
                                                    //        Console.WriteLine(keyArray[i] + " = " + valueArray[i]);
                                                    //}
                                                    for (int i = 0; i < addressFields.FieldCount; i++)
                                                    {
                                                        IField addressField = addressFields.get_Field(i);
                                                        string tempVal = addressProperties.GetProperty(addressField.Name).ToString();

                                                        inFeature.set_Value(fieldNum, tempVal);

                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: GET_ADDRESS_USING_GEOCODER" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: GET_ADDRESS_USING_GEOCODER");
                                                }
                                                break;

                                            }
                                            break;

                                        case "GET_ADDRESS_USING_ARCGIS_SERVICE":  //ARGS: url
                                            try
                                            {
                                                AAState.WriteLine("                  Trying GET_ADDRESS_USING_ARCGIS_SERVICE");
                                                if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                {
                                                    if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                    {

                                                        IPoint revGCLoc = Globals.GetGeomCenter(inFeature);

                                                        if (revGCLoc != null)
                                                        {
                                                            //Test for user specified URL
                                                            if (Globals.IsUrl(valData))
                                                            {
                                                                locatorURL = valData;
                                                                /////locatorURL.TrimEnd(char[] );
                                                                if (!(locatorURL.EndsWith(reverseGeocode)))
                                                                    locatorURL += reverseGeocode;
                                                            }

                                                            //If no valid user speficied URL, test for keywords for North America or European Union locators
                                                            else if (valData == "ESRI_Geocode_NA" || valData == "ESRI_Geocode_EU")
                                                                locatorURL = _agsOnlineLocators + valData + reverseGeocode;
                                                            else if (valData == "TA_Streets_US " || valData == "TA_Address_NA" || valData == "TA_Address_EU")
                                                                locatorURL = _agsOnlineLocators + valData + reverseGeocode;
                                                            //Default to AGS Online USA geocode service

                                                            else if (_agsOnlineLocators.Substring(_agsOnlineLocators.LastIndexOf('/', _agsOnlineLocators.Length - 2)).Contains("Locator"))
                                                                locatorURL = _agsOnlineLocators + "TA_Address_NA" + reverseGeocode;
                                                            else
                                                                locatorURL = _agsOnlineLocators + reverseGeocode;

                                                            //Copy point from this current feature
                                                            _copyPoint = revGCLoc;//inFeature.ShapeCopy as IPoint;

                                                            //Project point to WGS84
                                                            _copyPoint.Project(AAState.srWGS84);

                                                            //Include location parameters in URL
                                                            string results = Globals.FormatLocationRequest(locatorURL, _copyPoint.X, _copyPoint.Y, 100);

                                                            //Send and receieve the request
                                                            WebRequest req = WebRequest.Create(results);
                                                            WebResponse res = req.GetResponse();

                                                            //Convert response from JSON to XML
                                                            XmlDocument doc = new XmlDocument();
                                                            using (Stream s = res.GetResponseStream())
                                                            {
                                                                XmlDictionaryReader xr = JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max);
                                                                doc.Load(xr);
                                                                xr.Close();
                                                                s.Close();

                                                                //Store Address element from Address Results in the specified field
                                                                //if (mode == "ON_CREATE")
                                                                //{
                                                                //    inFeature.set_Value(fieldNum, doc.DocumentElement.FirstChild.FirstChild.InnerText.Replace("    ", " "));
                                                                //}
                                                                //else//on change
                                                                //{
                                                                //    if (inFeature.Fields.get_Field(fieldNum).DefaultValue == inFeature.get_Value(fieldNum))
                                                                //    //if (inFeature.get_Value(fieldNum).ToString() != "")
                                                                //    {
                                                                //        inFeature.set_Value(fieldNum, doc.DocumentElement.FirstChild.FirstChild.InnerText.Replace("    ", " "));
                                                                //    }
                                                                //}
                                                                inFeature.set_Value(fieldNum, doc.DocumentElement.FirstChild.FirstChild.InnerText.Replace("    ", " "));

                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Could not get location to Reverse Geocode");
                                                        }
                                                    }

                                                }

                                            }
                                            catch
                                            {
                                                AAState.WriteLine("                  ERROR: GET_ADDRESS_USING_ARCGIS_SERVICE");
                                            }

                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GET_ADDRESS_USING_ARCGIS_SERVICE");
                                            }
                                            break;
                                        case "TIMESTAMP":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TIMESTAMP");
                                                if (fieldObj.Type == esriFieldType.esriFieldTypeDate)
                                                    inObject.set_Value(fieldNum, DateTime.Now);
                                                else if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                    inObject.set_Value(fieldNum, DateTime.Now.ToString());

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TIMESTAMP " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TIMESTAMP");
                                            }
                                            break;

                                        case "LAST_VALUE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LAST_VALUE");
                                                if (mode == "ON_CREATE")
                                                {

                                                    lastValue = AAState.lastValueProperties.GetProperty(fieldName);
                                                    if (lastValue != null)
                                                    {
                                                        inObject.set_Value(fieldNum, lastValue);
                                                        AAState.WriteLine("                  " + fieldName + ": " + lastValue);
                                                    }
                                                }
                                                else if (mode == "ON_CHANGE" && inObject.get_Value(fieldNum) == null)
                                                {
                                                    lastValue = AAState.lastValueProperties.GetProperty(fieldName);
                                                    if (lastValue != null)
                                                    {
                                                        inObject.set_Value(fieldNum, lastValue);
                                                        AAState.WriteLine("                  " + fieldName + ": " + lastValue);
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LAST_VALUE " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LAST_VALUE");
                                            }
                                            break;

                                        case "X_COORDINATE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: X_COORDINATE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {
                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.Shape as IPoint;
                                                        inFeature.set_Value(fieldNum, _copyPoint.X);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).X);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.FromPoint.X);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.ToPoint.X);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).X);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolygon).X);
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: X_COORDINATE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: X_COORDINATE");
                                            }
                                            break;

                                        case "Y_COORDINATE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: Y_COORDINATE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {
                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.Shape as IPoint;
                                                        inFeature.set_Value(fieldNum, _copyPoint.Y);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).Y);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.FromPoint.Y);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.ToPoint.Y);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).Y);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;

                                                        inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolygon).Y);
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: Y_COORDINATE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: Y_COORDINATE");
                                            }
                                            break;

                                        case "LATITUDE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LATITUDE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {

                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.ShapeCopy as IPoint;
                                                        _copyPoint.Project(AAState._sr1);

                                                        inFeature.set_Value(fieldNum, _copyPoint.Y);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.ShapeCopy as IPolyline;
                                                        _copyPolyline.Project(AAState._sr1);

                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).X);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.FromPoint.X);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.ToPoint.X);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).X);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;
                                                        _copyPolygon.Project(AAState._sr1);

                                                        inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolygon).X);
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  Error: LATITUDE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LATITUDE");
                                            }
                                            break;

                                        case "LONGITUDE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LONGITUDE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {

                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.ShapeCopy as IPoint;
                                                        _copyPoint.Project(AAState._sr1);

                                                        inFeature.set_Value(fieldNum, _copyPoint.Y);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        _copyPolyline.Project(AAState._sr1);

                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).Y);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.FromPoint.Y);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(fieldNum, _copyPolyline.ToPoint.Y);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolyline).Y);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;
                                                        _copyPolygon.Project(AAState._sr1);

                                                        inFeature.set_Value(fieldNum, Globals.GetGeomCenter(_copyPolygon).Y);
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LONGITUDE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LONGITUDE");
                                            }
                                            break;

                                        case "FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: Field");
                                                // verify that field to copy exists
                                                fieldCopy = inObject.Fields.FindField(valData as string);
                                                if (fieldCopy > -1)
                                                {
                                                    if (mode == "ON_CREATE")
                                                    {
                                                        inObject.set_Value(fieldNum, inObject.get_Value(fieldCopy));
                                                    }
                                                    if (mode == "ON_CHANGE")
                                                    {
                                                        //copy value only if current field is empty
                                                        if (inObject.get_Value(fieldNum).ToString() == "")
                                                            inObject.set_Value(fieldNum, inObject.get_Value(fieldCopy));
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  " + valData + " is not found");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: Field: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: Field");
                                            }
                                            break;

                                        //CURRENT_USER
                                        //Value Data options:
                                        //U - windows username only
                                        //W or (blank) - full username including domain i.e. domain\username
                                        //D - database user if available and not dbo
                                        case "CURRENT_USER":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: CURRENT_USER");
                                                lastEditorName = AAState._currentUserInfo.GetCurrentUser(valData, fieldObj.Length);

                                                if (!String.IsNullOrEmpty(lastEditorName))
                                                {
                                                    inObject.set_Value(fieldNum, lastEditorName);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: CURRENT_USER: "******"                  Finished: CURRENT_USER");
                                            }
                                            break;

                                        case "JUNCTION_ROTATION":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: JUNCTION_ROTATION");
                                                if ((inFeature != null))
                                                {
                                                    AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolGeographic;
                                                    args = null;

                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args[0].Length == 0)
                                                        {
                                                            if (args[0].Substring(0, 1).ToLower() == "a")
                                                                AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                                                        }
                                                        if (args[0].Length == 1)
                                                        {
                                                            if (args[0].Substring(0, 1).ToLower() == "a")
                                                                AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                                                            if (Globals.IsNumeric(args[1].ToString()))
                                                                AAState.rCalc.SpinAngle = Convert.ToDouble(args[1]);

                                                        }
                                                    }
                                                    AAState.WriteLine("                  " + AAState.rCalc.RotationType.ToString() + " is being used");
                                                    rotationAngle = AAState.rCalc.GetRotationUsingConnectedEdges(inFeature);
                                                    if (rotationAngle == null)
                                                    {
                                                        AAState.WriteLine("                  Rotation Angle not found or errored out");
                                                        continue;
                                                    }

                                                    //Accept optional second argument to provide extra rotation
                                                    //if ((args != null) && (args.Length > 1) && (Globals.IsInteger(args[1])))
                                                    //    rotationAngle += System.Convert.ToInt32(args[1]);
                                                    if (rotationAngle != -1)
                                                        inObject.set_Value(fieldNum, rotationAngle);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: JUNCTION_ROTATION \r\n" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: JUNCTION_ROTATION");
                                            }
                                            break;

                                        //For Release: 1.2
                                        //New Dynamic Value Method: Length - stores calculated length of line feature
                                        case "LENGTH":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LENGTH");
                                                if (inFeature != null)
                                                {
                                                    curve = (ICurve)inFeature.Shape;
                                                    if (curve != null)
                                                    {
                                                        inObject.set_Value(fieldNum, curve.Length);
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LENGTH: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LENGTH");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: SET_MEASURES - stores calculated M values (from 0 to length of line) for line feature
                                        //Value Data options:
                                        //P = Percent - Ms will be zero to 100
                                        //default - Ms will be zero to length of line
                                        case "SET_MEASURES":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: SET_MEASURES");
                                                if (inFeature != null)
                                                {
                                                    curve = inFeature.Shape as ICurve;
                                                    mseg = inFeature.Shape as IMSegmentation;
                                                    if (curve != null && mseg != null)
                                                        if (valData != null && valData != "" && valData.Substring(0, 1).ToUpper() == "P")
                                                            mseg.SetAndInterpolateMsBetween(0, 100);
                                                        else
                                                            mseg.SetAndInterpolateMsBetween(0, curve.Length);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: SET_MEASURES: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: SET_MEASURES");
                                            }
                                            break;
                                        //case "EDGE_INTERSECT_SECOND":
                                        //    try
                                        //    {
                                        //        if (inFeature != null)
                                        //        {
                                        //            netFeat = inFeature as INetworkFeature;
                                        //            if (netFeat != null)
                                        //            {
                                        //                if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                        //                {

                                        //                    iJuncFeat = (IJunctionFeature)netFeat;
                                        //                    // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                        //                    ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                        //                    if (iSJunc == null)
                                        //                        break;
                                        //                    if (iSJunc.EdgeFeatureCount <= 1)
                                        //                        break;
                                        //                    edgeFeat = iSJunc.get_EdgeFeature(1);

                                        //                    // verify that field (in junction) to copy exists

                                        //                    IRow pRow = edgeFeat as IRow;

                                        //                    juncField = pRow.Fields.FindField(valData as string);
                                        //                    if (juncField > -1)
                                        //                    {
                                        //                        inObject.set_Value(fieldNum, pRow.get_Value(juncField));
                                        //                    }
                                        //                }
                                        //            }
                                        //        }
                                        //    }
                                        //    catch
                                        //    {
                                        //    }
                                        //    break;
                                        //case "EDGE_INTERSECT_FIRST":
                                        //    try
                                        //    {
                                        //        if (inFeature != null)
                                        //        {
                                        //            netFeat = inFeature as INetworkFeature;
                                        //            if (netFeat != null)
                                        //            {
                                        //                if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                        //                {

                                        //                    iJuncFeat = (IJunctionFeature)netFeat;
                                        //                    // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                        //                    ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                        //                    if (iSJunc == null)
                                        //                        break;
                                        //                    if (iSJunc.EdgeFeatureCount <= 0)
                                        //                        break;
                                        //                    edgeFeat = iSJunc.get_EdgeFeature(0);

                                        //                    IRow pRow = edgeFeat as IRow;

                                        //                    juncField = pRow.Fields.FindField(valData as string);
                                        //                    if (juncField > -1)
                                        //                    {
                                        //                        inObject.set_Value(fieldNum, pRow.get_Value(juncField));
                                        //                    }
                                        //                }
                                        //            }
                                        //        }
                                        //    }
                                        //    catch
                                        //    {
                                        //    }
                                        //    break;

                                        //Release: 2.0
                                        //New Dynamic Value Method: TO_EDGE_FIELD transfers a field value from a connected egde feature to a junction feature
                                        //Takes value from the frist edge whose "TO" point connects with this junction
                                        case "TO_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TO_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {

                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    edgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {
                                                                        juncFeat = (IFeature)edgeFeat.FromJunctionFeature;
                                                                        if (juncFeat.Shape.Equals(inFeature.Shape))
                                                                        {
                                                                            IRow pRow = edgeFeat as IRow;

                                                                            // verify that field (in junction) to copy exists
                                                                            juncField = pRow.Fields.FindField(valData as string);
                                                                            if (juncField > -1)
                                                                            {
                                                                                inObject.set_Value(fieldNum, pRow.get_Value(juncField));
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  " + valData + " field not found in edge");
                                                                            }
                                                                            break;

                                                                        }
                                                                    }
                                                                    catch
                                                                    {
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_FIELD");
                                            }
                                            break;

                                        //Release: 2.0
                                        //New Dynamic Value Method: FROM_EDGE_FIELD transfers a field value from a connected egde feature to a junction feature
                                        //Takes value from the frist edge whose "FROM" point connects with this junction
                                        case "FROM_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FROM_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {

                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                            {
                                                                edgeFeat = iSJunc.get_EdgeFeature(i);
                                                                try
                                                                {
                                                                    juncFeat = (IFeature)edgeFeat.ToJunctionFeature;
                                                                    if (juncFeat.Shape.Equals(inFeature.Shape))
                                                                    {
                                                                        IRow pRow = edgeFeat as IRow;

                                                                        // verify that field (in junction) to copy exists
                                                                        juncField = pRow.Fields.FindField(valData as string);
                                                                        if (juncField > -1)
                                                                        {
                                                                            inObject.set_Value(fieldNum, pRow.get_Value(juncField));
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  " + valData + " field not found");
                                                                        }
                                                                        break;

                                                                    }

                                                                }

                                                                catch
                                                                {
                                                                    AAState.WriteLine("                  error ");
                                                                }
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FROM_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FROM_EDGE_FIELD");
                                            }
                                            break;

                                        case "FROM_JUNCTION_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FROM_JUNCTION_FIELD");
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                        {
                                                            edgeFeat = (IEdgeFeature)netFeat;
                                                            juncFeat = (IFeature)edgeFeat.FromJunctionFeature;

                                                            // verify that field (in junction) to copy exists
                                                            juncField = juncFeat.Fields.FindField(valData as string);
                                                            if (juncField > -1)
                                                            {
                                                                inObject.set_Value(fieldNum, juncFeat.get_Value(juncField));
                                                            }
                                                            else
                                                                AAState.WriteLine("                  " + valData + " field not found");
                                                        }
                                                        else
                                                            AAState.WriteLine("                  not an edge feature");
                                                    }
                                                    else
                                                        AAState.WriteLine("                  Not a network feature");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FROM_JUNCTION_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FROM_JUNCTION_FIELD");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: TO_JUNCTION_FIELD transfers a field value from a junction connected at terminal end of a line feature
                                        case "TO_JUNCTION_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TO_JUNCTION_FIELD");
                                                if (inFeature != null)
                                                {

                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                        {
                                                            edgeFeat = (IEdgeFeature)netFeat;
                                                            juncFeat = (IFeature)edgeFeat.ToJunctionFeature;

                                                            // verify that field (in junction) to copy exists
                                                            juncField = juncFeat.Fields.FindField(valData as string);
                                                            if (juncField > -1)
                                                            {
                                                                inObject.set_Value(fieldNum, juncFeat.get_Value(juncField));
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  Trying: TO_JUNCTION_FIELD");
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an edge feature");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  not an geometric network feature");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_JUNCTION_FIELD:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_JUNCTION_FIELD");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: GENERATE_ID - uses value in specificed table and increments it as specified
                                        case "GENERATE_ID":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: GENERATE_ID");
                                                if (AAState._gentab != null)
                                                {
                                                    sequenceColumnName = "";
                                                    sequenceColumnNum = -1;
                                                    sequenceValue = -1;
                                                    sequenceFixedWidth = "";
                                                    sequencePadding = 0;
                                                    formatString = "";

                                                    // Parse arguments
                                                    if (valData == null) break;
                                                    args = valData.Split('|');
                                                    switch (args.GetLength(0))
                                                    {
                                                        case 1:  // sequenceColumnName only
                                                            sequenceColumnName = args[0].ToString(); break;
                                                        case 2:  // sequenceColumnName|sequenceFixedWidth
                                                            sequenceColumnName = args[0].ToString();
                                                            sequenceFixedWidth = args[1].ToString();
                                                            break;
                                                        case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                            sequenceColumnName = args[0].ToString();
                                                            sequenceFixedWidth = args[1].ToString();
                                                            formatString = args[2].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    //Check for requested zero padding of sequence number
                                                    if (sequenceFixedWidth != "")
                                                        int.TryParse(sequenceFixedWidth.ToString(), out sequencePadding);
                                                    if (sequencePadding > 25)
                                                    {

                                                        AAState.WriteLine("                  WARNING: you are trying to pad your id with a more than 25 - 0's");
                                                        AAState.WriteLine("                  WARNING: " + sequencePadding + " 0's is what you have");

                                                    }
                                                    else if (sequencePadding > 50)
                                                    {
                                                        MessageBox.Show("You are trying to add 50 places to your ID, this is not supported, please fix your dynamic value table");
                                                    }

                                                    //Check for sequence column in generate id table
                                                    sequenceColumnNum = AAState._gentab.FindField(sequenceColumnName);
                                                    if (AAState._gentab.FindField(sequenceColumnName) >= 0)
                                                    {
                                                        //get value of first row, increment it, and return incremented value
                                                        for (int j = 0; j < 51; j++)
                                                        {
                                                            row = AAState._gentab.Update(null, false).NextRow();
                                                            if (row == null)
                                                            {
                                                                break;
                                                            }
                                                            if (row.get_Value(sequenceColumnNum) == null)
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else if (row.get_Value(sequenceColumnNum).ToString() == "")
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else
                                                                sequenceValue = Convert.ToInt32(row.get_Value(sequenceColumnNum));

                                                            sequenceValue += 1;
                                                            // _editEvents.OnChangeFeature -= OnChangeFeature;
                                                            // _editEvents.OnCreateFeature -= OnCreateFeature;

                                                            row.set_Value(sequenceColumnNum, sequenceValue);
                                                            AAState.WriteLine("                  " + row.Fields.get_Field(sequenceColumnNum).AliasName + " changed to " + sequenceValue);

                                                            row.Store();
                                                            //  _editEvents.OnChangeFeature += OnChangeFeature;
                                                            //  _editEvents.OnCreateFeature += OnCreateFeature;
                                                            if (Convert.ToInt32(row.get_Value(sequenceColumnNum)) == sequenceValue)
                                                                break;

                                                        }
                                                        if (sequenceValue == -1)
                                                        {
                                                            AAState.WriteLine("                  ERROR: GENERATE_ID: Sequence Not Found");
                                                        }

                                                        else
                                                        {
                                                            if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeString)
                                                                if (formatString == null || formatString == "" || formatString.ToLower().IndexOf("[seq]") == -1)
                                                                {
                                                                    string setVal = (sequenceValue.ToString("D" + sequencePadding) + sequencePostfix).ToString();

                                                                    if (inObject.Fields.get_Field(fieldNum).Length < setVal.Length && inObject.Fields.get_Field(fieldNum).Length != 0)
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: " + sequenceValue + " is to long for field " + row.Fields.get_Field(sequenceColumnNum).AliasName);
                                                                    }
                                                                    else
                                                                    {
                                                                        inObject.set_Value(fieldNum, sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);
                                                                        AAState.WriteLine("                  " + inObject.Fields.get_Field(fieldNum).AliasName + " set to " + sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);

                                                                    }

                                                                }
                                                                else
                                                                {

                                                                    int locIdx = formatString.ToUpper().IndexOf("[SEQ]");
                                                                    if (locIdx >= 0)
                                                                    {
                                                                        formatString = formatString.Remove(locIdx, 5);
                                                                        formatString = formatString.Insert(locIdx, sequenceValue.ToString("D" + sequencePadding));
                                                                    }
                                                                    //formatString = formatString.Replace("[seq]", sequenceValue.ToString("D" + sequencePadding));

                                                                    if (inObject.Fields.get_Field(fieldNum).Length < formatString.Length && inObject.Fields.get_Field(fieldNum).Length != 0)
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: " + formatString + " is to long for field " + row.Fields.get_Field(sequenceColumnNum).AliasName);
                                                                    }
                                                                    else
                                                                    {
                                                                        inObject.set_Value(fieldNum, formatString);
                                                                        AAState.WriteLine("                  " + inObject.Fields.get_Field(fieldNum).AliasName + " set to " + formatString);
                                                                    }

                                                                }
                                                            else
                                                            {

                                                                inObject.set_Value(fieldNum, sequenceValue);
                                                                AAState.WriteLine("                  " + sequenceColumnNum + " changed to " + sequenceValue);
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Sequence Field not found");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: GENERATE_ID table is not found");

                                                }

                                            }

                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GENERATE_ID: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GENERATE_ID");
                                            }
                                            break;

                                        case "GENERATE_ID_BY_INTERSECT":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: GENERATE_ID_BY_INTERSECT");
                                                if (AAState._gentab != null && inFeature != null && !(inFeature.Shape.IsEmpty))
                                                {
                                                    sequenceColumnName = "";
                                                    sequenceColumnNum = -1;
                                                    sequenceValue = -1;
                                                    sequenceFixedWidth = "";
                                                    sequencePadding = 0;
                                                    //genIdAreaFieldName = "";
                                                    intersectLayerName = "";
                                                    intersectLayerFieldName = "";
                                                    formatString = "";
                                                    intersectFieldPos = -1;

                                                    // Parse arguments
                                                    if (valData == null) break;

                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) < 3)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Improper value method");
                                                        break;
                                                    }
                                                    switch (args.GetLength(0))
                                                    {
                                                        case 3:  //columnName
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            // genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            break;
                                                        case 4:  // columnName|sequenceFixedWidth
                                                            //sequenceFixedWidth formats the sequence with leading zeros to create specified width
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            //genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            sequenceFixedWidth = Convert.ToString(0);
                                                            formatString = args[3].ToString();

                                                            break;
                                                        case 5:  // columnName|sequenceFixedWidth|formatString
                                                            //formatString must contain [seq] and [id]  and may contain [area] plus any desired text
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            //genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            sequenceFixedWidth = args[3].ToString();
                                                            formatString = args[4].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    //Find Area Layer
                                                    // FindLayerByName(areaLayerName, out areaLayer);
                                                    intersectLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, intersectLayerName);
                                                    if (intersectLayer == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature Layer(" + intersectLayerName + ") not found");
                                                        break;
                                                    }
                                                    //Find Area Field
                                                    intersectFieldPos = intersectLayer.FeatureClass.FindField(intersectLayerFieldName);
                                                    if (intersectFieldPos < 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature Layer Field(" + intersectLayerFieldName + ") not found");
                                                        break;
                                                    }

                                                    //Find GenID Area Field
                                                    //genIdAreaFieldPos = areaLayer.FeatureClass.FindField(genIdAreaFieldName);
                                                    //if (genIdAreaFieldPos < 0) break;

                                                    //Perform spatial search
                                                    IGeometry pSearchGeo = (IGeometry)inFeature.ShapeCopy;
                                                    pSearchGeo.SpatialReference = (inFeature.Class as IGeoDataset).SpatialReference;
                                                    pSearchGeo.Project((intersectLayer as IGeoDataset).SpatialReference);
                                                    sFilter = new SpatialFilterClass();
                                                    sFilter.Geometry = pSearchGeo;
                                                    sFilter.GeometryField = intersectLayer.FeatureClass.ShapeFieldName;
                                                    sFilter.SubFields = intersectLayerFieldName;
                                                    sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                                    fCursor = intersectLayer.FeatureClass.Search(sFilter, true);
                                                    sourceFeature = fCursor.NextFeature();
                                                    if (sourceFeature != null)
                                                        intersectValue = sourceFeature.get_Value(intersectFieldPos).ToString();
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature not found");
                                                        break;
                                                    }
                                                    //Check for requested zero padding of sequence number
                                                    if (sequenceFixedWidth != "")
                                                        int.TryParse(sequenceFixedWidth.ToString(), out sequencePadding);

                                                    if (sequencePadding > 25)
                                                    {
                                                        AAState.WriteLine("                  WARNING: you are trying to pad your id with a more than 25 - 0's");
                                                        AAState.WriteLine("                  WARNING: " + sequencePadding + " 0's is what you have");

                                                    }

                                                    sequenceColumnName = sequenceColumnName + intersectValue;
                                                    AAState.WriteLine("                  Looking for a field called " + sequenceColumnName + " in the generate ID table");
                                                    sequenceColumnNum = AAState._gentab.FindField(sequenceColumnName);
                                                    if (sequenceColumnNum > -1)
                                                    {
                                                        AAState.WriteLine("                  Field Found");

                                                        //get value of first row, increment it, and return incremented value
                                                        for (int j = 0; j < 51; j++)
                                                        {
                                                            row = AAState._gentab.Update(qFilter, false).NextRow();
                                                            if (row.get_Value(sequenceColumnNum) == null)
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else if (row.get_Value(sequenceColumnNum).ToString() == "")
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else
                                                                sequenceValue = Convert.ToInt32(row.get_Value(sequenceColumnNum));
                                                            sequenceValue += 1;
                                                            row.set_Value(sequenceColumnNum, sequenceValue);
                                                            row.Store();
                                                            if (Convert.ToInt32(row.get_Value(sequenceColumnNum)) == sequenceValue)
                                                                break;

                                                        }
                                                        if (sequenceValue == -1)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Sequence number not found");
                                                        }
                                                        else
                                                        {
                                                            if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeString)
                                                                if (formatString == null || formatString == "" || (formatString.ToUpper().IndexOf("[SEQ]") == -1 && formatString.ToUpper().IndexOf("[ID]") == -1))
                                                                    inObject.set_Value(fieldNum, intersectValue + sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);
                                                                else
                                                                {

                                                                    int locIdx = formatString.ToUpper().IndexOf("[ID]");
                                                                    if (locIdx >= 0)
                                                                    {
                                                                        formatString = formatString.Remove(locIdx, 4);
                                                                        formatString = formatString.Insert(locIdx, intersectValue);
                                                                    }
                                                                    //  formatString = formatString.Replace("[id]", intersectValue);
                                                                    // formatString = formatString.Replace("[seq]", sequenceValue.ToString("D" + sequencePadding));
                                                                    locIdx = formatString.ToUpper().IndexOf("[SEQ]");
                                                                    if (locIdx >= 0)
                                                                    {
                                                                        formatString = formatString.Remove(locIdx, 5);
                                                                        formatString = formatString.Insert(locIdx, sequenceValue.ToString());
                                                                    }
                                                                    //
                                                                    inObject.set_Value(fieldNum, formatString);
                                                                }
                                                            else
                                                                inObject.set_Value(fieldNum, sequenceValue);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Field NOT Found");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: GENERATE_ID table is not found");

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GENERATE_ID_BY_INTERSECT: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GENERATE_ID_BY_INTERSECT");
                                            }
                                            break;
                                        //Modified for Release 1.2  (No longer uses ICalculator)
                                        //Requires valid VBScript expression
                                        //Can include string, numeric, and date fields by name in square brackets []
                                        //Example: DateDiff("yyyy",[INSTALLDATE],Now())
                                        case "GENERATE_ID_BY_AREA":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: GENERATE_ID_BY_AREA");
                                                if (AAState._gentab != null && inFeature != null && !(inFeature.Shape.IsEmpty))
                                                {
                                                    sequenceColumnName = "";
                                                    sequenceColumnNum = -1;
                                                    sequenceValue = -1;
                                                    sequenceFixedWidth = "";
                                                    sequencePadding = 0;
                                                    genIdAreaFieldName = "";
                                                    areaLayerName = "";
                                                    areaLayerFieldName = "";
                                                    formatString = "";

                                                    // Parse arguments
                                                    if (valData == null) break;

                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) < 3)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Improper Value Method");
                                                        break;
                                                    }
                                                    switch (args.GetLength(0))
                                                    {
                                                        case 4:  //columnName
                                                            areaLayerName = args[0].ToString();
                                                            areaLayerFieldName = args[1].ToString();
                                                            genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[3].ToString();
                                                            break;
                                                        case 5:  // columnName|sequenceFixedWidth
                                                            //sequenceFixedWidth formats the sequence with leading zeros to create specified width
                                                            areaLayerName = args[0].ToString();
                                                            areaLayerFieldName = args[1].ToString();
                                                            genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[3].ToString();
                                                            sequenceFixedWidth = args[4].ToString();
                                                            break;
                                                        case 6:  // columnName|sequenceFixedWidth|formatString
                                                            //formatString must contain [seq] and may contain [area] plus any desired text
                                                            areaLayerName = args[0].ToString();
                                                            areaLayerFieldName = args[1].ToString();
                                                            genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[3].ToString();
                                                            sequenceFixedWidth = args[4].ToString();
                                                            formatString = args[5].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    //Find Area Layer
                                                    // FindLayerByName(areaLayerName, out areaLayer);
                                                    areaLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, areaLayerName);
                                                    if (areaLayer == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Area Layer not found: " + areaLayerName);
                                                        break;
                                                    }

                                                    //Find Area Field
                                                    areaFieldPos = areaLayer.FeatureClass.FindField(areaLayerFieldName);
                                                    if (areaFieldPos < 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Area Layer field not found: " + areaLayerFieldName);
                                                        break;
                                                    }

                                                    //Find GenID Area Field
                                                    //genIdAreaFieldPos = areaLayer.FeatureClass.FindField(genIdAreaFieldName);
                                                    //if (genIdAreaFieldPos < 0) break;

                                                    //Perform spatial search
                                                    sFilter = new SpatialFilterClass();
                                                    sFilter.Geometry = (IGeometry)inFeature.ShapeCopy;
                                                    sFilter.GeometryField = areaLayer.FeatureClass.ShapeFieldName;
                                                    sFilter.SubFields = areaLayerFieldName;
                                                    sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                                    fCursor = areaLayer.FeatureClass.Search(sFilter, true);
                                                    sourceFeature = fCursor.NextFeature();
                                                    if (sourceFeature != null)
                                                        areaValue = sourceFeature.get_Value(areaFieldPos).ToString();
                                                    else
                                                        break;

                                                    //Check for requested zero padding of sequence number
                                                    if (sequenceFixedWidth != "")
                                                        int.TryParse(sequenceFixedWidth.ToString(), out sequencePadding);

                                                    sequenceColumnNum = AAState._gentab.FindField(sequenceColumnName);
                                                    if (sequenceColumnNum > -1)
                                                    {
                                                        qFilter = new QueryFilterClass();
                                                        qFilter.SubFields = areaLayerFieldName + "," + sequenceColumnName;

                                                        ISQLSyntax sqlSyntax = (ISQLSyntax)AAState._editor.EditWorkspace;
                                                        char[] charBuf = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix).ToCharArray();
                                                        string strSC = new string(charBuf);
                                                        switch (strSC)
                                                        {
                                                            case "":
                                                                qFilter.WhereClause = genIdAreaFieldName + " = '" + areaValue + "'";
                                                                break;
                                                            case "[":
                                                                qFilter.WhereClause = "[" + genIdAreaFieldName + "]" + " = '" + areaValue + "'";
                                                                break;
                                                            default:
                                                                qFilter.WhereClause = "\"" + genIdAreaFieldName + "\" = '" + areaValue + "'";
                                                                break;
                                                        }

                                                        //get value of first row, increment it, and return incremented value
                                                        for (int j = 0; j < 51; j++)
                                                        {
                                                            row = AAState._gentab.Update(qFilter, false).NextRow();
                                                            if (row.get_Value(sequenceColumnNum) == null)
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else if (row.get_Value(sequenceColumnNum).ToString() == "")
                                                            {
                                                                sequenceValue = 0;
                                                            }
                                                            else
                                                                sequenceValue = Convert.ToInt32(row.get_Value(sequenceColumnNum));
                                                            sequenceValue += 1;
                                                            sequenceValue += 1;
                                                            row.set_Value(sequenceColumnNum, sequenceValue);
                                                            row.Store();
                                                            if (Convert.ToInt32(row.get_Value(sequenceColumnNum)) == sequenceValue)
                                                                break;

                                                        }
                                                        if (sequenceValue == -1)
                                                        {
                                                            //TODO raise error
                                                        }
                                                        else
                                                        {
                                                            if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeString)
                                                                if (formatString == null || formatString == "" || formatString.IndexOf("[seq]") == -1)
                                                                    inObject.set_Value(fieldNum, areaValue + sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);
                                                                else
                                                                {
                                                                    formatString = formatString.Replace("[area]", areaValue);
                                                                    formatString = formatString.Replace("[seq]", sequenceValue.ToString("D" + sequencePadding));
                                                                    inObject.set_Value(fieldNum, formatString);
                                                                }
                                                            else
                                                                inObject.set_Value(fieldNum, sequenceValue);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: GENERATE_ID table is not found");

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GENERATE_ID_BY_AREA: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GENERATE_ID_BY_AREA");
                                            }

                                            break;
                                        //Modified for Release 1.2  (No longer uses ICalculator)
                                        //Requires valid VBScript expression
                                        //Can include string, numeric, and date fields by name in square brackets []
                                        //Example: DateDiff("yyyy",[INSTALLDATE],Now())
                                        case "EXPRESSION":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: EXPRESSION");
                                                if (inObject != null & valData != null)
                                                {
                                                    newValue = valData;
                                                    for (int i = 0; i < inObject.Fields.FieldCount; i++)
                                                    {
                                                        testField = inObject.Fields.get_Field(i);

                                                        int indFld = newValue.ToUpper().IndexOf("[" + testField.Name.ToUpper() + "]");
                                                        while (indFld >= 0)
                                                        {
                                                            AAState.WriteLine("                  replace field: " + testField.Name + " with a value");
                                                            int fldLen = testField.Name.Length;
                                                            string tmpStr1 = newValue.Substring(0, indFld + 1);
                                                            string tmpStr2 = newValue.Substring(indFld + fldLen + 1);
                                                            newValue = tmpStr1 + "_REPLACE_VAL_" + tmpStr2;

                                                            switch (testField.Type)
                                                            {
                                                                case esriFieldType.esriFieldTypeString:

                                                                    if (inObject.get_Value(i) == null || inObject.get_Value(i).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(i) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", null);
                                                                        }
                                                                        else if (inObject.get_Value(i).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                        }
                                                                    }

                                                                    // newValue = newValue.Replace("[" + testField.Name + "]", "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                    break;
                                                                case esriFieldType.esriFieldTypeDate:

                                                                    if (inObject.get_Value(i) == null || inObject.get_Value(i).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(i) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "CDATE(" + null + ")");
                                                                        }
                                                                        else if (inObject.get_Value(i).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "CDATE(\"" + inObject.get_Value(i).ToString() + "\")");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "CDATE(\"" + inObject.get_Value(i).ToString() + "\")");
                                                                        }
                                                                    }

                                                                    // newValue = newValue.Replace("[" + testField.Name + "]", "CDATE(\"" + inObject.get_Value(i).ToString() + "\")");
                                                                    break;

                                                                default:
                                                                    if (inObject.get_Value(i) == null || inObject.get_Value(i).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(i) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", null);
                                                                        }
                                                                        else if (inObject.get_Value(i).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", null);// "\"" + inObject.get_Value(i).ToString() + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "" + inObject.get_Value(i).ToString() + "");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", inObject.get_Value(i).ToString());
                                                                        }
                                                                    }
                                                                    //  newValue = newValue.Replace("[" + testField.Name + "]", inObject.get_Value(i).ToString());
                                                                    break;
                                                            }
                                                            indFld = newValue.ToUpper().IndexOf("[" + testField.Name.ToUpper() + "]");
                                                        }
                                                    }
                                                    //MessageBox.Show(newValue);

                                                    try
                                                    {
                                                        newValue = script.Eval(newValue).ToString();
                                                        if (inObject.get_Value(fieldNum).ToString() != newValue)
                                                            inObject.set_Value(fieldNum, newValue);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        AAState.WriteLine("                  ERROR: evaluating the expression for feature in " + inObject.Class.AliasName + " with OID of " + inObject.OID);
                                                        AAState.WriteLine("                         " + ex.Message);
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: EXPRESSION: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: EXPRESSION");
                                            }
                                            break;

                                        // GUID values are calculated into text fields or into native GUID field types
                                        // When using text field you have an optional argument (valdata) to specify the format
                                        // N-none 32 chars, D-dash 36, B-braces 38, P-Parenthesis 38
                                        case "GUID":
                                            try
                                            {
                                                if (inObject != null)
                                                {
                                                    if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeGUID)
                                                        inObject.set_Value(fieldNum, System.Guid.NewGuid().ToString("B"));
                                                    else if (inObject.Fields.get_Field(fieldNum).Type == esriFieldType.esriFieldTypeString &&
                                                             inObject.Fields.get_Field(fieldNum).Length >= 32)
                                                    {

                                                        valData = valData.Trim();
                                                        if (valData != "N" && valData != "D" && valData != "B" && valData != "P")
                                                            if (inObject.Fields.get_Field(fieldNum).Length >= 38)
                                                                valData = "B";  //Default to braces
                                                            else if (inObject.Fields.get_Field(fieldNum).Length < 36)
                                                                valData = "N";
                                                            else
                                                                valData = "D";
                                                        inObject.set_Value(fieldNum, System.Guid.NewGuid().ToString(valData));
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: EXPRESSION: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: EXPRESSION");
                                            }
                                            break;

                                        case "CREATE_LINKED_RECORD"://Feature Layer|Field To Copy|Field To Populate|Primary Key Field|Foreign Key Field
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying: CREATE_LINKED_RECORD");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 5)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inFeature == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    AAState.WriteLine("                  Getting Value Info");
                                                    sourceLayerNames = args[0].ToString().Split(',');
                                                    sourceFieldName = args[1].ToString();
                                                    string targetFieldName = args[2].ToString();
                                                    string sourceIDFieldName = args[3].ToString();
                                                    string targetIDFieldName = args[4].ToString();
                                                    AAState.WriteLine("                  Checking values");
                                                    if (sourceFieldName != null)
                                                    {
                                                        AAState.WriteLine("                  Checking Fields in Source Layer");
                                                        int fldValToCopyIdx = inObject.Fields.FindField(sourceFieldName);
                                                        int fldIDToCopyIdx = inObject.Fields.FindField(sourceIDFieldName);
                                                        if (fldValToCopyIdx > -1 && fldIDToCopyIdx > -1)
                                                        {

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString();

                                                                if (sourceLayerName != "")
                                                                {

                                                                    // Get layer
                                                                    AAState.WriteLine("                  Checking for table to populate");
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);

                                                                    if (sourceLayer != null)
                                                                    {

                                                                    }
                                                                    else
                                                                    {
                                                                        ITable pTable = Globals.FindTable(AAState._editor.Map, sourceLayerName);
                                                                        if (pTable != null)
                                                                        {
                                                                            int fldValToPopIdx = pTable.Fields.FindField(targetFieldName);
                                                                            int fldIDToPopIdx = pTable.Fields.FindField(targetIDFieldName);
                                                                            if (fldValToPopIdx > -1 && fldIDToPopIdx > -1)
                                                                            {
                                                                                AAState.WriteLine("                  Trying to create a row in the target table");
                                                                                IRow pNewRow = pTable.CreateRow();
                                                                                AAState.WriteLine("                  Row Created");
                                                                                AAState.WriteLine("                  Trying to Copy ID");
                                                                                try
                                                                                {
                                                                                    pNewRow.set_Value(fldIDToPopIdx, inObject.get_Value(fldIDToCopyIdx));

                                                                                }
                                                                                catch
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldIDToCopyIdx) + " to field: " + targetIDFieldName);
                                                                                }
                                                                                AAState.WriteLine("                  ID successfully copied");
                                                                                AAState.WriteLine("                  Trying to Copy Value");
                                                                                try
                                                                                {
                                                                                    pNewRow.set_Value(fldValToPopIdx, inObject.get_Value(fldValToCopyIdx));

                                                                                }
                                                                                catch
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldValToCopyIdx) + " to field: " + targetFieldName);
                                                                                }
                                                                                AAState.WriteLine("                  Value successfully copied");
                                                                                pNewRow.Store();
                                                                                if (newFeatureList == null)
                                                                                {
                                                                                    newFeatureList = new List<IObject>();
                                                                                }
                                                                                IObject featobj = pNewRow as IObject;

                                                                                if (featobj != null)
                                                                                {
                                                                                    newFeatureList.Add(featobj);
                                                                                }

                                                                                AAState.WriteLine("                  Row successfully stored");
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR: Table to populate not found: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: ID or Field to Copy was not found");
                                                        }

                                                        //if ((!found) && (inObject.Fields.get_Field(fieldNum).IsNullable))
                                                        //{
                                                        //    inObject.set_Value(fieldNum, null);
                                                        //}
                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: CREATE_LINKED_RECORD" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: CREATE_LINKED_RECORD");
                                                    // fieldNum = -1;

                                                }
                                                break;

                                            }

                                        case "UPDATE_INTERSECTING_FEATURE"://Intersected Feature|FieldIntersectingFeatureToChange|FromFieldinModifiedFeature
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying: UPDATE_INTERSECTING_FEATURE");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 3)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inFeature == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    AAState.WriteLine("                  Getting Value Info");
                                                    sourceLayerNames = args[0].ToString().Split(',');
                                                    sourceFieldName = args[1].ToString();
                                                    string targetFieldName = args[2].ToString();
                                                    AAState.WriteLine("                  Checking values");
                                                    if (sourceFieldName != null)
                                                    {
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString();
                                                            if (sourceLayerName != "")
                                                            {
                                                                // Get layer
                                                                sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);

                                                                if (sourceLayer != null)
                                                                {
                                                                    if (inObject.Class != sourceLayer.FeatureClass)
                                                                    {
                                                                        if (Globals.IsEditable(sourceLayer, AAState._editor))
                                                                        {

                                                                            sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                            if (sourceField > -1)
                                                                            {
                                                                                sFilter = new SpatialFilterClass();
                                                                                if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                                                {

                                                                                    try
                                                                                    {
                                                                                        ISpatialReferenceResolution pSRResolution;

                                                                                        pSRResolution = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference) as ISpatialReferenceResolution;

                                                                                        //  sFilter = new SpatialFilterClass();
                                                                                        double intTol = pSRResolution.get_XYResolution(false);
                                                                                        bool hasXY = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference).HasXYPrecision();

                                                                                        searchEnvelope = new EnvelopeClass();
                                                                                        searchEnvelope.XMin = 0 - intTol;
                                                                                        searchEnvelope.YMin = 0 - intTol;
                                                                                        searchEnvelope.XMax = 0 + intTol;
                                                                                        searchEnvelope.YMax = 0 + intTol;
                                                                                        searchEnvelope.CenterAt(inFeature.ShapeCopy as IPoint);

                                                                                        //searchEnvelope.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                        searchEnvelope.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                        searchEnvelope.SnapToSpatialReference();
                                                                                        searchEnvelope.Project(AAState._editor.Map.SpatialReference);

                                                                                        sFilter.Geometry = Globals.Env2Polygon(searchEnvelope);

                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        sFilter.Geometry = inFeature.ShapeCopy;
                                                                                    }

                                                                                }
                                                                                else
                                                                                {
                                                                                    sFilter.Geometry = inFeature.ShapeCopy;
                                                                                }
                                                                                sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                if (sourceFeature != null)
                                                                                {
                                                                                    int fldIdx = inFeature.Fields.FindField(targetFieldName);
                                                                                    AAState.WriteLine("                  " + targetFieldName + " at index " + fldIdx);
                                                                                    string test = targetFieldName;
                                                                                    if (fldIdx > -1)
                                                                                    {
                                                                                        test = inFeature.get_Value(fldIdx).ToString();
                                                                                        AAState.WriteLine("                  Value Found " + test);
                                                                                    }
                                                                                    AAState.WriteLine("                  Value used " + test);
                                                                                    try
                                                                                    {

                                                                                        if (sourceFeature.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeString)
                                                                                        {
                                                                                            sourceFeature.set_Value(sourceField, test);
                                                                                            sourceFeature.Store();
                                                                                            found = true;
                                                                                            break;
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            if (Globals.IsNumeric(test))
                                                                                            {
                                                                                                if (sourceFeature.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSmallInteger ||
                                                                                                    sourceFeature.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeInteger)
                                                                                                {

                                                                                                    sourceFeature.set_Value(sourceField, Convert.ToInt32(test));
                                                                                                    sourceFeature.Store();
                                                                                                    found = true;
                                                                                                    break;
                                                                                                }
                                                                                                else if (sourceFeature.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeDouble ||
                                                                                                    sourceFeature.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSingle)
                                                                                                {
                                                                                                    sourceFeature.set_Value(sourceField, Convert.ToDouble(test));

                                                                                                    sourceFeature.Store(); found = true;
                                                                                                    break;
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    sourceFeature.set_Value(sourceField, test as object);
                                                                                                    sourceFeature.Store();
                                                                                                    found = true;
                                                                                                    break;
                                                                                                }
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                sourceFeature.set_Value(sourceField, test as object);
                                                                                                sourceFeature.Store();
                                                                                                found = true;
                                                                                                break;
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR setting value");
                                                                                    }
                                                                                    finally
                                                                                    {
                                                                                        if (found)
                                                                                        {
                                                                                            //   break;
                                                                                        }
                                                                                    }

                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Source Layer is not editable: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                }
                                                            }
                                                        }
                                                        //if ((!found) && (inObject.Fields.get_Field(fieldNum).IsNullable))
                                                        //{
                                                        //    inObject.set_Value(fieldNum, null);
                                                        //}
                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: UPDATE_INTERSECTING_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: UPDATE_INTERSECTING_FEATURE");
                                                    // fieldNum = -1;

                                                }
                                                break;

                                            }
                                        case "MULTI_FIELD_INTERSECT":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: MULTI_FIELD_INTERSECT");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    //LayerToIntersect|Field To Elevate
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int popFldIdx = 0;
                                                    if (args.GetLength(0) > 2)
                                                    {
                                                        AAState.WriteLine("                  Parsing Valueinfo");

                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString();
                                                        string[] fieldsToPop = args[2].ToString().Split(',');
                                                        if (args.GetLength(0) == 4)
                                                        {
                                                            AAState.WriteLine("                  Search distance specified");

                                                            if (Globals.IsDouble(args[3]))
                                                            {
                                                                searchDistance = Convert.ToDouble(args[3]);
                                                            }
                                                            else
                                                            {
                                                                searchDistance = 0.0;
                                                            }
                                                        }
                                                        else
                                                        {

                                                            searchDistance = 0.0;
                                                        }

                                                        if (sourceFieldName != null)
                                                        {
                                                            AAState.WriteLine("                  Looping Through Layers");

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                if (fieldsToPop.Length == popFldIdx)
                                                                    break;

                                                                sourceLayerName = sourceLayerNames[i].ToString();
                                                                if (sourceLayerName != "")
                                                                {
                                                                    // Get layer
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);
                                                                    if (sourceLayer != null)
                                                                    {
                                                                        if (sourceLayer.FeatureClass != null)
                                                                        {
                                                                            sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                            if (sourceField > -1)
                                                                            {
                                                                                sFilter = new SpatialFilterClass();
                                                                                if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                                                {

                                                                                    searchEnvelope = Globals.CalcSearchExtent(sourceLayer, inFeature, searchDistance);

                                                                                    sFilter.Geometry = searchEnvelope;

                                                                                }
                                                                                else
                                                                                {
                                                                                    sFilter.Geometry = inFeature.ShapeCopy;
                                                                                }
                                                                                sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                while (sourceFeature != null)
                                                                                {
                                                                                    if (fieldsToPop.Length == popFldIdx)
                                                                                        break;

                                                                                    string test = sourceFeature.get_Value(sourceField).ToString();

                                                                                    int tempFieldNum = inObject.Fields.FindField(fieldsToPop[popFldIdx]);
                                                                                    popFldIdx++;
                                                                                    if (tempFieldNum > -1)
                                                                                    {
                                                                                        inObject.set_Value(tempFieldNum, sourceFeature.get_Value(sourceField));
                                                                                    }
                                                                                    sourceFeature = fCursor.NextFeature();

                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Datasource is invalid: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer string is empty");

                                                                }
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field name is invalid");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Invalid Value method definition");

                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: MULTI_FIELD_INTERSECT: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: MULTI_FIELD_INTERSECT");
                                            }
                                            break;
                                        case "INTERSECT_STATS":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECT_STATS");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    //LayerToIntersect|Field To Elevate
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int AverageCount = 0;
                                                    if (args.GetLength(0) > 2)
                                                    {
                                                        AAState.WriteLine("                  Parsing Valueinfo");

                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString();
                                                        string statType = args[2].ToString();
                                                        if (args.GetLength(0) == 4)
                                                        {
                                                            AAState.WriteLine("                  Search distance specified");

                                                            if (Globals.IsDouble(args[3]))
                                                                searchDistance = Convert.ToDouble(args[3]);
                                                            else
                                                                searchDistance = 0.0;
                                                        }
                                                        else
                                                        {

                                                            searchDistance = 0.0;
                                                        }
                                                        double result = -999999.1;

                                                        if (sourceFieldName != null)
                                                        {
                                                            AAState.WriteLine("                  Looping Through Layers");

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {

                                                                sourceLayerName = sourceLayerNames[i].ToString();
                                                                if (sourceLayerName != "")
                                                                {
                                                                    // Get layer
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);
                                                                    if (sourceLayer != null)
                                                                    {
                                                                        if (sourceLayer.FeatureClass != null)
                                                                        {
                                                                            sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                            if (sourceField > -1)
                                                                            {
                                                                                sFilter = new SpatialFilterClass();
                                                                                if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                                                {

                                                                                    searchEnvelope = Globals.CalcSearchExtent(sourceLayer, inFeature, searchDistance);

                                                                                    sFilter.Geometry = searchEnvelope;

                                                                                }
                                                                                else
                                                                                {
                                                                                    sFilter.Geometry = inFeature.ShapeCopy;
                                                                                }
                                                                                sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                while (sourceFeature != null)
                                                                                {
                                                                                    string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                    if (Globals.IsNumeric(test))
                                                                                    {
                                                                                        double valToTest = Convert.ToDouble(test);
                                                                                        if (result == -999999.1)
                                                                                        {
                                                                                            result = valToTest;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            switch (statType.ToUpper())
                                                                                            {
                                                                                                case "MAX":
                                                                                                    if (result < valToTest)
                                                                                                    {
                                                                                                        result = valToTest;

                                                                                                    }
                                                                                                    break;
                                                                                                case "MIN":
                                                                                                    if (result > valToTest)
                                                                                                    {
                                                                                                        result = valToTest;

                                                                                                    }
                                                                                                    break;
                                                                                                case "SUM":
                                                                                                    result += valToTest;

                                                                                                    break;
                                                                                                case "AVERAGE":
                                                                                                    result += valToTest;
                                                                                                    AverageCount++;
                                                                                                    break;
                                                                                                case "MEAN":
                                                                                                    result += valToTest;
                                                                                                    AverageCount++;

                                                                                                    break;
                                                                                                default:
                                                                                                    AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                                    break;
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);
                                                                                    }
                                                                                    sourceFeature = fCursor.NextFeature();

                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Datasource is invalid: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer string is empty");

                                                                }
                                                            }

                                                            if (result != -999999.1)
                                                            {
                                                                if (AverageCount != 0)
                                                                {
                                                                    result = result / AverageCount;
                                                                }
                                                                inObject.set_Value(fieldNum, result);

                                                            }
                                                            else
                                                            {
                                                                IField field = inObject.Fields.get_Field(fieldNum);
                                                                object newval = field.DefaultValue;
                                                                if (newval == null)
                                                                {
                                                                    if (field.IsNullable)
                                                                    {
                                                                        inObject.set_Value(fieldNum, null);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(fieldNum, newval);
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field name is invalid");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Invalid Value method definition");

                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECT_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECT_STATS");
                                            }
                                            break;
                                        case "INTERSECTING_FEATURE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_FEATURE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) >= 2)
                                                    {
                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString();

                                                        if (sourceFieldName != null)
                                                        {
                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString();
                                                                if (sourceLayerName != "")
                                                                {
                                                                    // Get layer
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);
                                                                    if (sourceLayer != null)
                                                                    {
                                                                        sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                        if (sourceField > -1)
                                                                        {
                                                                            sFilter = new SpatialFilterClass();

                                                                            sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                            sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                            sFilter.set_OutputSpatialReference(sourceLayer.FeatureClass.ShapeFieldName, (sourceLayer.FeatureClass as IGeoDataset).SpatialReference);
                                                                            //sFilter.set_OutputSpatialReference(sourceLayer.FeatureClass.ShapeFieldName, AAState._editor.Map.SpatialReference);
                                                                            if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                                            {

                                                                                try
                                                                                {
                                                                                    IGeometry pSourceGeo = inFeature.ShapeCopy as IPoint;
                                                                                    pSourceGeo.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                    pSourceGeo.Project((sourceLayer.FeatureClass as IGeoDataset).SpatialReference);
                                                                                    //pSourceGeo.Project(AAState._editor.Map.SpatialReference);

                                                                                    bool hasXY;
                                                                                    hasXY = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference).HasXYPrecision();
                                                                                    //hasXY = (AAState._editor.Map.SpatialReference).HasXYPrecision();

                                                                                    double intTol = .001;
                                                                                    if (hasXY)
                                                                                    {
                                                                                        ISpatialReferenceResolution pSRResolution;

                                                                                        pSRResolution = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference) as ISpatialReferenceResolution;
                                                                                        //pSRResolution = (AAState._editor.Map.SpatialReference) as ISpatialReferenceResolution;
                                                                                        intTol = pSRResolution.get_XYResolution(false) * 2;
                                                                                    }

                                                                                    searchEnvelope = new EnvelopeClass();
                                                                                    searchEnvelope.XMin = 0 - intTol;
                                                                                    searchEnvelope.YMin = 0 - intTol;
                                                                                    searchEnvelope.XMax = 0 + intTol;
                                                                                    searchEnvelope.YMax = 0 + intTol;
                                                                                    searchEnvelope.CenterAt(pSourceGeo as IPoint);

                                                                                    searchEnvelope.SpatialReference = ((sourceLayer.FeatureClass as IGeoDataset).SpatialReference);
                                                                                    //searchEnvelope.SpatialReference = (AAState._editor.Map.SpatialReference);

                                                                                    //searchEnvelope.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                    //searchEnvelope.SnapToSpatialReference();
                                                                                    //if (AAState._editor.Map.SpatialReference != ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference)
                                                                                    //{

                                                                                    //  searchEnvelope.Project((sourceLayer.FeatureClass as IGeoDataset).SpatialReference);

                                                                                    //searchEnvelope.Project(AAState._editor.Map.SpatialReference);
                                                                                    //}

                                                                                    sFilter.Geometry = Globals.Env2Polygon(searchEnvelope);

                                                                                    //searchEnvelope.Expand(.1, .1, true);
                                                                                    //searchEnvelope.Expand(searchDistance, searchDistance, false);
                                                                                }
                                                                                catch
                                                                                {
                                                                                    IGeometry pGeo = inFeature.ShapeCopy;
                                                                                    pGeo.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                    pGeo.Project(AAState._editor.Map.SpatialReference);

                                                                                    sFilter.Geometry = pGeo;

                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                IGeometry pGeo = inFeature.ShapeCopy;
                                                                                pGeo.SpatialReference = ((inFeature.Class as IFeatureClass) as IGeoDataset).SpatialReference;
                                                                                pGeo.Project(AAState._editor.Map.SpatialReference);

                                                                                sFilter.Geometry = pGeo;

                                                                            }
                                                                            fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                            sourceFeature = fCursor.NextFeature();
                                                                            while (sourceFeature != null)
                                                                            {
                                                                                string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                inObject.set_Value(fieldNum, sourceFeature.get_Value(sourceField));
                                                                                found = true;
                                                                                sourceFeature = fCursor.NextFeature();

                                                                            }

                                                                            if (found == false  && AAState._CheckEnvelope)

                                                                            {
                                                                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects;
                                                                              //  sFilter.SpatialRelDescription = "T*T***T*T";
                                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                while (sourceFeature != null)
                                                                                {
                                                                                    string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                    inObject.set_Value(fieldNum, sourceFeature.get_Value(sourceField));
                                                                                    found = true;
                                                                                    sourceFeature = fCursor.NextFeature();

                                                                                }

                                                                            }
                                                                            if (found)
                                                                            {
                                                                                break;
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                            }
                                                            if (!found)
                                                            {
                                                                IField field = inObject.Fields.get_Field(fieldNum);
                                                                object newval = field.DefaultValue;
                                                                if (newval == null)
                                                                {
                                                                    if (field.IsNullable)
                                                                    {
                                                                        inObject.set_Value(fieldNum, null);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(fieldNum, newval);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_FEATURE");
                                            }
                                            break;
                                        case "INTERSECTING_RASTER":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_RASTER");
                                                if (inFeature != null & valData != null)
                                                {

                                                    sourceLayerName = "";
                                                    formatString = "";
                                                    found = false;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.Length < 1) break;
                                                    switch (args.Length)
                                                    {
                                                        case 1:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            break;
                                                        case 2:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            formatString = args[1].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    // Get layer
                                                    for (int i = 0; i < sourceLayerNames.Length; i++)
                                                    {
                                                        sourceLayerName = sourceLayerNames[i].ToString();
                                                        IPoint pLoc = Globals.GetGeomCenter(inFeature);

                                                        if (pLoc != null)
                                                        {
                                                            string cellVal = GetCellValue(sourceLayerName, pLoc, AAState._editor.Map);// Globals.GetCellValue(sourceLayerName, pLoc, _editor.Map);
                                                            AAState.WriteLine("                  ERROR/WARING: No cell value or raster was found: " + sourceLayerName);
                                                            if (cellVal != null && cellVal != "" && cellVal != "No Raster")
                                                            {

                                                                if (formatString == null || formatString == "" || (inObject.Fields.get_Field(fieldNum).Type != esriFieldType.esriFieldTypeString))
                                                                {
                                                                    inObject.set_Value(fieldNum, cellVal);
                                                                    found = true;
                                                                    break;
                                                                }
                                                                else
                                                                {
                                                                    // formatString = formatString.Replace("[value]",cellVal);
                                                                    formatString = formatString + cellVal;
                                                                    inObject.set_Value(fieldNum, formatString);

                                                                    found = true;
                                                                    break;
                                                                }

                                                            }

                                                        }
                                                    }
                                                    if (!(found) && inObject.Fields.get_Field(fieldNum).IsNullable)
                                                        inObject.set_Value(fieldNum, null);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_RASTER: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_RASTER");
                                            }
                                            break;
                                        case "INTERSECTING_LAYER_DETAILS":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_LAYER_DETAILS");
                                                if (inFeature != null & valData != null)
                                                {

                                                    sourceLayerName = "";
                                                    formatString = "";
                                                    found = false;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.Length < 1) break;
                                                    switch (args.Length)
                                                    {
                                                        case 1:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            formatString = "P";
                                                            break;
                                                        case 2:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            formatString = args[1].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    // Get layer
                                                    for (int i = 0; i < sourceLayerNames.Length; i++)
                                                    {
                                                        sourceLayerName = sourceLayerNames[i].ToString();
                                                        //AAState.WriteLine("                  Getting Features Centeroid");

                                                        //IPoint pLoc = Globals.GetGeomCenter(inFeature);
                                                        IGeometry pGeo = inFeature.ShapeCopy;

                                                        if (pGeo != null)
                                                        {
                                                            // AAState.WriteLine("                  Centroid Found");
                                                            AAState.WriteLine("                  Getting list of " + sourceLayerName + " Layers");
                                                            IEnumLayer pEnum = Globals.GetLayers(AAState._editor.Map, sourceLayerName);

                                                            if (pEnum != null)
                                                            {
                                                                AAState.WriteLine("                  List retrieved of " + sourceLayerName + " Layers");
                                                                AAState.WriteLine("                  Starting Loop");
                                                                ILayer pLay = pEnum.Next();
                                                                ISpatialFilter pSpatFilt;
                                                                while (pLay != null)
                                                                {

                                                                    if (found)
                                                                    {
                                                                        AAState.WriteLine("                  Exiting Layer Loop");
                                                                        break;
                                                                    }
                                                                    AAState.WriteLine("                  Checking " + pLay.Name);

                                                                    if (pLay is IRasterLayer)
                                                                    {

                                                                        IRasterLayer pRasLay = pLay as IRasterLayer;
                                                                        AAState.WriteLine("                  Trying " + pRasLay.Name);
                                                                        IEnvelope pEnv = pRasLay.AreaOfInterest;
                                                                        // ITopologicalOperator pTopo = pEnv as ITopologicalOperator;
                                                                        IRelationalOperator pRel = pEnv as IRelationalOperator;
                                                                        IRelationalOperator2 pRel2 = pEnv as IRelationalOperator2;

                                                                        if (pRel.Crosses(pGeo) || pRel.Touches(pGeo) || pRel.Overlaps(pGeo) || pRel2.ContainsEx(pGeo, esriSpatialRelationExEnum.esriSpatialRelationExClementini))
                                                                        {
                                                                            AAState.WriteLine("                  Geometry does intersect " + pRasLay.Name);
                                                                            switch (formatString)
                                                                            {
                                                                                case "P":
                                                                                    // IDataset pDS = pFLay.FeatureClass as IDataset;

                                                                                    inObject.set_Value(fieldNum, Globals.GetPathForALayer(pLay));
                                                                                    pRasLay = null;
                                                                                    pEnv = null;

                                                                                    pRel = null;
                                                                                    pRel2 = null;
                                                                                    found = true;
                                                                                    break;
                                                                                case "N":
                                                                                    inObject.set_Value(fieldNum, pLay.Name);
                                                                                    pRasLay = null;
                                                                                    pEnv = null;

                                                                                    pRel = null;
                                                                                    pRel2 = null;
                                                                                    found = true;
                                                                                    break;
                                                                                default:
                                                                                    inObject.set_Value(fieldNum, Globals.GetPathForALayer(pLay));
                                                                                    pRasLay = null;
                                                                                    pEnv = null;

                                                                                    pRel = null;
                                                                                    pRel2 = null;
                                                                                    found = true;
                                                                                    break;
                                                                            }
                                                                        }
                                                                    }
                                                                    else if (pLay is IFeatureLayer)
                                                                    {
                                                                        IFeatureLayer pFLay = pLay as IFeatureLayer;
                                                                        if (pFLay.FeatureClass == inObject.Class)
                                                                        {
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Trying " + pFLay.Name);
                                                                            pSpatFilt = new SpatialFilterClass();
                                                                            pSpatFilt.GeometryField = pFLay.FeatureClass.ShapeFieldName;
                                                                            pSpatFilt.Geometry = pGeo as IGeometry;
                                                                            pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                                                            if (pFLay.FeatureClass.FeatureCount(pSpatFilt) > 0)
                                                                            {
                                                                                AAState.WriteLine("                  Geometry does intersect " + pFLay.Name);
                                                                                switch (formatString)
                                                                                {
                                                                                    case "P":
                                                                                        // IDataset pDS = pFLay.FeatureClass as IDataset;
                                                                                        // AAState.WriteLine("                  Exiting Layer Loop");
                                                                                        inObject.set_Value(fieldNum, Globals.GetPathForALayer(pLay));
                                                                                        pFLay = null;
                                                                                        found = true;
                                                                                        break;
                                                                                    case "N":
                                                                                        inObject.set_Value(fieldNum, pLay.Name);
                                                                                        pFLay = null;
                                                                                        found = true;
                                                                                        break;
                                                                                    default:
                                                                                        inObject.set_Value(fieldNum, Globals.GetPathForALayer(pLay));
                                                                                        pFLay = null;
                                                                                        found = true;
                                                                                        //inObject.set_Value(fieldNum, null);
                                                                                        break;
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Does not intersect " + pFLay.Name);
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Warning: Unsupported type");
                                                                    }
                                                                    pLay = pEnum.Next();
                                                                }
                                                                pEnum = null;

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: not matching layer types found");
                                                            }

                                                        }
                                                        else
                                                            AAState.WriteLine("                  ERROR: Geo not Found");
                                                    }
                                                    //if (!(found) && inObject.Fields.get_Field(fieldNum).IsNullable)
                                                    //    inObject.set_Value(fieldNum, null);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_LAYER_DETAILS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_LAYER_DETAILS");
                                            }
                                            break;
                                        case "INTERSECTING_FEATURE_DISTANCE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_FEATURE_DISTANCE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) >= 2)
                                                    {
                                                        //    sourceLayerName = args[0].ToString();
                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString();
                                                    }
                                                    // Get layer

                                                    if (sourceFieldName != null)
                                                    {
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString();
                                                            if (sourceLayerName != "")

                                                                sourceLayerName = args[i].ToString();
                                                            if (i == 0)
                                                                i++;

                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName);
                                                            if (sourceLayer == null)
                                                            {
                                                                AAState.WriteLine("                  ERROR/WARNING: " + sourceLayer + " was not found");
                                                                continue;
                                                            }

                                                            IFeatureClass iFC = inFeature.Class as IFeatureClass;
                                                            if (sourceLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                                                            {
                                                                AAState.WriteLine("                  ERROR: " + sourceLayer + " is a polygon layer");

                                                                break;
                                                            }
                                                            //if (sourceLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline || iFC.ShapeType != esriGeometryType.esriGeometryPoint)
                                                            //    break;
                                                            //FindLayerByName(sourceLayerName, out sourceLayer);
                                                            if (sourceLayer != null)
                                                            {
                                                                sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                if (sourceField > -1)
                                                                {
                                                                    sFilter = new SpatialFilterClass();
                                                                    sFilter.Geometry = inFeature.ShapeCopy;
                                                                    sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                    sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                    fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                    sourceFeature = fCursor.NextFeature();
                                                                    if (sourceFeature != null)
                                                                    {

                                                                        IPoint pIntPnt;
                                                                        if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                                        {
                                                                            pIntPnt = Globals.GetIntersection(inFeature.ShapeCopy, sourceFeature.ShapeCopy as IPolyline) as IPoint;

                                                                        }
                                                                        else
                                                                            pIntPnt = inFeature.ShapeCopy as IPoint;

                                                                        double dAlong = Globals.PointDistanceOnLine(pIntPnt, sourceFeature.Shape as IPolyline, 2);
                                                                        string strUnit = Globals.GetSpatRefUnitName(Globals.GetLayersCoordinateSystem(sourceLayer.FeatureClass), true);
                                                                        if (strUnit == "Foot" && dAlong != 1)
                                                                        {
                                                                            strUnit = "Feet";
                                                                        }
                                                                        else if (strUnit == "Meter" && dAlong != 1)
                                                                        {
                                                                            strUnit = "Meters";
                                                                        }
                                                                        string strDis = dAlong + " " + strUnit + " along " + sourceLayer.Name + " with " + sourceLayer.FeatureClass.Fields.get_Field(sourceField).AliasName + " of " + sourceFeature.get_Value(sourceField);

                                                                        if (inObject.Fields.get_Field(fieldNum).Length < strDis.Length - 1)
                                                                        {

                                                                            strDis = dAlong + " " + strUnit + ": " + sourceFeature.get_Value(sourceField);
                                                                            AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);

                                                                            if (inObject.Fields.get_Field(fieldNum).Length < strDis.Length - 1)
                                                                            {

                                                                                if (inObject.Fields.get_Field(fieldNum).Length < strDis.Length - 1)
                                                                                {
                                                                                    strDis = dAlong.ToString();
                                                                                    inObject.set_Value(fieldNum, strDis);
                                                                                    break;
                                                                                }
                                                                                else
                                                                                {
                                                                                    inObject.set_Value(fieldNum, strDis);
                                                                                    break;
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                strDis = dAlong.ToString();
                                                                                AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);
                                                                                if (inObject.Fields.get_Field(fieldNum).Length < strDis.Length - 1)
                                                                                {
                                                                                    strDis = dAlong.ToString();
                                                                                    inObject.set_Value(fieldNum, strDis);
                                                                                    break;
                                                                                }
                                                                                else
                                                                                {
                                                                                    inObject.set_Value(fieldNum, strDis);
                                                                                    break;
                                                                                }
                                                                            }

                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Value set to: " + strDis);
                                                                            inObject.set_Value(fieldNum, strDis);
                                                                            break;
                                                                        }
                                                                    }

                                                                    else if (inObject.Fields.get_Field(fieldNum).IsNullable)
                                                                        inObject.set_Value(fieldNum, null);
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayer + ": field: " + sourceFieldName + " was not found");
                                                                }
                                                            }
                                                            else { }
                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE_DISTANCE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_FEATURE_DISTANCE");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: NEARSET_FEATURE - similiar to INTERSECTING_FEATURE but requires a search distance.

                                        case "NEAREST_FEATURE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: NEAREST_FEATURE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    searchDistance = 0;
                                                    found = false;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) > 1)
                                                    {
                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString();
                                                    }

                                                    if (args.GetLength(0) > 2)
                                                        Double.TryParse(args[2], out searchDistance);

                                                    if (sourceLayerNames.Length > 0 & sourceFieldName != null)
                                                    {
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString();
                                                            if (sourceLayerName != "")
                                                            {
                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName) as IFeatureLayer;
                                                                if (sourceLayer != null)
                                                                {
                                                                    sourceField = sourceLayer.FeatureClass.FindField(sourceFieldName);

                                                                    if (sourceField > -1)
                                                                    {
                                                                        sFilter = new SpatialFilterClass();
                                                                        if (searchDistance > 0)
                                                                        {
                                                                            searchEnvelope = inFeature.ShapeCopy.Envelope;
                                                                            searchEnvelope.Expand(searchDistance, searchDistance, false);
                                                                            sFilter.Geometry = searchEnvelope;
                                                                        }
                                                                        else
                                                                            sFilter.Geometry = inFeature.ShapeCopy;

                                                                        sFilter.GeometryField = sourceLayer.FeatureClass.ShapeFieldName;
                                                                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                                                        fCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                        sourceFeature = fCursor.NextFeature();
                                                                        nearestFeature = null;

                                                                        proxOp = (IProximityOperator)inFeature.Shape;
                                                                        lastDistance = searchDistance;
                                                                        while (!(sourceFeature == null))
                                                                        {
                                                                            distance = proxOp.ReturnDistance(sourceFeature.Shape);
                                                                            if (distance <= lastDistance)
                                                                            {
                                                                                nearestFeature = sourceFeature;
                                                                                lastDistance = distance;
                                                                            }
                                                                            sourceFeature = fCursor.NextFeature();
                                                                        }

                                                                        if (nearestFeature != null)
                                                                        {
                                                                            inObject.set_Value(fieldNum, nearestFeature.get_Value(sourceField));
                                                                            found = true;
                                                                            break;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: " + sourceLayer + ": field: " + sourceFieldName + " was not found");
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayer + " was not found");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Empty source layer name");
                                                            }

                                                        }
                                                        if (!found)
                                                        {
                                                            IField field = inObject.Fields.get_Field(fieldNum);
                                                            object newval = field.DefaultValue;
                                                            if (newval == null)
                                                            {
                                                                if (field.IsNullable)
                                                                {
                                                                    inObject.set_Value(fieldNum, null);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                inObject.set_Value(fieldNum, newval);
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: NEAREST_FEATURE: " + ex.Message);

                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: NEAREST_FEATURE");
                                            }
                                            break;

                                        default:
                                            //    MessageBox.Show(valMethod + " for layer " + tableName + " is not a valid method, check the dynamic value table", "Attribute Assistant");
                                            AAState.WriteLine("ERROR: " + valMethod + " for layer " + tableName + " is not a valid method, check the dynamic value table");

                                            break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("TableName:" + tableName + "  FieldName:" + fieldName + System.Environment.NewLine + "ValueMethod:" + valMethod + "  ValueData:" + valData + System.Environment.NewLine + "Message: " + ex.Message, "Attribute Assistant Message");
                                    AAState.WriteLine("ERROR: TableName:" + tableName + "  FieldName:" + fieldName + System.Environment.NewLine + "ValueMethod:" + valMethod + "  ValueData:" + valData + System.Environment.NewLine + "Message: " + ex.Message);
                                }

                            }

                            // if (mode == "ON_CREATE")
                            //{
                            if (inObject != null)
                            {

                                inChanges = inObject as IRowChanges;
                                if (fieldNum < inObject.Fields.FieldCount)
                                {
                                    changed = inChanges.get_ValueChanged(fieldNum);
                                    if (changed)
                                        //  if (fieldName.ToUpper() != "SHAPE")
                                        try
                                        {
                                            // AAState.WriteLine("                      Setting Last Value");
                                            if (AAState.lastValueProperties.GetProperty(fieldName) != null)
                                            {
                                                AAState.WriteLine("                      Setting Last Value");
                                                AAState.WriteLine("                           " + fieldName + ": " + inObject.get_Value(fieldNum).ToString());
                                                AAState.lastValueProperties.SetProperty(fieldName, inObject.get_Value(fieldNum));
                                            }

                                            else
                                            {
                                                AAState.WriteLine("                      Setting Last Value");
                                                AAState.WriteLine("                           " + fieldName + ": " + inObject.get_Value(fieldNum).ToString());

                                                AAState.lastValueProperties.SetProperty(fieldName, inObject.get_Value(fieldNum));
                                            }

                                        }
                                        catch
                                        {
                                            //AAState.WriteLine("        Error Setting Last Value " + inObject.Fields.get_Field(fieldNum).Name);

                                        }
                                    //}
                                }
                            }

                        }

                     }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem in setup." + System.Environment.NewLine + "Message:" + ex.Message, "Attribute Assistant Message");
                AAState.WriteLine("Error in setup");
            }
            finally
            {
                if (AAState._tab == inObject.Class)
                {
                    AAState.reInitExt();

                }
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }
                AAState.WriteLine("DONE");
                AAState.WriteLine("---------------------------------------");
                if (fCursor != null)
                {
                    Marshal.ReleaseComObject(fCursor);
                    GC.Collect(300);
                    GC.WaitForFullGCComplete();
                }
            }
        }
        public static void SetMeasures(IApplication app)
        {
            IEditor editor = null;
            ICursor pCursor = null;
            IFeatureCursor pFCursor = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            IMap map = null;
            IMxDocument mxdoc = null;
            ILayer layer = null;
            IFeatureLayer fLayer = null;
            IFeatureClass fc = null;
            IFeatureSelection fSel = null;
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;

            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;

            IFeature pFeature = null;
            IMSegmentation pMSeg = null;
            ICurve pCurve = null;
            try
            {
                editor = Globals.getEditor(app);
                if (editor == null)
                {
                    return;
                }

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_1"));
                    return;
                }
                mxdoc = app.Document as IMxDocument;
                layer = mxdoc.SelectedLayer as ILayer;
                // Verify that there are layers in the table on contents
                map = mxdoc.FocusMap;
                if (map.LayerCount < 1)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_1"));
                    return;
                }

                if (layer == null)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("TOC_6") + Environment.NewLine +
                                     A4LGSharedFunctions.Localizer.GetString("Measure_1"));
                    return;
                }

                //Verify that it is a feature layer
                fLayer = layer as IFeatureLayer;
                if (fLayer == null)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("TOC_1"));
                    return;
                }

                //Get the Feature layer and feature class
                fc = fLayer.FeatureClass;
                if (fc == null)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_2"));
                    return;

                }
                if (fc.Fields.get_Field(fc.Fields.FindField(fc.ShapeFieldName)).GeometryDef.HasM == false)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_3"));
                    return;

                }
                fSel = fLayer as IFeatureSelection;

                //Verify that it is a line layer
                if (fc.ShapeType != esriGeometryType.esriGeometryPolyline)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("TOC_2"));
                    return;
                }
                //Verify Layer Selection
                if (fSel.SelectionSet.Count == 0)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_4"));
                    return;
                }

                bool WithDig = true;
                if (MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsAsk_1"), A4LGSharedFunctions.Localizer.GetString("CalibrateLn"), MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    WithDig = false;
                }

                //Start edit operation (for undo)
                editor.StartOperation();
                //ProgressBar
                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                // Create a CancelTracker
                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = app.hWnd;
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                stepProgressor.MinRange = 0;
                stepProgressor.MaxRange = fSel.SelectionSet.Count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_1") + A4LGSharedFunctions.Localizer.GetString("ForLn") + 1 + A4LGSharedFunctions.Localizer.GetString("Of") + fSel.SelectionSet.Count.ToString() + ".";

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

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_1");
                progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_1") + A4LGSharedFunctions.Localizer.GetString("ForSltedLn");
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
                //Step through each selected line in the highlighted layer
                fSel.SelectionSet.Search(null, false, out pCursor);
                pFCursor = (IFeatureCursor)pCursor;

                pFeature = pFCursor.NextFeature();
                int intCount = 1;
                //'Loop through each selected feature in the highlighted layer

                while ((pFeature != null))
                {

                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_1") + A4LGSharedFunctions.Localizer.GetString("ForLn") + intCount + A4LGSharedFunctions.Localizer.GetString("Of") + fSel.SelectionSet.Count.ToString() + ".";
                    if (pFeature.Shape is IMSegmentation)
                    {
                        try
                        {
                            if (pFeature.Shape != null)
                            {
                                pMSeg = (IMSegmentation)pFeature.ShapeCopy;
                                pCurve = (ICurve)pFeature.ShapeCopy;
                                if (WithDig)
                                {
                                    pMSeg.SetAndInterpolateMsBetween(0, pCurve.Length);
                                }
                                else
                                    pMSeg.SetAndInterpolateMsBetween(pCurve.Length, 0);

                                pFeature.Shape = (IGeometry)pMSeg;
                                pFeature.Store();
                            }
                            else
                            {
                                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("OID") + pFeature.OID + A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_5"));
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_1") + "\n" + ex.Message + A4LGSharedFunctions.Localizer.GetString("OID") + pFeature.OID);
                        }
                    }

                    Marshal.ReleaseComObject(pFeature);
                    intCount++;
                    pFeature = pFCursor.NextFeature();
                    stepProgressor.Step();

                }

                editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_2"));
            }
            catch (Exception ex)
            {
                editor.AbortOperation();
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_1") + "\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }
                if (pCursor != null)
                    Marshal.ReleaseComObject(pCursor);
                if (pFCursor != null)
                    Marshal.ReleaseComObject(pFCursor);

                editor = null;
                pCursor = null;
                pFCursor = null;
                stepProgressor = null;
                progressDialog = null;
                map = null;
                mxdoc = null;
                layer = null;
                fLayer = null;
                fc = null;
                fSel = null;
                progressDialogFactory = null;
                trackCancel = null;

                pFeature = null;
                pMSeg = null;
                pCurve = null;
            }
        }
        public bool SetDynamicValues(IObject inObject, string mode, out List<IObject> ChangeFeatureList, out List<IObject> NewFeatureList, out List<IObject> ChangeFeatureGeoList)
        {
            NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
            nfi.NumberGroupSeparator = "";

            ChangeFeatureList = null;
            NewFeatureList = null;
            ChangeFeatureGeoList = null;

            IMSegmentation mseg = null;
            INetworkFeature netFeat = null;

            IJunctionFeature iJuncFeat = null;
            IEdgeFeature iEdgeFeat = null;
            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
            trackCancel.CancelOnKeyPress = true;
            // trackCancel.CancelOnClick = true;

            try
            {
                AAState.WriteLine("Starting AA");
                if (AAState.PerformUpdates == false)
                {
                    AAState.WriteLine("Perform Updates is false");

                }
                if (AAState.PerformUpdates && AAState._dv == null)
                {

                    AAState.WriteLine("Dynamic Value Table is missing - Name in Config:" + AAState._defaultsTableName);

                    AAState.PerformUpdates = false;
                    return false;
                }

                if (AAState.PerformUpdates && AAState._dv != null)
                {
                    if (AAState._dv.Table == null)
                    {

                        AAState.WriteLine("the dv.table is null");

                        return false;
                    }

                    if (inObject == null)
                    {
                        AAState.WriteLine("Input object is null");

                        return false;
                    }
                    if (inObject.Table == AAState._tab)
                    {

                        if (inObject.get_Value(inObject.Fields.FindField("VALUEMETHOD")).ToString().ToUpper() == "LAST_VALUE")
                        {
                            if (inObject.get_Value(inObject.Fields.FindField("FIELDNAME")) != null)
                            {
                                if (inObject.get_Value(inObject.Fields.FindField("FIELDNAME")) != DBNull.Value)
                                {
                                    try
                                    {
                                        LastValueEntry lstVal = AAState.lastValueProperties.GetProperty(inObject.get_Value(inObject.Fields.FindField("FIELDNAME")).ToString()) as LastValueEntry;
                                        if (lstVal != null)
                                        {
                                            lstVal.On_Manual = Globals.toBoolean(inObject.get_Value(inObject.Fields.FindField("ON_MANUAL")).ToString());
                                            lstVal.On_Create = Globals.toBoolean(inObject.get_Value(inObject.Fields.FindField("ON_CREATE")).ToString());
                                            lstVal.On_ChangeAtt = Globals.toBoolean(inObject.get_Value(inObject.Fields.FindField("ON_CHANGE")).ToString());

                                            if (inObject.Fields.FindField("ON_CHANGEGEO") >= 0)
                                            {
                                                lstVal.On_ChangeGeo = Globals.toBoolean(inObject.get_Value(inObject.Fields.FindField("ON_CHANGEGEO")).ToString());
                                            }
                                        }
                                        AAState.WriteLine("Last Value rule was modified, updating Last Value Array");
                                    }
                                    catch
                                    {
                                        //property does not exist

                                    }
                                }
                            }

                        }
                        else
                        {
                            AAState.WriteLine("Dynamic Value Table is the table that is edited, skipping");
                        }
                        return false;
                    }

                    string modeVal;

                    if (AAState._dv.Table.Columns[mode] == null)
                    {
                        AAState.WriteLine(mode + " column is missing");
                        mode = mode.Replace("GEO", "");

                    }
                    if (AAState._dv.Table.Columns[mode].DataType == System.Type.GetType("System.String"))
                    {
                        modeVal = "(" + mode + " = '1' or " + mode + " = 'Yes' or " + mode + " = 'YES' or " + mode + " = 'True' or " + mode + " = 'TRUE')";

                    }
                    else
                    {
                        modeVal = mode + " = 1";
                    }
                    System.Int32 int32_hWnd = ArcMap.Application.hWnd;

                    progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);

                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = inObject.Fields.FieldCount;
                    stepProgressor.StepValue = 1;
                    stepProgressor.Message = "Attribute Assistant Progress";
                    // Create the ProgressDialog. This automatically displays the dialog
                    progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                    // Set the properties of the ProgressDialog
                    progressDialog.CancelEnabled = true;
                    progressDialog.Description = "Checking rules for " + inObject.Class.AliasName;
                    progressDialog.Title = "Attribute Assistant Progress";
                    progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                    progressDialog.ShowDialog();

                    //Optional skip junctions feature class
                    //if (Globals.isOrpanJunction(inFeature))
                    //    return false;

                    //Get table name for this feature
                    _currentDataset = inObject.Class as IDataset;
                    _currentDatasetNameItems = _currentDataset.Name.Split('.');
                    tableName = _currentDatasetNameItems[_currentDatasetNameItems.GetLength(0) - 1];

                    stepProgressor.Message = "Checking rules for edited feature: " + inObject.Class.AliasName;
                    progressDialog.Description = "Checking rules for edited feature: " + inObject.Class.AliasName;
                    AAState.WriteLine("***********************************************************");
                    AAState.WriteLine("############ " + DateTime.Now + " ################");

                    AAState.WriteLine("");
                    AAState.WriteLine("  Setting sort order: Field - RUNORDER");

                    if (AAState._dv.Table.Columns.Contains("RUN_WEIGHT"))
                        AAState._dv.Sort = "RUN_WEIGHT DESC";

                    AAState.WriteLine("  Querying table for Last Value for layer: " + inObject.Class.AliasName);
                    AAState.WriteLine("  Query Used: (TABLENAME = '*' OR TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') AND VALUEMETHOD = 'Last_Value'");
                    AAState._dv.RowFilter = "(TABLENAME = '*' OR TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') AND VALUEMETHOD = 'Last_Value'";
                    AAState.WriteLine("  Number of results: " + AAState._dv.Count.ToString());

                    if (AAState._dv.Count > 0)
                    {
                        IRowChanges pRowChLast = inObject as IRowChanges;
                        for (int retRows = 0; retRows < AAState._dv.Count; retRows++)
                        {
                            DataRowView drv = AAState._dv[retRows];
                            AAState.WriteLine("       Looking for " + drv["FIELDNAME"].ToString());

                            int fldLoc = inObject.Fields.FindField(drv["FIELDNAME"].ToString());

                            if (fldLoc > 0)
                            {
                                AAState.WriteLine("       " + drv["FIELDNAME"].ToString() + " field found at position: " + fldLoc);

                                if (pRowChLast.get_ValueChanged(fldLoc))
                                {
                                    AAState.WriteLine("       " + drv["FIELDNAME"].ToString() + " Has Changed");

                                    try
                                    {
                                        LastValueEntry lstVal = (AAState.lastValueProperties.GetProperty(drv["FIELDNAME"].ToString()) as LastValueEntry);

                                        if (lstVal != null)
                                        {

                                            if (inObject.get_Value(fldLoc) != null)
                                            {
                                                if (inObject.get_Value(fldLoc) != DBNull.Value)
                                                {

                                                    if (lstVal.Value != null)
                                                    {
                                                        AAState.WriteLine("                      Setting Last Value");
                                                        AAState.WriteLine("                           " + drv["FIELDNAME"].ToString() + ": " + inObject.get_Value(fldLoc).ToString());
                                                        lstVal.Value = inObject.get_Value(fldLoc);

                                                        AAState.lastValueProperties.SetProperty(drv["FIELDNAME"].ToString(), lstVal);
                                                    }

                                                    else
                                                    {
                                                        AAState.WriteLine("                      Setting Last Value");
                                                        AAState.WriteLine("                           " + drv["FIELDNAME"].ToString() + ": " + inObject.get_Value(fldLoc));
                                                        lstVal.Value = inObject.get_Value(fldLoc);

                                                        AAState.lastValueProperties.SetProperty(drv["FIELDNAME"].ToString(), lstVal);
                                                    }

                                                }
                                                else
                                                {
                                                    if (mode == "ON_CREATE")
                                                    {
                                                        AAState.WriteLine("                      Skipping null on create");

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                      Setting Last Value");
                                                        AAState.WriteLine("                           " + drv["FIELDNAME"].ToString() + ": NULL");
                                                        lstVal.Value = null;
                                                        AAState.lastValueProperties.SetProperty(drv["FIELDNAME"].ToString(), lstVal);
                                                    }

                                                }
                                            }
                                            else
                                            {
                                                if (mode == "ON_CREATE")
                                                {
                                                    AAState.WriteLine("                      Skipping null on create");

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                      Setting Last Value");
                                                    AAState.WriteLine("                           " + drv["FIELDNAME"].ToString() + ": NULL");
                                                    lstVal.Value = null;
                                                    AAState.lastValueProperties.SetProperty(drv["FIELDNAME"].ToString(), lstVal);

                                                }
                                            }

                                        }
                                        else
                                        {
                                            lstVal = new LastValueEntry();
                                            lstVal.Value = inObject.get_Value(fldLoc);

                                            lstVal.On_Manual = Globals.toBoolean(drv["ON_MANUAL"].ToString());
                                            lstVal.On_Create = Globals.toBoolean(drv["ON_CREATE"].ToString());
                                            lstVal.On_ChangeAtt = Globals.toBoolean(drv["ON_CHANGE"].ToString());
                                            if (drv["ON_CHANGEGEO"] != null)
                                            {
                                                lstVal.On_ChangeGeo = Globals.toBoolean(drv["ON_CHANGEGEO"].ToString());
                                            }
                                            AAState.lastValueProperties.SetProperty(drv["FIELDNAME"].ToString(), lstVal);

                                        }

                                    }
                                    catch
                                    {

                                    }

                                }
                                else
                                {
                                    AAState.WriteLine("       " + drv["FIELDNAME"].ToString() + " Has not changed");

                                }
                            }
                        }

                        pRowChLast = null;

                    }

                    AAState.WriteLine("  Querying table for rules for layer: " + inObject.Class.AliasName);
                    AAState.WriteLine("  Query Used: (TABLENAME = '*' OR TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') AND " + modeVal);
                    AAState._dv.RowFilter = "(TABLENAME = '*' OR TABLENAME = '" + tableName + "' OR TABLENAME like '" + tableName + "|*' OR TABLENAME like '" + tableName + "|%') AND " + modeVal;
                    AAState.WriteLine("  Number of results: " + AAState._dv.Count.ToString());
                    if (AAState._processCount > 2)
                    {
                        System.Threading.Thread.Sleep(400);
                    }
                    if (AAState._processCount > 15)
                    {
                        MessageBox.Show("You have more than 15 processes running, more than likely your rules are causing an infinite loop.  Any rule that creates a new feature with * as the table name can cause this issue.");

                        return false;

                    }
                    if (AAState._dv.Count > 0)
                    {
                        bool proc = false;
                        AAState.WriteLine("  Looping through the rows");

                        for (int retRows = 0; retRows < AAState._dv.Count; retRows++)
                        {
                            DataRowView drv = AAState._dv[retRows];

                            AAState.WriteLine("    ------------------------------------------------");
                            AAState.WriteLine("      Row Info");
                            AAState.WriteLine("        Row Number " + (retRows + 1).ToString());
                            AAState.WriteLine("        TableName: " + drv["TABLENAME"].ToString());
                            AAState.WriteLine("        FieldName: " + drv["FIELDNAME"].ToString());
                            AAState.WriteLine("        ValueInfo: " + drv["VALUEINFO"].ToString());
                            AAState.WriteLine("        ValueMethod: " + drv["VALUEMETHOD"].ToString());
                            AAState.WriteLine("        On Create: " + drv["ON_CREATE"].ToString());
                            AAState.WriteLine("        On Change: " + drv["ON_CHANGE"].ToString());
                            if (AAState._dv.Table.Columns.Contains("RUNORDER"))
                                AAState.WriteLine("        Order: " + drv["RUNORDER"].ToString());

                            AAState.WriteLine("");

                            AAState.WriteLine("      Checking for Subtype Restriction");
                            valFC = drv["TABLENAME"].ToString().Trim();
                            if (valFC.Contains("|"))
                            {
                                AAState.WriteLine("        Subtype restriction Found");
                                string[] spliVal = valFC.Split('|');
                                List<string> validSubtypes = new List<string>(spliVal[1].Split(','));
                                List<string> inValidSubtypes;
                                if (spliVal.GetLength(0) == 3)
                                {
                                    inValidSubtypes = new List<string>(spliVal[2].Split(','));
                                }
                                else
                                {
                                    inValidSubtypes = new List<string>();
                                }

                                int obSubVal;
                                ISubtypes pSub = inObject.Class as ISubtypes;
                                if (pSub != null)
                                {
                                    if (pSub.HasSubtype)
                                    {
                                        if (inObject.get_Value(pSub.SubtypeFieldIndex).ToString() != "")
                                        {
                                            obSubVal = Convert.ToInt32(inObject.get_Value(pSub.SubtypeFieldIndex).ToString());
                                            if (validSubtypes.Contains("*"))
                                            {
                                                if (inValidSubtypes.Contains(obSubVal.ToString()))
                                                {
                                                    AAState.WriteLine("        Skipping, not the subtype defined");
                                                    proc = false;
                                                    continue;
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("        Subtype is valid");
                                                }
                                            }

                                            else if (validSubtypes.Contains(obSubVal.ToString()))
                                            {
                                                AAState.WriteLine("        Subtype is valid");
                                            }
                                            else
                                            {
                                                AAState.WriteLine("        Skipping, not the subtype defined");
                                                proc = false;
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            AAState.WriteLine("        Skipping, subtype is not set");
                                            proc = false;
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        AAState.WriteLine("        ERROR: Layer does not have subtypes");
                                    }
                                }
                                else
                                {
                                    AAState.WriteLine("        ERROR: Layer does not have subtypes");
                                }

                            }
                            valMethod = drv["VALUEMETHOD"].ToString().ToUpper().Trim();
                            valData = drv["VALUEINFO"].ToString().Trim();
                            if (valData.Contains(Environment.NewLine))
                            {
                                valData = valData.Substring(0, valData.IndexOf(Environment.NewLine));

                            }
                            List<string> strFldNames = new List<string>();
                            List<string> strFldAlias = new List<string>();
                            List<int> intFldIdxs = new List<int>();
                            fieldObj = null;
                            if (drv["FIELDNAME"] != null && drv["FIELDNAME"].ToString().Trim() != "" && drv["FIELDNAME"].ToString().Trim() != "*" && drv["FIELDNAME"].ToString().Trim() != "#")
                            {
                                strFldNames = new List<string>(drv["FIELDNAME"].ToString().Trim().Split(','));
                                foreach (string strFldName in strFldNames)
                                {
                                    if (inObject.Fields.FindField(strFldName) >= 0)
                                    {
                                        strFldAlias.Add(inObject.Fields.get_Field(inObject.Fields.FindField(strFldName)).AliasName);

                                        int tem = inObject.Fields.FindField(strFldName);
                                        intFldIdxs.Add(tem);
                                        fieldObj = inObject.Fields.get_Field(tem);
                                        AAState.WriteLine("      Field Name: " + inObject.Fields.get_Field(inObject.Fields.FindField(strFldName)).AliasName + " was found at index: " + tem);

                                        proc = true;
                                    }
                                    else if (inObject.Fields.FindFieldByAliasName(strFldName) >= 0)
                                    {
                                        int tem = inObject.Fields.FindFieldByAliasName(strFldName);
                                        intFldIdxs.Add(tem);
                                        strFldAlias.Add(inObject.Fields.get_Field(tem).AliasName);

                                        fieldObj = inObject.Fields.get_Field(tem);

                                        AAState.WriteLine("      Field Name: " + strFldName + " was found at index: " + tem);

                                        proc = true;
                                    }
                                    else
                                    {
                                        intFldIdxs.Add(-1);
                                        strFldAlias.Add("{Not Found}");

                                        AAState.WriteLine("      " + strFldName + " Field not found");

                                        fieldObj = null;
                                        proc = false;
                                    }
                                }
                            }
                            else if (drv["FIELDNAME"].ToString() == "#")
                            {
                                AAState.WriteLine("      Field is set to edited field");
                                IRowChanges pRowCh = null;
                                IField pTmpFld = null;
                                pRowCh = inObject as IRowChanges;

                                for (int i = 0; i < inObject.Fields.FieldCount; i++)
                                {
                                    pTmpFld = inObject.Fields.get_Field(i);

                                    if (pTmpFld.Type != esriFieldType.esriFieldTypeGlobalID &&
                                                               pTmpFld.Type != esriFieldType.esriFieldTypeOID &&
                                                               pTmpFld.Type != esriFieldType.esriFieldTypeGeometry &&
                                                                pTmpFld.Name.ToUpper() != "SHAPE_LENGTH" &&
                                                               pTmpFld.Name.ToUpper() != "SHAPE.LEN" &&
                                                               pTmpFld.Name.ToUpper() != "SHAPE_AREA" &&
                                                               pTmpFld.Name.ToUpper() != "SHAPE.AREA")
                                    {
                                        if (pRowCh.get_ValueChanged(i) == true)
                                        {
                                            AAState.WriteLine("      Adding " + pTmpFld.Name + " to field array");
                                            strFldNames.Add(pTmpFld.Name);
                                            intFldIdxs.Add(i);
                                            proc = true;

                                        }
                                    }

                                }
                                pRowCh = null;
                                pTmpFld = null;
                            }
                            else
                            {
                                AAState.WriteLine("      Field is not specified, empty, or set for all.");
                                fieldObj = null;
                                proc = true;
                            }

                            if (proc)
                            {

                                try
                                {
                                    switch (valMethod)
                                    {

                                        case "FIELD_TRIGGER"://Value|FieldToChange|Value

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FIELD_TRIGGER");
                                                if (inFeature != null & valData != null)
                                                {

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    string valToCheck = "";
                                                    string fldToChange = "";
                                                    string valToSet = "";
                                                    if (args.GetLength(0) == 3)
                                                    {
                                                        valToCheck = args[0];
                                                        fldToChange = args[1];
                                                        valToSet = args[2];

                                                    }

                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Incorrect Value info was not found");
                                                        continue;
                                                    }

                                                    IRowChanges pRowCh = null;

                                                    pRowCh = inObject as IRowChanges;

                                                    if (intFldIdxs.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Field Not Set");
                                                        continue;
                                                    }
                                                    if (intFldIdxs[0] == -1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Field Not Found");
                                                        continue;
                                                    }
                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]))
                                                    {
                                                        AAState.WriteLine("                  Listed field changed");
                                                        if (inObject.get_Value(intFldIdxs[0]).ToString() == valToCheck)
                                                        {
                                                            AAState.WriteLine("                  Values Match");
                                                            int chngFldIdx = Globals.GetFieldIndex(inObject.Fields, fldToChange);
                                                            if (chngFldIdx == -1)
                                                            {
                                                                AAState.WriteLine("                  ERROR: Field Not Found");
                                                                continue;
                                                            }
                                                            try
                                                            {
                                                                inObject.set_Value(chngFldIdx, valToSet);
                                                                AAState.WriteLine("                  Value Set");
                                                            }
                                                            catch
                                                            {
                                                                AAState.WriteLine("                  ERROR: Could not store Value: " + valToSet);
                                                            }

                                                        }
                                                    }
                                                    pRowCh = null;

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FIELD_TRIGGER: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FIELD_TRIGGER");
                                            }
                                            break;
                                        case "VALIDATE_ATTRIBUTE_LOOKUP":
                                            {
                                                AAState.WriteLine("                  Trying VALIDATE_ATTRIBUTE_LOOKUP");
                                                IRowChanges pRowCh = null;
                                                ISQLSyntax sqlSyntax = null;
                                                IQueryFilter pQFilt = null;
                                                try
                                                {
                                                    if ((valData != null) && (inObject != null))
                                                    {

                                                        pRowCh = inObject as IRowChanges;
                                                        bool valueChanged = false;
                                                        for (int i = 0; i < intFldIdxs.Count; i++)
                                                        {
                                                            if (pRowCh.get_ValueChanged(intFldIdxs[i]) == true)
                                                            {
                                                                valueChanged = true;
                                                                break;

                                                            }
                                                        }
                                                        if (valueChanged == false)
                                                        {
                                                            AAState.WriteLine("                  VALIDATE_ATTRIBUTE_LOOKUP: Target value(s) did not change, skipping");
                                                            continue;
                                                        }
                                                        sourceLayerName = "";
                                                        string[] sourceFieldNames = null;

                                                        // Parse arguments
                                                        args = valData.Split('|');
                                                        if (args.Length == 2)
                                                        {
                                                            sourceLayerName = args[0].ToString().Trim();
                                                            sourceFieldNames = args[1].ToString().Split(',');

                                                        }

                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR:  the valuemethod is not defined properly for this rule");
                                                            continue;

                                                        }

                                                        if ((sourceFieldNames != null) &&
                                                            (sourceFieldNames.Length > 0))
                                                        {
                                                            AAState.WriteLine("                  Looking for layer: " + sourceLayerName);

                                                            boolLayerOrFC = true;
                                                            if (sourceLayerName.Contains("("))
                                                            {
                                                                string[] tempSplt = sourceLayerName.Split('(');
                                                                sourceLayerName = tempSplt[0];
                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                                if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                            }
                                                            else
                                                            {

                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                            }

                                                            IFields pFlds = null;

                                                            IDataset pDs = null;
                                                            string layNameFnd = "";
                                                            bool matchingLayFnd = false;
                                                            IStandaloneTable pTbl = null;
                                                            if (sourceLayer != null)
                                                            {
                                                                if (sourceLayer.FeatureClass != null)
                                                                {
                                                                    pFlds = sourceLayer.FeatureClass.Fields;
                                                                    pDs = sourceLayer.FeatureClass as IDataset;
                                                                    layNameFnd = sourceLayer.Name;
                                                                    matchingLayFnd = true;
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayerName + " data source is not set");
                                                                    continue;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                pTbl = Globals.FindStandAloneTable(AAState._editor.Map, sourceLayerName) as IStandaloneTable;

                                                                if (pTbl != null)
                                                                {
                                                                    if (pTbl.Table != null)
                                                                    {
                                                                        pFlds = pTbl.Table.Fields;
                                                                        pDs = pTbl.Table as IDataset;
                                                                        layNameFnd = pTbl.Name;

                                                                        matchingLayFnd = true;
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayerName + " data source is not set");
                                                                    continue;
                                                                }

                                                            }
                                                            if (matchingLayFnd == false)
                                                            {
                                                                AAState.WriteLine("                  ERROR: " + sourceLayerName + " was not found");
                                                                continue;
                                                            }
                                                            sqlSyntax = (ISQLSyntax)(pDs.Workspace);
                                                            string specChar = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_WildcardManyMatch);

                                                            AAState.WriteLine("                  Lookup layer " + layNameFnd + " was Found: " + sourceLayerName);

                                                            AAState.WriteLine("                  Checking for field in Lookup table");

                                                            if (sourceFieldNames.Length != intFldIdxs.Count)
                                                            {
                                                                AAState.WriteLine("                  Number of listed fields do not match");
                                                                continue;

                                                            }
                                                            int[] sourceFieldNums = new int[sourceFieldNames.Length];

                                                            pQFilt = new QueryFilterClass();
                                                            string sqlString = "";
                                                            string sqlStringUpper = "";
                                                            string sqlUpp = "";
                                                            if (sqlSyntax.GetStringComparisonCase())
                                                            {
                                                                sqlUpp = "UPPER";
                                                            }
                                                            for (int i = 0; i < sourceFieldNames.Length; i++)
                                                            {
                                                                sourceFieldNums[i] = Globals.GetFieldIndex(pFlds, sourceFieldNames[i].Trim());
                                                                if (sourceFieldNums[i] < 0)
                                                                {
                                                                    AAState.WriteLine("                  Fields Missing: " + sourceFieldName[i]);
                                                                    break;

                                                                }
                                                                if (pFlds.get_Field(sourceFieldNums[i]).Type == esriFieldType.esriFieldTypeString)
                                                                {
                                                                    if (sqlString == "")
                                                                    {
                                                                        sqlString = pFlds.get_Field(sourceFieldNums[i]).Name + "" + " = '" + inObject.get_Value(intFldIdxs[i]).ToString() + "'";
                                                                        sqlStringUpper = sqlUpp + "(" + pFlds.get_Field(sourceFieldNums[i]).Name + ")" + " LIKE '" + specChar + inObject.get_Value(intFldIdxs[i]).ToString().ToUpper().Replace(" ", specChar) + specChar + "'";
                                                                    }
                                                                    else
                                                                    {
                                                                        sqlString = sqlString + " AND " + pFlds.get_Field(sourceFieldNums[i]).Name + "" + " = '" + inObject.get_Value(intFldIdxs[i]).ToString() + "'";
                                                                        sqlStringUpper = sqlStringUpper + " AND " + sqlUpp + "(" + pFlds.get_Field(sourceFieldNums[i]).Name + ")" + " LIKE '" + specChar + inObject.get_Value(intFldIdxs[i]).ToString().ToUpper().Replace(" ", specChar) + specChar + "'";
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    if (sqlString == "")
                                                                    {
                                                                        sqlString = pFlds.get_Field(sourceFieldNums[i]).Name + " = " + inObject.get_Value(intFldIdxs[i]);
                                                                        sqlStringUpper = pFlds.get_Field(sourceFieldNums[i]).Name + " LIKE " + specChar + inObject.get_Value(intFldIdxs[i]) + specChar;
                                                                    }
                                                                    else
                                                                    {
                                                                        sqlString = sqlString + " AND " + pFlds.get_Field(sourceFieldNums[i]).Name + " = " + inObject.get_Value(intFldIdxs[i]);
                                                                        sqlStringUpper = sqlStringUpper + " AND " + pFlds.get_Field(sourceFieldNums[i]).Name + " LIKE " + specChar + inObject.get_Value(intFldIdxs[i]) + specChar;
                                                                    }
                                                                }

                                                            }
                                                            pQFilt.WhereClause = sqlString;

                                                            AAState.WriteLine("                  " + pQFilt.WhereClause + " used to search for matching record");
                                                            int intRecFound = 0;
                                                            if (sourceLayer == null)
                                                            {
                                                                intRecFound = pTbl.Table.RowCount(pQFilt);
                                                            }
                                                            else
                                                            {
                                                                intRecFound = sourceLayer.FeatureClass.FeatureCount(pQFilt);
                                                            }

                                                            AAState.WriteLine("                  " + intRecFound + " rows found using " + sqlString);

                                                            if (intRecFound != 1)
                                                            {

                                                                pQFilt.WhereClause = sqlStringUpper;

                                                                AAState.WriteLine("                  " + pQFilt.WhereClause + " used to search for matching record");
                                                                if (sourceLayer == null)
                                                                {
                                                                    intRecFound = pTbl.Table.RowCount(pQFilt);
                                                                }
                                                                else
                                                                {
                                                                    intRecFound = sourceLayer.FeatureClass.FeatureCount(pQFilt);
                                                                }
                                                                AAState.WriteLine("                  " + intRecFound + " rows found");

                                                                if (intRecFound == 0)
                                                                {
                                                                    AAState.WriteLine("                     Abort Edit");
                                                                    AAState._editor.AbortOperation();
                                                                    return false;

                                                                }

                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Prompting for user input");
                                                                    ICursor pCurs = null;
                                                                    if (sourceLayer == null)
                                                                    {
                                                                        pCurs = pTbl.Table.Search(pQFilt, true);
                                                                    }
                                                                    else
                                                                    {
                                                                        pCurs = sourceLayer.FeatureClass.Search(pQFilt, true) as ICursor;
                                                                    }

                                                                    pQFilt = null;

                                                                    List<string> pLst = Globals.CursorToList(ref pCurs, sourceFieldNums);
                                                                    if (pCurs != null)
                                                                        Marshal.ReleaseComObject(pCurs);
                                                                    pCurs = null;

                                                                    string disFld = "";
                                                                    for (int j = 0; j < sourceFieldNames.Length - 1; j++)
                                                                    {
                                                                        disFld = disFld == "" ? sourceFieldNames[j] : disFld + "|" + sourceFieldNames[j];

                                                                    }
                                                                    string selectVal = Globals.showOptionsForm(pLst, "Select a valid value to store for " + disFld, ComboBoxStyle.DropDownList);
                                                                    if (selectVal == "||Cancelled||")
                                                                    {
                                                                        AAState.WriteLine("                     Abort Edit");
                                                                        AAState._editor.AbortOperation();
                                                                        return false;

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Value selected: " + selectVal);
                                                                        string[] strVals = selectVal.Split('|');

                                                                        for (int i = 0; i < sourceFieldNums.Length; i++)
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[i], strVals[i]);
                                                                        }

                                                                    }

                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  One Exact match was found");
                                                            }
                                                            pQFilt = null;

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Invalid Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Not a feature or missing Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: VALIDATE_ATTRIBUTE_LOOKUP" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    pQFilt = null;
                                                    sqlSyntax = null;
                                                    pRowCh = null;
                                                    AAState.WriteLine("                  Finished: VALIDATE_ATTRIBUTE_LOOKUP");
                                                }
                                                break;
                                            }

                                        case "PREVIOUS_VALUE":
                                            {
                                                AAState.WriteLine("                  Trying PREVIOUS_VALUE");
                                                IRowChanges pRowCh = null;
                                                try
                                                {
                                                    if ((valData != null) && (inObject != null))
                                                    {

                                                        pRowCh = inObject as IRowChanges;
                                                        bool valueChanged = false;
                                                        for (int i = 0; i < intFldIdxs.Count; i++)
                                                        {
                                                            if (pRowCh.get_ValueChanged(intFldIdxs[i]) == true)
                                                            {
                                                                valueChanged = true;
                                                                break;

                                                            }
                                                        }
                                                        if (valueChanged == false)
                                                        {
                                                            AAState.WriteLine("                  PREVIOUS_VALUE: Target value(s) did not change, skipping");
                                                            continue;
                                                        }

                                                        string[] sourceFieldNames = null;

                                                        // Parse arguments
                                                        args = valData.Split('|');
                                                        if (args.Length == 1)
                                                        {

                                                            sourceFieldNames = args[0].ToString().Split(',');

                                                        }

                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR:  the valuemethod is not defined properly for this rule");
                                                            continue;

                                                        }

                                                        if ((sourceFieldNames != null) &&
                                                            (sourceFieldNames.Length > 0))
                                                        {
                                                            int flx = inObject.Fields.FindField(sourceFieldNames[0]);
                                                            if (flx > 0)
                                                            {
                                                                inObject.set_Value(flx, pRowCh.get_OriginalValue(intFldIdxs[0]));
                                                                inObject.Store();

                                                            }
                                                        }
                                                        else
                                                        {

                                                            AAState.WriteLine("                  ERROR: Invalid Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Not a feature or missing Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: PREVIOUS_VALUE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {

                                                    pRowCh = null;
                                                    AAState.WriteLine("                  Finished: PREVIOUS_VALUE");
                                                }
                                                break;
                                            }

                                        case "ANGLE":

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: ANGLE");
                                                if (inFeature != null)
                                                {
                                                    if (intFldIdxs.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  Field not found");
                                                        continue;

                                                    }
                                                    if ((inFeature.Class as IFeatureClass).ShapeType != esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        AAState.WriteLine("                 Input feature is not a line");
                                                        continue;
                                                    }

                                                    bool boolGeo = true;
                                                    if (valData.Trim() != "")
                                                    {
                                                        if (valData.ToUpper() == "A")
                                                        {
                                                            boolGeo = false;
                                                        }
                                                    }
                                                    AAState.WriteLine("                 Getting Angle for feature");
                                                    IPolyline pLyLine = inFeature.Shape as IPolyline;

                                                    ILine pLine = new LineClass();
                                                    pLine.ToPoint = pLyLine.FromPoint;
                                                    pLine.FromPoint = pLyLine.ToPoint;

                                                    double angArth = pLine.Angle * 180 / Math.PI;
                                                    if (angArth < 0)
                                                    {
                                                        angArth = 360 + angArth;
                                                    }

                                                    double angGeo = 270 - angArth;
                                                    if (angGeo < 0)
                                                    {
                                                        angGeo = 360 + angGeo;
                                                    }
                                                    double ang;
                                                    if (boolGeo)
                                                    {
                                                        ang = angGeo;
                                                    }
                                                    else
                                                    {
                                                        ang = angArth;
                                                    }
                                                    AAState.WriteLine("                  Angle Calculated: " + ang);
                                                    try
                                                    {
                                                        inObject.set_Value(intFldIdxs[0], ang);
                                                        AAState.WriteLine("                  Angle Stored");

                                                    }
                                                    catch
                                                    {
                                                        AAState.WriteLine("                  Could not store angle");
                                                    }

                                                    pLine = null;
                                                    pLyLine = null;

                                                    AAState.WriteLine("                  Done");

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: ANGLE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: ANGLE");
                                            }
                                            break;

                                        case "CREATE_PERP_LINE"://Layer to Search For|Offset Distante or Field|Search distance to look for a line|UseSnapPoint|TargetLayer|TargetLayerTemplate

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: CREATE_PERP_LINE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    double offsetVal = 5;
                                                    bool useSnapPnt = false;
                                                    string targetLayerName = "";
                                                    IFeatureLayer targetLayer = null;
                                                    string targetLayerTemp = "";

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int fldOff = -1;
                                                    if (args.GetLength(0) == 6)
                                                    {

                                                        sourceLayerNames = args[0].ToString().Split(',');

                                                        if (Globals.IsNumeric(args[1]))
                                                            Double.TryParse(args[1], out offsetVal);
                                                        else
                                                        {
                                                            fldOff = Globals.GetFieldIndex(inObject.Fields, args[1]);

                                                        }

                                                        Double.TryParse(args[2], out searchDistance);
                                                        Boolean.TryParse(args[3], out useSnapPnt);
                                                        targetLayerName = args[4];
                                                        targetLayerTemp = args[5];

                                                    }
                                                    else if (args.GetLength(0) == 5)
                                                    {

                                                        sourceLayerNames = args[0].ToString().Split(',');

                                                        if (Globals.IsNumeric(args[1]))
                                                            Double.TryParse(args[1], out offsetVal);
                                                        else
                                                        {
                                                            fldOff = Globals.GetFieldIndex(inObject.Fields, args[1]);

                                                        }

                                                        Double.TryParse(args[2], out searchDistance);
                                                        Boolean.TryParse(args[3], out useSnapPnt);
                                                        targetLayerName = args[4];
                                                        targetLayerTemp = "";
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Incorrect Value info was not found");
                                                        continue;
                                                    }
                                                    if (intFldIdxs.Count > 0)
                                                    {
                                                        AAState.WriteLine("                  WARNING: Input fields are not used for this tool");
                                                        continue;
                                                    }

                                                    targetLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, targetLayerName, ref boolLayerOrFC);
                                                    if (targetLayer == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Target layer not found. " + targetLayerName);
                                                        continue;
                                                    }
                                                    if (targetLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Target layer is not a line layer. " + targetLayerName);
                                                        continue;
                                                    }

                                                    for (int i = 0; i < sourceLayerNames.Length; i++)
                                                    {
                                                        sourceLayerName = sourceLayerNames[i].ToString();
                                                        if (sourceLayerName != "")

                                                            sourceLayerName = args[i].ToString();
                                                        if (i == 0)
                                                            i++;
                                                        boolLayerOrFC = true;

                                                        if (sourceLayerName.Contains("("))
                                                        {
                                                            string[] tempSplt = sourceLayerName.Split('(');
                                                            sourceLayerName = tempSplt[0];
                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                            if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                        }
                                                        if (sourceLayer == null)
                                                        {
                                                            AAState.WriteLine("                  ERROR/WARNING: " + sourceLayer + " was not found");
                                                            continue;
                                                        }
                                                        if (fldOff != -1)
                                                        {
                                                            try
                                                            {
                                                                string temp = inObject.get_Value(fldOff).ToString();
                                                                if (Globals.IsNumeric(temp))
                                                                {
                                                                    Double.TryParse(temp, out offsetVal);
                                                                }
                                                            }
                                                            catch
                                                            {
                                                            }

                                                        }

                                                        IPolyline pTempLine = new PolylineClass();
                                                        pTempLine = Globals.CreateAngledLineFromLocationOnLine((IPoint)inFeature.Shape, sourceLayer,
                                                            boolLayerOrFC, Globals.ConvertDegToRads(90), offsetVal, "true", true, false);

                                                        IEditTemplate pTemp = null;
                                                        IFeature pFeat = null;

                                                        if (targetLayerTemp != "")
                                                            pTemp = Globals.GetEditTemplate(targetLayerTemp, targetLayer);
                                                        if (pTemp != null)
                                                        {
                                                            AAState.WriteLine("                  Template found");
                                                            pFeat = Globals.CreateFeature(pTempLine, pTemp, AAState._editor, ArcMap.Application, false, false, false);

                                                        }
                                                        else
                                                        {

                                                            pFeat = Globals.CreateFeature(pTempLine, targetLayer, AAState._editor, ArcMap.Application, false, false, false);
                                                        }

                                                        if (NewFeatureList == null)
                                                        {
                                                            NewFeatureList = new List<IObject>();
                                                        }
                                                        AAState.WriteLine("                  Added to the new feature list");
                                                        NewFeatureList.Add(pFeat);

                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: CREATE_PERP_LINE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: CREATE_PERP_LINE");
                                            }
                                            break;
                                        case "AUTONUMBER"://Layer to Search For|Offset Distante or Field|Search distance to look for a line

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: AUTONUMBER");
                                                if (inObject != null)
                                                {
                                                    if (intFldIdxs.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  Field not found");
                                                        continue;

                                                    }
                                                    AAState.WriteLine("                  Getting Max value for Field: " + strFldNames[0]);
                                                    string res = Globals.GetFieldStats(inObject.Class as IFeatureClass, strFldNames[0], Globals.statsType.Max);
                                                    AAState.WriteLine("                  Value returned: " + res);
                                                    if (res == "External component has thrown an exception.")
                                                    {
                                                        AAState.WriteLine("                  The field specified was not a numeric field");

                                                        AAState.WriteLine("                  Starting at 1 ");
                                                        long val = 1;

                                                        try
                                                        {
                                                            AAState.WriteLine("                  Trying to set value ");
                                                            inObject.set_Value(intFldIdxs[0], val);
                                                            AAState.WriteLine("                  Value set");

                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Could not set value: " + ex.Message.ToString());
                                                        }
                                                    }
                                                    else
                                                    {

                                                        if (Globals.IsNumeric(res))
                                                        {
                                                            AAState.WriteLine("                  Value is numeric");

                                                            AAState.WriteLine("                  Trying to Incriment " + res);
                                                            try
                                                            {
                                                                long val = (Convert.ToInt64(res) + 1);

                                                                AAState.WriteLine("                  Incrimented to " + res);
                                                                try
                                                                {
                                                                    AAState.WriteLine("                  Trying to set value " + res);
                                                                    inObject.set_Value(intFldIdxs[0], val);
                                                                    AAState.WriteLine("                  Value set" + res);

                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Could not set value: " + ex.Message.ToString());
                                                                }

                                                            }

                                                            catch (Exception ex)
                                                            {
                                                                AAState.WriteLine("                  ERROR: Could not set value: " + ex.Message.ToString());
                                                                AAState.WriteLine("                  Setting the value to 1");
                                                                long val = 1;

                                                                inObject.set_Value(intFldIdxs[0], val);
                                                                AAState.WriteLine("                  Value set");

                                                            }

                                                        }

                                                        else
                                                        {
                                                            AAState.WriteLine("                  Value is not numeric: " + res);

                                                            AAState.WriteLine("                  Starting at 1 ");
                                                            long val = 1;

                                                            try
                                                            {
                                                                AAState.WriteLine("                  Trying to set value " + res);
                                                                inObject.set_Value(intFldIdxs[0], val);
                                                                AAState.WriteLine("                  Value set" + res);

                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                AAState.WriteLine("                  ERROR: Could not set value: " + ex.Message.ToString());
                                                            }

                                                        }
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: AUTONUMBER: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: AUTONUMBER");
                                            }
                                            break;

                                        case "COPY_LINKED_RECORD"://Feature Layer|Field To Copy|Primary Key Field|Foreign Key Field
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying: COPY_LINKED_RECORD");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 4)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inObject == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    string[] targetLayerNames;
                                                    string targetFieldName = "";

                                                    found = false;
                                                    AAState.WriteLine("                  Getting Value Info");
                                                    targetLayerNames = args[0].ToString().Split(',');
                                                    targetFieldName = args[1].ToString();
                                                    string targetLayerName = "";
                                                    string sourceIDFieldName = args[2].ToString();
                                                    string targetIDFieldName = args[3].ToString();
                                                    AAState.WriteLine("                  Checking values");
                                                    if (targetFieldName != null)
                                                    {
                                                        AAState.WriteLine("                  Checking Field in Edited Layer");

                                                        int fldIDSourecIdx = Globals.GetFieldIndex(inObject.Fields, sourceIDFieldName);
                                                        if (fldIDSourecIdx > -1 && intFldIdxs.Count > 0 )
                                                        {
                                                            if (inObject.get_Value(fldIDSourecIdx) != null && inObject.get_Value(fldIDSourecIdx) != DBNull.Value)
                                                            {
                                                                if (inObject.get_Value(fldIDSourecIdx).ToString() != "")
                                                                {

                                                                    for (int i = 0; i < targetLayerNames.Length; i++)
                                                                    {
                                                                        targetLayerName = targetLayerNames[i].ToString().Trim();

                                                                        if (targetLayerName != "")
                                                                        {

                                                                            // Get layer
                                                                            AAState.WriteLine("                  Checking for join record");
                                                                            bool FCorLayerSource = true;
                                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, targetLayerName, ref FCorLayerSource);

                                                                            if (sourceLayer != null)
                                                                            {

                                                                                int fldValToCopyIdx = sourceLayer.FeatureClass.Fields.FindField(targetFieldName);
                                                                                int fldIDTargetIdx = sourceLayer.FeatureClass.Fields.FindField(targetIDFieldName);
                                                                                if (fldIDTargetIdx > -1 && fldValToCopyIdx > -1)
                                                                                {
                                                                                    IQueryFilter pQFilt = Globals.createQueryFilter();
                                                                                    if (sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Type == esriFieldType.esriFieldTypeString)
                                                                                    {
                                                                                        pQFilt.WhereClause = "" + sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Name + "" + " = '" + inObject.get_Value(fldIDSourecIdx).ToString() + "'";

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        pQFilt.WhereClause = sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Name + " = " + inObject.get_Value(fldIDSourecIdx);

                                                                                    }
                                                                                    IFeatureCursor pCurs;

                                                                                    pCurs = sourceLayer.FeatureClass.Search(pQFilt, true);
                                                                                    IFeature pRow;
                                                                                    while ((pRow = pCurs.NextFeature()) != null)
                                                                                    {
                                                                                        AAState.WriteLine("                  Trying to Copy Value from Record");
                                                                                        try
                                                                                        {
                                                                                            inObject.set_Value(intFldIdxs[0], pRow.get_Value(fldValToCopyIdx));
                                                                                            break;

                                                                                        }
                                                                                        catch
                                                                                        {
                                                                                            AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldValToCopyIdx) + " to field: " + strFldNames[0]);
                                                                                        }

                                                                                        pRow = null;
                                                                                    }
                                                                                    pRow = null;

                                                                                    AAState.WriteLine("                  Value successfully copied");

                                                                                    if (pCurs != null)
                                                                                        Marshal.ReleaseComObject(pCurs);
                                                                                    pCurs = null;

                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                                }

                                                                            }
                                                                            else
                                                                            {

                                                                                ITable pTable = Globals.FindTable(AAState._editor.Map, targetLayerName);
                                                                                if (pTable != null)
                                                                                {
                                                                                    int fldValToCopyIdx = Globals.GetFieldIndex(pTable.Fields, targetFieldName);
                                                                                    int fldIDTargetIdx = Globals.GetFieldIndex(pTable.Fields, targetIDFieldName);
                                                                                    if (fldIDTargetIdx > -1 && fldValToCopyIdx > -1)
                                                                                    {
                                                                                        IQueryFilter pQFilt = Globals.createQueryFilter();
                                                                                        if (pTable.Fields.get_Field(fldIDTargetIdx).Type == esriFieldType.esriFieldTypeString)
                                                                                        {
                                                                                            pQFilt.WhereClause = "" + pTable.Fields.get_Field(fldIDTargetIdx).Name + "" + " = '" + inObject.get_Value(fldIDSourecIdx).ToString() + "'";

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pQFilt.WhereClause = pTable.Fields.get_Field(fldIDTargetIdx).Name + " = " + inObject.get_Value(fldIDSourecIdx);

                                                                                        }
                                                                                        ICursor pCurs;

                                                                                        pCurs = pTable.Search(pQFilt, true);
                                                                                        IRow pRow;
                                                                                        bool valSet = false;
                                                                                        pRow = pCurs.NextRow();
                                                                                        while (pRow != null)
                                                                                        {
                                                                                            AAState.WriteLine("                  Trying to Copy Value from Record");
                                                                                            try
                                                                                            {
                                                                                                inObject.set_Value(intFldIdxs[0], pRow.get_Value(fldValToCopyIdx));

                                                                                                AAState.WriteLine("                  " + pRow.get_Value(fldValToCopyIdx).ToString() + " Set in related record");
                                                                                                valSet = true;
                                                                                                break;

                                                                                            }
                                                                                            catch
                                                                                            {
                                                                                                AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldValToCopyIdx) + " to field: " + strFldNames[0]);
                                                                                            }

                                                                                            pRow = pCurs.NextRow();

                                                                                        }
                                                                                        pRow = null;
                                                                                        if (valSet)
                                                                                            AAState.WriteLine("                  Value successfully copied");
                                                                                        else
                                                                                            AAState.WriteLine("                  Related record not found.");

                                                                                        if (pCurs != null)
                                                                                            Marshal.ReleaseComObject(pCurs);
                                                                                        pCurs = null;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: Table to populate not found: " + sourceLayerName);
                                                                                }
                                                                                pTable = null;

                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: ID was null");
                                                        }

                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: COPY_LINKED_RECORD" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: COPY_LINKED_RECORD");

                                                }
                                                break;

                                            }
                                        case "UPDATE_LINKED_RECORD"://Feature Layer|Field To Copy|Primary Key Field|Foreign Key Field
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying: UPDATE_LINKED_RECORD");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 4)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inObject == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }

                                                    IRowChanges pRowCh = inObject as IRowChanges;

                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]) == false && mode != "ON_CREATE")
                                                    {
                                                        AAState.WriteLine("                  PROMPT: Target value did not change, skipping");
                                                        pRowCh = null;
                                                        continue;
                                                    }
                                                    else
                                                    {
                                                        pRowCh = null;
                                                        string[] targetLayerNames;
                                                        string targetFieldName = "";

                                                        found = false;
                                                        AAState.WriteLine("                  Getting Value Info");
                                                        targetLayerNames = args[0].ToString().Split(',');
                                                        targetFieldName = args[1].ToString();
                                                        string targetLayerName = "";
                                                        string sourceIDFieldName = args[2].ToString();
                                                        string targetIDFieldName = args[3].ToString();
                                                        AAState.WriteLine("                  Checking values");
                                                        if (targetFieldName != null)
                                                        {
                                                            AAState.WriteLine("                  Checking Field in Edited Layer");

                                                            int fldIDSourecIdx = Globals.GetFieldIndex(inObject.Fields, sourceIDFieldName);
                                                            if (fldIDSourecIdx > -1 && intFldIdxs.Count > 0)
                                                            {
                                                                if (inObject.get_Value(fldIDSourecIdx) != null && inObject.get_Value(fldIDSourecIdx) != DBNull.Value)
                                                                {
                                                                    if (inObject.get_Value(fldIDSourecIdx).ToString() != "")
                                                                    {

                                                                        for (int i = 0; i < targetLayerNames.Length; i++)
                                                                        {
                                                                            targetLayerName = targetLayerNames[i].ToString().Trim();

                                                                            if (targetLayerName != "")
                                                                            {

                                                                                // Get layer
                                                                                AAState.WriteLine("                  Checking for related record");
                                                                                bool FCorLayerSource = true;
                                                                                sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, targetLayerName, ref FCorLayerSource);

                                                                                if (sourceLayer != null)
                                                                                {

                                                                                    int fldValToCopyIdx = sourceLayer.FeatureClass.Fields.FindField(targetFieldName);
                                                                                    int fldIDTargetIdx = sourceLayer.FeatureClass.Fields.FindField(targetIDFieldName);
                                                                                    if (fldIDTargetIdx > -1 && fldValToCopyIdx > -1)
                                                                                    {
                                                                                        IQueryFilter pQFilt = Globals.createQueryFilter();
                                                                                        if (sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Type == esriFieldType.esriFieldTypeString)
                                                                                        {
                                                                                            pQFilt.WhereClause = "" + sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Name + "" + " = '" + inObject.get_Value(fldIDSourecIdx).ToString() + "'";

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pQFilt.WhereClause = sourceLayer.FeatureClass.Fields.get_Field(fldIDTargetIdx).Name + " = " + inObject.get_Value(fldIDSourecIdx);

                                                                                        }
                                                                                        IFeatureCursor pCurs;

                                                                                        pCurs = sourceLayer.FeatureClass.Search(pQFilt, true);
                                                                                        IFeature pRow;
                                                                                        bool valSet = false;
                                                                                        while ((pRow = pCurs.NextFeature()) != null)
                                                                                        {
                                                                                            AAState.WriteLine("                  Trying to Copy Value to the Record");
                                                                                            try
                                                                                            {
                                                                                                pRow.set_Value(fldValToCopyIdx, inObject.get_Value(intFldIdxs[0]));
                                                                                                pRow.Store();
                                                                                                AAState.WriteLine("                  " + inObject.get_Value(intFldIdxs[0]).ToString() + " Set in related record");
                                                                                                valSet = true;

                                                                                            }
                                                                                            catch
                                                                                            {
                                                                                                AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(intFldIdxs[0]).ToString() + " to field: " + targetFieldName);
                                                                                            }

                                                                                            pRow = null;
                                                                                        }
                                                                                        pRow = null;

                                                                                        if (valSet)
                                                                                            AAState.WriteLine("                  Value successfully copied");
                                                                                        else
                                                                                            AAState.WriteLine("                  Related record not found.");

                                                                                        if (pCurs != null)
                                                                                            Marshal.ReleaseComObject(pCurs);
                                                                                        pCurs = null;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                                    }

                                                                                }
                                                                                else
                                                                                {

                                                                                    ITable pTable = Globals.FindTable(AAState._editor.Map, targetLayerName);
                                                                                    if (pTable != null)
                                                                                    {
                                                                                        int fldValToCopyIdx = Globals.GetFieldIndex(pTable.Fields, targetFieldName);
                                                                                        int fldIDTargetIdx = Globals.GetFieldIndex(pTable.Fields, targetIDFieldName);
                                                                                        if (fldIDTargetIdx > -1 && fldValToCopyIdx > -1)
                                                                                        {
                                                                                            IQueryFilter pQFilt = Globals.createQueryFilter();
                                                                                            if (pTable.Fields.get_Field(fldIDTargetIdx).Type == esriFieldType.esriFieldTypeString)
                                                                                            {
                                                                                                pQFilt.WhereClause = "" + pTable.Fields.get_Field(fldIDTargetIdx).Name + "" + " = '" + inObject.get_Value(fldIDSourecIdx).ToString() + "'";

                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                pQFilt.WhereClause = pTable.Fields.get_Field(fldIDTargetIdx).Name + " = " + inObject.get_Value(fldIDSourecIdx);

                                                                                            }
                                                                                            ICursor pCurs;

                                                                                            pCurs = pTable.Search(pQFilt, false);
                                                                                            IRow pRow;
                                                                                            bool valSet = false;
                                                                                            pRow = pCurs.NextRow();
                                                                                            while (pRow != null)
                                                                                            {
                                                                                                AAState.WriteLine("                  Trying to Copy Value from Record");
                                                                                                try
                                                                                                {
                                                                                                    pRow.set_Value(fldValToCopyIdx, inObject.get_Value(intFldIdxs[0]));
                                                                                                    pRow.Store();

                                                                                                    AAState.WriteLine("                  " + inObject.get_Value(intFldIdxs[0]).ToString() + " Set in related record");
                                                                                                    valSet = true;

                                                                                                }
                                                                                                catch
                                                                                                {
                                                                                                    AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldValToCopyIdx) + " to field: " + strFldNames[0]);
                                                                                                }

                                                                                                pRow = pCurs.NextRow();

                                                                                            }
                                                                                            pRow = null;
                                                                                            if (valSet)
                                                                                                AAState.WriteLine("                  Value successfully copied");
                                                                                            else
                                                                                                AAState.WriteLine("                  Related record not found.");

                                                                                            if (pCurs != null)
                                                                                                Marshal.ReleaseComObject(pCurs);
                                                                                            pCurs = null;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR: Table to populate not found: " + sourceLayerName);
                                                                                    }
                                                                                    pTable = null;

                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: ID or Field to Copy was not found");
                                                            }

                                                        }

                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: UPDATE_LINKED_RECORD" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: UPDATE_LINKED_RECORD");

                                                }
                                                break;

                                            }

                                        case "OFFSET"://Layer to Search For|Offset Distante or Field|Search distance to look for a line

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: OFFSET");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    double offsetVal = 5;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int fldOff = -1;
                                                    if (args.GetLength(0) >= 3)
                                                    {

                                                        sourceLayerNames = args[0].ToString().Split(',');

                                                        if (Globals.IsNumeric(args[1]))
                                                            Double.TryParse(args[1], out offsetVal);
                                                        else
                                                        {
                                                            fldOff = Globals.GetFieldIndex(inObject.Fields, args[1]);

                                                        }

                                                        Double.TryParse(args[2], out searchDistance);
                                                    }
                                                    else if (args.GetLength(0) >= 2)
                                                    {

                                                        sourceLayerNames = args[0].ToString().Split(',');

                                                        if (Globals.IsNumeric(args[1]))
                                                            Double.TryParse(args[1], out offsetVal);
                                                        else
                                                        {
                                                            fldOff = Globals.GetFieldIndex(inObject.Fields, args[1]);

                                                        }

                                                        Double.TryParse("1", out searchDistance);
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Incorrect Value info was not found");
                                                        continue;
                                                    }
                                                    if (intFldIdxs.Count != 2)
                                                    {
                                                        AAState.WriteLine("                  ERROR: 2 fields in fieldname are required for this tool");
                                                        continue;
                                                    }

                                                    // Get layer

                                                    for (int i = 0; i < sourceLayerNames.Length; i++)
                                                    {
                                                        sourceLayerName = sourceLayerNames[i].ToString();
                                                        if (sourceLayerName != "")

                                                            sourceLayerName = args[i].ToString();
                                                        if (i == 0)
                                                            i++;
                                                        boolLayerOrFC = true;

                                                        if (sourceLayerName.Contains("("))
                                                        {
                                                            string[] tempSplt = sourceLayerName.Split('(');
                                                            sourceLayerName = tempSplt[0];
                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                            if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                            {
                                                                boolLayerOrFC = false;
                                                            }
                                                            else
                                                            {
                                                                boolLayerOrFC = true;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                        }
                                                        if (sourceLayer == null)
                                                        {
                                                            AAState.WriteLine("                  ERROR/WARNING: " + sourceLayer + " was not found");
                                                            continue;
                                                        }

                                                        IFeatureClass iFC = inFeature.Class as IFeatureClass;
                                                        if (sourceLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                                                        {
                                                            AAState.WriteLine("                  ERROR: " + sourceLayer + " is a polygon layer");

                                                            break;
                                                        }
                                                        if (sourceLayer != null)
                                                        {

                                                            sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, searchDistance, false);

                                                            pFS = (IFeatureSelection)sourceLayer;
                                                            if (boolLayerOrFC)
                                                            {
                                                                if (pFS.SelectionSet.Count > 0)
                                                                {
                                                                    pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                    fCursor = cCurs as IFeatureCursor;

                                                                }
                                                                else
                                                                {
                                                                    fCursor = sourceLayer.Search(sFilter, true);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                            }

                                                            while ((sourceFeature = fCursor.NextFeature()) != null)
                                                            {
                                                                double dAlong = 0;
                                                                if (sourceFeature.Class != inFeature.Class)
                                                                {
                                                                    IPoint pIntPnt;
                                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                                    {
                                                                        pIntPnt = Globals.GetIntersection(inFeature.ShapeCopy, sourceFeature.ShapeCopy as IPolyline) as IPoint;

                                                                    }
                                                                    else
                                                                        pIntPnt = inFeature.ShapeCopy as IPoint;
                                                                    IPoint snapPnt = null;

                                                                    dAlong = Globals.PointDistanceOnLine(pIntPnt, sourceFeature.Shape as IPolyline, 2, out snapPnt);

                                                                    snapPnt = null;
                                                                    pIntPnt = null;

                                                                }

                                                                else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                {
                                                                    IPoint pIntPnt;
                                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                                    {
                                                                        pIntPnt = Globals.GetIntersection(inFeature.ShapeCopy, sourceFeature.ShapeCopy as IPolyline) as IPoint;

                                                                    }
                                                                    else
                                                                        pIntPnt = inFeature.ShapeCopy as IPoint;
                                                                    IPoint snapPnt = null;

                                                                    dAlong = Globals.PointDistanceOnLine(pIntPnt, sourceFeature.Shape as IPolyline, 2, out snapPnt);
                                                                    snapPnt = null;

                                                                    pIntPnt = null;

                                                                }
                                                                AAState.WriteLine("                  Distance found: " + dAlong);
                                                                IPoint pNewPt = new PointClass();
                                                                IConstructPoint2 pConsPoint = pNewPt as IConstructPoint2;

                                                                if (fldOff != -1)
                                                                {
                                                                    string temp = inObject.get_Value(fldOff).ToString();
                                                                    if (Globals.IsNumeric(temp))
                                                                    {
                                                                        Double.TryParse(temp, out offsetVal);
                                                                    }

                                                                }
                                                                pConsPoint.ConstructOffset
                                                                    (sourceFeature.Shape as ICurve, esriSegmentExtension.esriNoExtension, dAlong, false, offsetVal);

                                                                inObject.set_Value(intFldIdxs[0], pNewPt.X);
                                                                inObject.set_Value(intFldIdxs[1], pNewPt.Y);

                                                                pNewPt = null;
                                                                pConsPoint = null;
                                                            }

                                                        }

                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: OFFSET: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: OFFSET");
                                            }
                                            break;

                                        case "SIDE":
                                            {
                                                AAState.WriteLine("                  Trying: SIDE");

                                                try
                                                {
                                                    //Layer|IDField|IDField source

                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        AAState.WriteLine("                     Feature and valueinfo is valid");

                                                        AAState.WriteLine("                     Splitting up value info: " + valData);
                                                        sourceLayerName = "";
                                                        sourceFieldName = "";
                                                        sourceField = -1;
                                                        string inputFieldName = "";
                                                        args = valData.Split('|');
                                                        if (args.Length < 2)
                                                        {
                                                            AAState.WriteLine("                  ERROR: SIDE: Value info does not have enough parameters");
                                                            continue;
                                                        }

                                                        switch (args.Length)
                                                        {
                                                            case 3:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                sourceFieldName = args[1].ToString();
                                                                inputFieldName = args[2].ToString();
                                                                break;
                                                            default:
                                                                AAState.WriteLine("                  ERROR: SIDE: Value info does not have enough parameters");
                                                                continue;

                                                        }
                                                        int fldValToCopyIdx = inObject.Fields.FindField(inputFieldName);

                                                        if (fldValToCopyIdx > -1)
                                                        {

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString();

                                                                if (sourceLayerName != "")
                                                                {

                                                                    boolLayerOrFC = true;
                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0];
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                    }
                                                                    if (sourceLayer != null)
                                                                    {

                                                                        // Get layer
                                                                        AAState.WriteLine("                  " + sourceLayerName + " Layer found");
                                                                        int fldValTargetJoinIdx = Globals.GetFieldIndex(sourceLayer, sourceFieldName);
                                                                        if (fldValTargetJoinIdx > -1)
                                                                        {
                                                                            IQueryFilter pQFilt = Globals.createQueryFilter();

                                                                            if (sourceLayer.FeatureClass.Fields.get_Field(fldValTargetJoinIdx).Type == esriFieldType.esriFieldTypeString)
                                                                            {
                                                                                pQFilt.WhereClause = "" + sourceLayer.FeatureClass.Fields.get_Field(fldValTargetJoinIdx).Name + "" + " = '" + inObject.get_Value(fldValToCopyIdx).ToString() + "'";

                                                                            }
                                                                            else
                                                                            {
                                                                                pQFilt.WhereClause = sourceLayer.FeatureClass.Fields.get_Field(fldValTargetJoinIdx).Name + " = " + inObject.get_Value(fldValToCopyIdx);

                                                                            }
                                                                            AAState.WriteLine("                     Where Clause: " + pQFilt.WhereClause);
                                                                            int cnt = sourceLayer.FeatureClass.FeatureCount(pQFilt);
                                                                            AAState.WriteLine("                     Feature Found: " + cnt);
                                                                            if (cnt > 0)
                                                                            {

                                                                                fCursor = sourceLayer.FeatureClass.Search(pQFilt, true);
                                                                                while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                                {
                                                                                    bool side = false;
                                                                                    if (Globals.GetPointOnLine(inFeature.Shape, sourceFeature.Shape, 450, out side) != null)
                                                                                    {

                                                                                        if (side)
                                                                                        {
                                                                                            AAState.WriteLine("                     Right Side");

                                                                                            inFeature.set_Value(intFldIdxs[0], "Right");
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                     Left Side");
                                                                                            inFeature.set_Value(intFldIdxs[0], "Left");
                                                                                        }
                                                                                        if (fCursor != null)
                                                                                            Marshal.ReleaseComObject(fCursor);
                                                                                        fCursor = null;
                                                                                        continue;
                                                                                    }

                                                                                }
                                                                                if (fCursor != null)
                                                                                    Marshal.ReleaseComObject(fCursor);
                                                                                fCursor = null;
                                                                            }
                                                                            pQFilt = null;

                                                                        }

                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: SIDE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    if (fCursor != null)
                                                        Marshal.ReleaseComObject(fCursor);
                                                    fCursor = null;

                                                    AAState.WriteLine("                  Finished: SIDE");

                                                }
                                                break;

                                            }

                                        case "PROMPT":
                                            {
                                                //Loop through all fields list in the fieldname
                                                //If blank or null, prompt user for value
                                                //Store Value

                                                IDomain pDom = default(IDomain);
                                                ISubtypes pSubType = null;
                                                List<Globals.DomSubList> lst = null;

                                                Globals.DomSubList dmRetVal = null;

                                                try
                                                {
                                                    if ((inObject != null))
                                                    {

                                                        pSubType = (ISubtypes)inObject.Class;

                                                        if (pSubType.HasSubtype)
                                                        {
                                                            int intSub;
                                                            if (intFldIdxs.Contains(pSubType.SubtypeFieldIndex))
                                                            {
                                                                lst = Globals.SubtypeToList(pSubType);
                                                                if (inObject.get_Value(pSubType.SubtypeFieldIndex) == null || inObject.get_Value(pSubType.SubtypeFieldIndex) == "" || inObject.get_Value(pSubType.SubtypeFieldIndex) == DBNull.Value)
                                                                {
                                                                    dmRetVal = Globals.showValuesOptionsForm(lst, "Provide a value for " + inObject.Class.AliasName + ":" + pSubType.SubtypeFieldName, "Provide a value for " + inObject.Class.AliasName + ":" + pSubType.SubtypeFieldName, ComboBoxStyle.DropDownList);
                                                                    inObject.set_Value(pSubType.SubtypeFieldIndex, dmRetVal.Value);

                                                                    intSub = Convert.ToInt32(dmRetVal.Value);
                                                                }
                                                                else
                                                                {
                                                                    intSub = Convert.ToInt32(inObject.get_Value(pSubType.SubtypeFieldIndex));
                                                                }

                                                                for (int l = 0; l < strFldNames.Count; l++)
                                                                {
                                                                    if (intFldIdxs[l] == pSubType.SubtypeFieldIndex)
                                                                        continue;

                                                                    if (intFldIdxs[l] != -1)
                                                                    {
                                                                        pDom = pSubType.get_Domain(intSub, inObject.Fields.get_Field(intFldIdxs[l]).Name);

                                                                        if (pDom == null)
                                                                        {
                                                                            if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                            {
                                                                                IList<string> pVals = new List<string>();

                                                                                string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + inObject.Class.AliasName + ":" + strFldAlias[l], "Provide a value for " + inObject.Class.AliasName + ":" + strFldAlias[l], ComboBoxStyle.DropDown);

                                                                                try
                                                                                {
                                                                                    inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                                }
                                                                                catch
                                                                                {

                                                                                }
                                                                                pVals = null;
                                                                            }

                                                                        }
                                                                        else
                                                                        {

                                                                            if (pDom is CodedValueDomain)
                                                                            {

                                                                                lst = Globals.DomainToList(pDom);
                                                                                if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                                {

                                                                                    dmRetVal = Globals.showValuesOptionsForm(lst, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDownList);
                                                                                    try
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[l], dmRetVal.Value);
                                                                                    }
                                                                                    catch
                                                                                    {

                                                                                    }

                                                                                    lst = null;
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                                {

                                                                                    IList<string> pVals = new List<string>();
                                                                                    string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDown);

                                                                                    try
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                                    }
                                                                                    catch
                                                                                    {

                                                                                    }

                                                                                    pVals = null;
                                                                                }
                                                                            }

                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  PROMPT: " + strFldNames[l] + " was not found");
                                                                    }
                                                                }

                                                            }
                                                            else
                                                            {
                                                                if (inObject.get_Value(pSubType.SubtypeFieldIndex) == null)
                                                                    intSub = pSubType.DefaultSubtypeCode;
                                                                else

                                                                    intSub = Convert.ToInt32(inObject.get_Value(pSubType.SubtypeFieldIndex));
                                                                for (int l = 0; l < strFldNames.Count; l++)
                                                                {
                                                                    if (intFldIdxs[l] != -1)
                                                                    {
                                                                        pDom = pSubType.get_Domain(intSub, inObject.Fields.get_Field(intFldIdxs[l]).Name);

                                                                        if (pDom == null)
                                                                        {
                                                                            if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                            {

                                                                                IList<string> pVals = new List<string>();
                                                                                string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDown);

                                                                                try
                                                                                {
                                                                                    inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                                }
                                                                                catch
                                                                                {

                                                                                }

                                                                                pVals = null;
                                                                            }
                                                                        }
                                                                        else
                                                                        {

                                                                            if (pDom is CodedValueDomain)
                                                                            {
                                                                                if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                                {

                                                                                    lst = Globals.DomainToList(pDom);

                                                                                    dmRetVal = Globals.showValuesOptionsForm(lst, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDownList);
                                                                                    try
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[l], dmRetVal.Value);
                                                                                    }
                                                                                    catch
                                                                                    {

                                                                                    }

                                                                                    lst = null;
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                                {

                                                                                    IList<string> pVals = new List<string>();
                                                                                    string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDown);

                                                                                    try
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                                    }
                                                                                    catch
                                                                                    {

                                                                                    }

                                                                                    pVals = null;
                                                                                }
                                                                            }

                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  PROMPT: " + strFldNames[l] + " was not found");
                                                                    }
                                                                }

                                                            }
                                                        }
                                                        else
                                                        {
                                                            for (int l = 0; l < strFldNames.Count; l++)
                                                            {

                                                                if (intFldIdxs[l] != -1)
                                                                {

                                                                    pDom = inObject.Fields.get_Field(intFldIdxs[l]).Domain;
                                                                    if (pDom == null)
                                                                    {
                                                                        if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                        {

                                                                            IList<string> pVals = new List<string>();
                                                                            string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDown);
                                                                            try
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                            }
                                                                            catch
                                                                            {

                                                                            }

                                                                            pVals = null;
                                                                        }
                                                                    }
                                                                    else
                                                                    {

                                                                        if (pDom is CodedValueDomain)
                                                                        {
                                                                            if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                            {

                                                                                lst = Globals.DomainToList(pDom);

                                                                                dmRetVal = Globals.showValuesOptionsForm(lst, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDownList);
                                                                                try
                                                                                {
                                                                                    inObject.set_Value(intFldIdxs[l], dmRetVal.Value);
                                                                                }
                                                                                catch
                                                                                {

                                                                                }

                                                                                lst = null;
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            if (inObject.get_Value(intFldIdxs[l]) == null || inObject.get_Value(intFldIdxs[l]) == "" || inObject.get_Value(intFldIdxs[l]) == DBNull.Value)
                                                                            {

                                                                                IList<string> pVals = new List<string>();
                                                                                string strRetVal = Globals.showValuesOptionsForm(pVals, "Provide a value for " + strFldAlias[l], "Provide a value for " + strFldAlias[l], ComboBoxStyle.DropDown);
                                                                                try
                                                                                {
                                                                                    inObject.set_Value(intFldIdxs[l], strRetVal);
                                                                                }
                                                                                catch
                                                                                {

                                                                                }
                                                                                pVals = null;
                                                                            }
                                                                        }

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  PROMPT: " + strFldNames[l] + " was not found");
                                                                }
                                                            }
                                                        }

                                                    }
                                                }

                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: PROMPT" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {

                                                    AAState.WriteLine("                  Finished: PROMPT");
                                                    pDom = null;
                                                    pSubType = null;
                                                    lst = null;

                                                    dmRetVal = null;
                                                }
                                                break;
                                            }

                                        case "CASCADE_ATTRIBUTE":
                                            {
                                                AAState.WriteLine("                  Trying: CASCADE_ATTRIBUTE");

                                                string flds;
                                                string targetLayer;
                                                IRowChanges pRowCh = null;

                                                try
                                                {

                                                    if ((valData != null) && (inObject != null))
                                                    {
                                                        AAState.WriteLine("                     Feature and valueinfo is valid");

                                                        AAState.WriteLine("                     Splitting up value info: " + valData);
                                                        //field name is the field to Check
                                                        //value|Layer|tempalte|Cut or Copy|field-toField
                                                        args = valData.Split('|');
                                                        if (args.Length < 2)
                                                        {
                                                            AAState.WriteLine("                  ERROR: CASCADE_ATTRIBUTE: Value info does not have enough parameters");
                                                            continue;
                                                        }

                                                        targetLayer = args[0];
                                                        flds = args[1];
                                                        bool bPrompt;
                                                        if (args.Length == 3)
                                                        {
                                                            if (args[2].ToUpper() == "T" || args[2].ToUpper() == "TRUE" || args[2].ToUpper() == "YES")
                                                            {
                                                                bPrompt = true;
                                                            }
                                                            else
                                                            {
                                                                bPrompt = false;
                                                            }

                                                        }
                                                        else
                                                        {
                                                            bPrompt = true;
                                                        }
                                                        pRowCh = inObject as IRowChanges;
                                                        if (pRowCh.get_ValueChanged(intFldIdxs[0]) == false)
                                                        {
                                                            AAState.WriteLine("                  CASCADE_ATTRIBUTE: Target value did not change, skipping");
                                                            continue;
                                                        }

                                                        bool boolFoundAsLayer = true;

                                                        sourceLayer = Globals.FindLayer(ArcMap.Application, args[0].ToString(), ref boolFoundAsLayer) as IFeatureLayer;
                                                        if (sourceLayer == null)
                                                        {
                                                            AAState.WriteLine("                  ERROR: CASCADE_ATTRIBUTE: Target layer was not found");
                                                            continue;
                                                        }
                                                        int intTargFld = -1;
                                                        intTargFld = sourceLayer.FeatureClass.Fields.FindField(flds);
                                                        if (intTargFld == -1)
                                                        {
                                                            intTargFld = sourceLayer.FeatureClass.Fields.FindFieldByAliasName(flds);
                                                            if (intTargFld != -1)
                                                            {
                                                                flds = sourceLayer.FeatureClass.Fields.get_Field(intTargFld).Name;

                                                            }
                                                        }
                                                        if (intTargFld > -1)
                                                        {

                                                            if (pRowCh.get_OriginalValue(intFldIdxs[0]).ToString().Trim() == "")
                                                                continue;
                                                            IQueryFilter pQFilt = new QueryFilterClass();
                                                            if (sourceLayer.FeatureClass.Fields.get_Field(intTargFld).Type == esriFieldType.esriFieldTypeString)
                                                            {
                                                                pQFilt.WhereClause = flds + " = '" + pRowCh.get_OriginalValue(intFldIdxs[0]) + "'";

                                                            }
                                                            else
                                                            {
                                                                pQFilt.WhereClause = flds + " = " + pRowCh.get_OriginalValue(intFldIdxs[0]) + "";

                                                            }

                                                            int featCnt = sourceLayer.FeatureClass.FeatureCount(pQFilt);
                                                            if (featCnt == 0)
                                                            {
                                                                AAState.WriteLine("                  Skipping, no Matching records found");

                                                            }
                                                            else
                                                            {
                                                                string promptLayname;

                                                                promptLayname = Globals.getClassName(sourceLayer);

                                                                if (bPrompt)
                                                                {
                                                                    if (MessageBox.Show("You are about to change " + featCnt + " rows in the " + promptLayname + " Feature Class, proceed?", "Cascade", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                                                    {
                                                                        AAState.WriteLine("                  User accepted prompt");

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  User declined prompt");

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Prompt surpressed");
                                                                }
                                                            }

                                                            IFeatureCursor pCalcCursor = sourceLayer.FeatureClass.Update(pQFilt, false);
                                                            IFeature updateFeat;
                                                            if (ChangeFeatureList == null)
                                                            {
                                                                ChangeFeatureList = new List<IObject>();
                                                            }
                                                            while ((updateFeat = pCalcCursor.NextFeature()) != null)
                                                            {

                                                                updateFeat.set_Value(intTargFld, inObject.get_Value(intFldIdxs[0]));
                                                                ChangeFeatureList.Add(updateFeat);

                                                                if (!trackCancel.Continue())
                                                                {
                                                                    AAState.WriteLine("                     Abort Edit");
                                                                    AAState._editor.AbortOperation();
                                                                    return false;
                                                                }
                                                            }
                                                            updateFeat = null;

                                                            if (pCalcCursor != null)
                                                            {
                                                                Marshal.ReleaseComObject(pCalcCursor);
                                                            }
                                                            pCalcCursor = null;

                                                            pQFilt = null;

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: CASCADE_ATTRIBUTE: Field was not found");
                                                        }

                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: CASCADE_ATTRIBUTE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    sourceLayer = null;

                                                    pRowCh = null;
                                                    AAState.WriteLine("                  Finished: CASCADE_ATTRIBUTE");
                                                }
                                                break;
                                            }

                                        case "COPY_FEATURE":
                                            {
                                                AAState.WriteLine("                  Trying: COPY_FEATURE");
                                                IFeatureLayer pTargetFL;
                                                string[] FldPairs;
                                                string targetValue;
                                                IRowChanges pRowCh = null;
                                                IFeature pNewFeat = null;
                                                try
                                                {

                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        AAState.WriteLine("                     Feature and valueinfo is valid");

                                                        AAState.WriteLine("                     Splitting up value info: " + valData);
                                                        //field name is the field to Check
                                                        //value|Layer|tempalte|Cut or Copy|field-toField
                                                        args = valData.Split('|');
                                                        if (args.Length < 2)
                                                        {
                                                            AAState.WriteLine("                  ERROR: COPY_FEATURE: Value info does not have enough parameters");
                                                            continue;
                                                        }

                                                        targetValue = args[0];

                                                        pRowCh = inObject as IRowChanges;
                                                        if (pRowCh.get_ValueChanged(intFldIdxs[0]) == false)
                                                        {
                                                            AAState.WriteLine("                  COPY_FEATURE: Field listed in the Field Name did not change, skipping");
                                                            continue;
                                                        }
                                                        if (inFeature.get_Value(intFldIdxs[0]).ToString() != targetValue.ToString())
                                                        {
                                                            AAState.WriteLine("                  COPY_FEATURE: Target value did not match listed value, skipping");
                                                            continue;
                                                        }

                                                        bool FCorLayerTarget = true;

                                                        pTargetFL = Globals.FindLayer(ArcMap.Application, args[1].ToString(), ref FCorLayerTarget) as IFeatureLayer;
                                                        if (pTargetFL == null)
                                                        {
                                                            AAState.WriteLine("                  ERROR: COPY_FEATURE: Target layer was not found");
                                                            continue;
                                                        }
                                                        if (Globals.IsEditable(ref pTargetFL, ref AAState._editor) == false)
                                                        {
                                                            AAState.WriteLine("                  ERROR: COPY_FEATURE: Target layer is not editable");
                                                            continue;
                                                        }

                                                        if (pTargetFL.FeatureClass.ShapeType != (inFeature.Class as IFeatureClass).ShapeType)
                                                        {
                                                            AAState.WriteLine("                  ERROR: COPY_FEATURE: Target layer and Source layer are different geometry types");
                                                            continue;
                                                        }

                                                        FldPairs = null;
                                                        //value|Layer|tempalte|Cut or Copy|field-toField

                                                        IEditTemplate pEditTemp = null;
                                                        string sourceAction = "COPY";
                                                        string fldMatching = null;

                                                        switch (args.Length)
                                                        {
                                                            //case 2:

                                                            //    break;
                                                            case 3:
                                                                if (args[2].Trim() != "")
                                                                {
                                                                    pEditTemp = Globals.PromptAndGetEditTemplateGraphic(pTargetFL, args[2].Trim());

                                                                }
                                                                else
                                                                {
                                                                    pEditTemp = null;
                                                                }
                                                                break;
                                                            case 4:
                                                                if (args[2].Trim() != "")
                                                                {

                                                                    pEditTemp = Globals.PromptAndGetEditTemplateGraphic(pTargetFL, args[2].Trim());
                                                                }
                                                                else
                                                                {
                                                                    pEditTemp = null;
                                                                }
                                                                sourceAction = args[3].ToUpper().Trim();

                                                                break;
                                                            case 5:
                                                                if (args[2].Trim() != "")
                                                                {

                                                                    pEditTemp = Globals.PromptAndGetEditTemplateGraphic(pTargetFL, args[2].Trim());
                                                                }
                                                                else
                                                                {
                                                                    pEditTemp = null;
                                                                }
                                                                sourceAction = args[3].ToUpper().Trim();
                                                                fldMatching = args[4].Trim();
                                                                break;
                                                        }

                                                        if (pEditTemp != null)
                                                        {

                                                            pNewFeat = Globals.CreateFeature(inFeature.ShapeCopy, pEditTemp, AAState._editor, ArcMap.Application, false, false, false);

                                                        }
                                                        else
                                                        {
                                                            pNewFeat = Globals.CreateFeature(inFeature.ShapeCopy, pTargetFL, AAState._editor, ArcMap.Application, false, false, false);

                                                        }
                                                        pEditTemp = null;
                                                        if (fldMatching != null)
                                                        {
                                                            if (fldMatching == "")
                                                            {
                                                                FldPairs = new string[] { };
                                                            }
                                                            else
                                                            {
                                                                FldPairs = fldMatching.Split(',');
                                                            }
                                                        }
                                                        else
                                                        {
                                                            FldPairs = new string[] { };

                                                        }

                                                        List<string> targFilds = new List<string>();

                                                        foreach (string strFlpPair in FldPairs)
                                                        {
                                                            string[] fldMatch = strFlpPair.Split('-');
                                                            if (fldMatch.Length != 2)
                                                            {
                                                                AAState.WriteLine("                  ERROR: COPY_FEATURE: Field pairing is not properly defined");
                                                            }
                                                            else
                                                            {
                                                                string strSrcFldName = fldMatch[0];
                                                                string strTarFldName = fldMatch[1];
                                                                int intSrcFldIdx = Globals.GetFieldIndex((inFeature.Class as IFeatureClass).Fields, (strSrcFldName));
                                                                int intTarFldIdx = Globals.GetFieldIndex(pTargetFL.FeatureClass.Fields, strTarFldName);
                                                                if (intSrcFldIdx == -1 || intTarFldIdx == -1)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: COPY_FEATURE: Either the source or target field was not found");
                                                                }
                                                                else
                                                                {
                                                                    targFilds.Add(strTarFldName.ToUpper());

                                                                    try
                                                                    {
                                                                        pNewFeat.set_Value(intTarFldIdx, inFeature.get_Value(intSrcFldIdx));
                                                                    }
                                                                    catch
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: COPY_FEATURE: Setting value: " + strFlpPair);

                                                                    }
                                                                }

                                                            }
                                                        }
                                                        IFields pTarFields = pTargetFL.FeatureClass.Fields;
                                                        IField pTarField = null;
                                                        for (int i = 0; i < pTarFields.FieldCount; i++)
                                                        {
                                                            pTarField = pTarFields.get_Field(i);
                                                            if (pTarField.Type != esriFieldType.esriFieldTypeGlobalID &&
                                                                pTarField.Type != esriFieldType.esriFieldTypeOID &&
                                                                pTarField.Type != esriFieldType.esriFieldTypeGeometry &&
                                                                 pTarField.Name.ToUpper() != "SHAPE_LENGTH" &&
                                                                pTarField.Name.ToUpper() != "SHAPE.LEN" &&
                                                                pTarField.Name.ToUpper() != "SHAPE_AREA" &&
                                                                pTarField.Name.ToUpper() != "SHAPE.AREA")
                                                            {
                                                                if (targFilds.Contains(pTarField.Name.ToUpper()) == false)
                                                                {
                                                                    int fldIdx = inFeature.Fields.FindField(pTarField.Name);
                                                                    if (fldIdx > 0)
                                                                    {
                                                                        try
                                                                        {
                                                                            pNewFeat.set_Value(i, inFeature.get_Value(fldIdx));
                                                                        }
                                                                        catch
                                                                        {
                                                                            AAState.WriteLine("                  WARNING: COPY_FEATURE: Setting value: " + pTarField.Name);

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        pTarFields = null;
                                                        pTarField = null;
                                                        if (NewFeatureList == null)
                                                        {
                                                            NewFeatureList = new List<IObject>();
                                                        }

                                                        NewFeatureList.Add(pNewFeat);

                                                        if (sourceAction == "CUT")
                                                        {
                                                            MessageBox.Show("CUT is not supported at the moment");

                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                     ERROR: Value info was not correct");

                                                    }
                                                }

                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: COPY_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    pTargetFL = null;

                                                    pRowCh = null;
                                                    pNewFeat = null;
                                                    AAState.WriteLine("                  Finished: COPY_FEATURE");
                                                }
                                                break;
                                            }

                                        case "VALIDATE_CONNECTIVITY":
                                            {
                                                AAState.WriteLine("                  Trying: VALIDATE_CONNECTIVITY");

                                                try
                                                {

                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        AAState.WriteLine("                     Feature and valueinfo is valid");

                                                        AAState.WriteLine("                     Checking if feature is in a Geometric Network");
                                                        bool validFeat = false;
                                                        if (inFeature is INetworkFeature)
                                                        {
                                                            AAState.WriteLine("                     Feature is in a Geometric Network");

                                                            AAState.WriteLine("                     Splitting up value info: " + valData);

                                                            args = valData.Split('|');
                                                            int connectionCnt = Globals.getConnectionCount(inFeature);

                                                            foreach (string fldConPair in args)
                                                            {

                                                                string[] fldCon = fldConPair.Split(',');
                                                                if (fldCon.Length == 1)
                                                                {
                                                                    AAState.WriteLine("                     No values for the specified fields");
                                                                    if (Globals.IsNumeric(fldCon[0]))
                                                                    {
                                                                        if (connectionCnt == Convert.ToInt32(fldCon[0]))
                                                                        {
                                                                            AAState.WriteLine("                     Valid Connection Rule Found");
                                                                            validFeat = true;
                                                                            break;

                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                     ERROR: Connection value is not numeric");
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    if (intFldIdxs.Count == 0)
                                                                    {
                                                                        AAState.WriteLine("                     No values for the specified fields");
                                                                        if (fldCon.Length == 2)
                                                                        {
                                                                            if (connectionCnt == Convert.ToInt32(fldCon[1]))
                                                                            {
                                                                                AAState.WriteLine("                     Valid Connection Rule Found");
                                                                                validFeat = true;
                                                                                break;

                                                                            }
                                                                        }
                                                                        if (fldCon.Length > 2)
                                                                        {
                                                                            if (connectionCnt >= Convert.ToInt32(fldCon[1]) && connectionCnt <= Convert.ToInt32(fldCon[2]))
                                                                            {
                                                                                AAState.WriteLine("                     Valid Connection Rule Found");
                                                                                validFeat = true;
                                                                                break;

                                                                            }
                                                                        }

                                                                    }

                                                                    else if (inFeature.get_Value(intFldIdxs[0]).ToString() == fldCon[0])
                                                                    {

                                                                        if (fldCon.Length == 2)
                                                                        {
                                                                            if (connectionCnt == Convert.ToInt32(fldCon[1]))
                                                                            {
                                                                                AAState.WriteLine("                     Valid Connection Rule Found");
                                                                                validFeat = true;
                                                                                break;

                                                                            }
                                                                        }
                                                                        if (fldCon.Length > 2)
                                                                        {
                                                                            if (connectionCnt >= Convert.ToInt32(fldCon[1]) && connectionCnt <= Convert.ToInt32(fldCon[2]))
                                                                            {
                                                                                AAState.WriteLine("                     Valid Connection Rule Found");
                                                                                validFeat = true;
                                                                                break;

                                                                            }
                                                                        }

                                                                    }

                                                                }

                                                            }
                                                            if (validFeat == false)
                                                            {
                                                                AAState.WriteLine("                     Abort Edit");
                                                                AAState._editor.AbortOperation();
                                                                return false;

                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                     ERROR: Feature is not a Geometric Network feature");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                     ERROR: Value info was not correct");

                                                    }
                                                }

                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: VALIDATE_CONNECTIVITY" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: VALIDATE_CONNECTIVITY");
                                                }
                                                break;
                                            }

                                        case "VALIDATE_ATTRIBUTES":
                                            {
                                                AAState.WriteLine("                  Trying: VALIDATE_ATTRIBUTES");

                                                try
                                                {
                                                    if ((valData != null) && (inFeature != null))
                                                    {

                                                        AAState.WriteLine("                     Feature and valueinfo is valid");
                                                        IRowChanges pRowCh = inObject as IRowChanges;
                                                        changed = true;
                                                        if (intFldIdxs != null && intFldIdxs.Count > 0 && mode != "ON_CREATE")
                                                        {
                                                            for (int fldIdx = 0; fldIdx < intFldIdxs.Count; fldIdx++)
                                                            {
                                                                AAState.WriteLine("                     Row to monitor specified");
                                                                changed = pRowCh.get_ValueChanged(intFldIdxs[fldIdx]);
                                                                AAState.WriteLine("                     " + strFldNames[fldIdx] + " changed value was " + changed);
                                                                if (changed)
                                                                    break;
                                                            }

                                                        }
                                                        if (changed)
                                                        {
                                                            args = valData.Split('|');
                                                            args = args[0].Split(',');
                                                            AAState.WriteLine("                     Checking fields to compare: " + args);
                                                            if (args.Length > 0)
                                                            {

                                                                AAState.WriteLine("                     Getting templates for feature class");
                                                                IList<ILayer> pLayList = Globals.FindLayersByClassID(((IMxDocument)ArcMap.Application.Document).FocusMap, inObject.Class.ObjectClassID);
                                                                if (pLayList != null)
                                                                {
                                                                    if (pLayList.Count > 0)
                                                                    {

                                                                        AAState.WriteLine("                     " + pLayList.Count + " Layers found");
                                                                        bool ValidComb = false;

                                                                        foreach (ILayer pLay in pLayList)
                                                                        {
                                                                            AAState.WriteLine("                     Checking " + pLay.Name);
                                                                            if (pLay is IFeatureLayer)
                                                                            {
                                                                                AAState.WriteLine("                     Layer is a featurelayer");

                                                                                AAState.WriteLine("                     Getting Edit Template Manager");
                                                                                IEditTemplateManager pEdTmpManager = Globals.GetEditTemplateManager((IFeatureLayer)pLay);
                                                                                AAState.WriteLine("                     Checking templates");
                                                                                ValidComb = Globals.FeatureIsValidTemplate(pEdTmpManager, inFeature, args);
                                                                                AAState.WriteLine("                     Template Found Status: " + ValidComb.ToString());
                                                                                if (ValidComb == true)
                                                                                    break;

                                                                            }

                                                                        }
                                                                        if (ValidComb == false)
                                                                        {
                                                                            AAState.WriteLine("                     Abort Edit");
                                                                            AAState._editor.AbortOperation();
                                                                            return false;

                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                     WARNING: No layers where found!");

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                     WARNING: No layers where found!");

                                                                }

                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                     Monitored fields where not changed");

                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: VALIDATE_ATTRIBUTES" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: VALIDATE_ATTRIBUTES");
                                                }
                                                break;
                                            }

                                        case "SPLIT_INTERSECTING_FEATURE":
                                            {
                                                AAState.WriteLine("                  Trying: SPLIT_INTERSECTING_FEATURE");

                                                try
                                                {
                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        intersectLayerName = "";
                                                        intersectLayer = null;
                                                        args = valData.Split('|');
                                                        if (args.Length > 0)
                                                        {
                                                            AAState.WriteLine("                  " + args.Length + " Layers listed ");

                                                            for (int i = 0; i < args.Length; i++)
                                                            {

                                                                intersectLayerName = args[i].Trim();
                                                                AAState.WriteLine("                  Searching for " + intersectLayerName);
                                                                boolLayerOrFC = true;
                                                                if (intersectLayerName.Contains("("))
                                                                {
                                                                    string[] tempSplt = intersectLayerName.Split('(');
                                                                    intersectLayerName = tempSplt[0];
                                                                    intersectLayer = Globals.FindLayer(AAState._editor.Map, intersectLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                                    if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                    {
                                                                        boolLayerOrFC = true;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                    {
                                                                        boolLayerOrFC = true;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }
                                                                    else
                                                                    {
                                                                        boolLayerOrFC = true;
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    intersectLayer = Globals.FindLayer(AAState._editor.Map, intersectLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                                }
                                                                if (intersectLayer != null)
                                                                {
                                                                    AAState.WriteLine("                  Layer Found " + intersectLayerName);
                                                                    if (intersectLayer.FeatureClass != null)
                                                                    {
                                                                        AAState.WriteLine("                  Datasource is valid for " + intersectLayerName);
                                                                        double snapTol = Globals.GetXYTolerance(intersectLayer);
                                                                        sFilter = Globals.createSpatialFilter(intersectLayer, inFeature, false);

                                                                        AAState.WriteLine("                  Checking source Geometry Type");

                                                                        AAState.WriteLine("                  Searching " + intersectLayerName + "for intersected feature");

                                                                        pFS = (IFeatureSelection)intersectLayer;
                                                                        if (boolLayerOrFC)
                                                                        {
                                                                            if (pFS.SelectionSet.Count > 0)
                                                                            {
                                                                                pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                                fCursor = cCurs as IFeatureCursor;

                                                                            }
                                                                            else
                                                                            {
                                                                                fCursor = intersectLayer.Search(sFilter, true);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            fCursor = intersectLayer.FeatureClass.Search(sFilter, true);
                                                                        }

                                                                        IFeature intsersectFeature;
                                                                        int idx = 1;
                                                                        while ((intsersectFeature = fCursor.NextFeature()) != null)
                                                                        {
                                                                            if (intsersectFeature.Class != inFeature.Class)
                                                                            {
                                                                                AAState.WriteLine("                  Splitting Intersected Feature number: " + idx);
                                                                                idx++;

                                                                                if (intsersectFeature is INetworkFeature)
                                                                                {
                                                                                    AAState.WriteLine("                  Line to split is a Geometric Network line, this operation is not valid for these types of features");
                                                                                }
                                                                                else
                                                                                {
                                                                                    ISet featset = Globals.splitLineWithPoint(intsersectFeature, inFeature.ShapeCopy as IPoint, snapTol, null, "{0:0.00}", ArcMap.Application);

                                                                                    if (featset != null)
                                                                                    {
                                                                                        AAState.WriteLine("                  Adding split features to array to call the AA ext");

                                                                                        if (featset.Count > 0)
                                                                                        {
                                                                                            if (NewFeatureList == null)
                                                                                            {
                                                                                                NewFeatureList = new List<IObject>();
                                                                                            }
                                                                                            object featobj;
                                                                                            while ((featobj = featset.Next()) != null)
                                                                                            {
                                                                                                IFeature feature = featobj as IFeature;

                                                                                                if (feature != null)
                                                                                                {
                                                                                                    NewFeatureList.Add(feature as IObject);
                                                                                                }
                                                                                                feature = null;
                                                                                            }

                                                                                        }
                                                                                        AAState.WriteLine("                  Split feature " + intersectLayerName + " into " + featset.Count);
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  Split return no features");

                                                                                    }
                                                                                    featset = null;
                                                                                }
                                                                            }
                                                                            if (intsersectFeature != null)
                                                                            {
                                                                                Marshal.ReleaseComObject(intsersectFeature);
                                                                            }

                                                                            else if (intsersectFeature.Class == inFeature.Class && intsersectFeature.OID != inFeature.OID)
                                                                            {
                                                                                AAState.WriteLine("                  Splitting Intersected Feature number: " + idx);
                                                                                idx++;
                                                                                if (intsersectFeature is INetworkFeature)
                                                                                {
                                                                                    AAState.WriteLine("                  Line to split is a Geometric Network line, this operation is not valid for these types of features");
                                                                                }
                                                                                else
                                                                                {
                                                                                    ISet featset = Globals.splitLineWithPoint(intsersectFeature, inFeature.ShapeCopy as IPoint, snapTol, null, "{0:0.00}", ArcMap.Application);

                                                                                    if (featset == null)
                                                                                    {
                                                                                        AAState.WriteLine("                  Error splitting feature, the feature may be a Geometric Network feature");

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  Adding split features to array to call the AA ext");

                                                                                        if (featset.Count > 0)
                                                                                        {
                                                                                            if (NewFeatureList == null)
                                                                                            {
                                                                                                NewFeatureList = new List<IObject>();
                                                                                            }
                                                                                            object featobj;
                                                                                            while ((featobj = featset.Next()) != null)
                                                                                            {
                                                                                                IFeature feature = featobj as IFeature;
                                                                                                if (feature != null)
                                                                                                {
                                                                                                    NewFeatureList.Add(feature as IObject);
                                                                                                }
                                                                                                feature = null;

                                                                                            }

                                                                                        }
                                                                                        AAState.WriteLine("                  Split feature " + intersectLayerName + " into " + featset.Count);
                                                                                    }
                                                                                    featset = null;

                                                                                }
                                                                                if (intsersectFeature != null)
                                                                                {
                                                                                    Marshal.ReleaseComObject(intsersectFeature);
                                                                                }

                                                                            }

                                                                        }
                                                                        intsersectFeature = null;
                                                                    }
                                                                }

                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Warning: Can't find intersecting layer: " + intersectLayerName);
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Unsupported Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: not a feature or no Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: SPLIT_INTERSECTING_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: SPLIT_INTERSECTING_FEATURE");
                                                }
                                                break;
                                            }

                                        case "NEAREST_FEATURE_ATTRIBUTES":
                                            {
                                                AAState.WriteLine("                  Trying NEAREST_FEATURE_ATTRIBUTES");
                                                try
                                                {
                                                    if ((valData != null) && (inFeature != null))
                                                    {
                                                        sourceLayerName = "";
                                                        string[] sourceFieldNames = null;
                                                        string[] destFieldNames = null;
                                                        searchDistance = 0;

                                                        // Parse arguments
                                                        args = valData.Split('|');
                                                        if (args.Length == 3)
                                                        {
                                                            sourceLayerName = args[0].ToString().Trim();
                                                            sourceFieldNames = args[1].ToString().Split(',');
                                                            destFieldNames = args[2].ToString().Split(',');
                                                            AAState.WriteLine("                  WARNING:  search distance as not specified, defaulting to 0");

                                                        }
                                                        else if (args.Length == 4)
                                                        {
                                                            sourceLayerName = args[0].ToString().Trim();
                                                            sourceFieldNames = args[1].ToString().Split(',');
                                                            destFieldNames = args[2].ToString().Split(',');
                                                            Double.TryParse(args[3], out searchDistance);
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR:  the valuemethod is not defined properly for this rule");
                                                            continue;

                                                        }

                                                        if ((sourceFieldNames != null) && (destFieldNames != null) &&
                                                            (sourceFieldNames.Length > 0) && (destFieldNames.Length > 0) &&
                                                            (sourceFieldNames.Length == destFieldNames.Length))
                                                        {
                                                            AAState.WriteLine("                  Looking for layer: " + sourceLayerName);

                                                            boolLayerOrFC = true;
                                                            if (sourceLayerName.Contains("("))
                                                            {
                                                                string[] tempSplt = sourceLayerName.Split('(');
                                                                sourceLayerName = tempSplt[0];
                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                                if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                            }

                                                            else
                                                            {
                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC) as IFeatureLayer;
                                                            }
                                                            if (sourceLayer != null)
                                                            {
                                                                if (sourceLayer.FeatureClass != null)
                                                                {
                                                                    AAState.WriteLine("                  " + sourceLayer.Name + " layer Found: " + sourceLayerName);

                                                                    string missingFieldMess = null;
                                                                    int[] sourceFieldNums = new int[sourceFieldNames.Length];
                                                                    int[] destFieldNums = new int[destFieldNames.Length];
                                                                    AAState.WriteLine("                  Checking Field Mapping");

                                                                    for (int i = 0; i < sourceFieldNums.Length; i++)
                                                                    {
                                                                        int fnum = sourceLayer.FeatureClass.FindField(sourceFieldNames[i].Trim());
                                                                        if (fnum < 0)
                                                                        {
                                                                            missingFieldMess = sourceFieldNames[i].Trim() + " in table " + sourceLayerName;
                                                                            break;
                                                                        }
                                                                        sourceFieldNums[i] = fnum;
                                                                    }
                                                                    if (missingFieldMess == null)
                                                                    {
                                                                        for (int i = 0; i < destFieldNums.Length; i++)
                                                                        {
                                                                            int fnum = inFeature.Fields.FindField(destFieldNames[i].Trim());
                                                                            if (fnum < 0)
                                                                            {
                                                                                missingFieldMess = destFieldNames[i].Trim() + " in table " + tableName;
                                                                                break;
                                                                            }
                                                                            destFieldNums[i] = fnum;
                                                                        }
                                                                    }
                                                                    if (missingFieldMess == null)
                                                                    {
                                                                        AAState.WriteLine("                  Field Mapping verified");

                                                                        // found source and destination fields.

                                                                        if (searchDistance > 0)
                                                                        {
                                                                            sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, searchDistance, false);

                                                                        }
                                                                        else
                                                                        {
                                                                            sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, searchDistance, false);

                                                                        }

                                                                        AAState.WriteLine("                  Searching for Nearest Feature");

                                                                        pFS = (IFeatureSelection)sourceLayer;
                                                                        if (boolLayerOrFC)
                                                                        {
                                                                            if (pFS.SelectionSet.Count > 0)
                                                                            {
                                                                                pFS.SelectionSet.Search(sFilter, false, out cCurs);
                                                                                fCursor = cCurs as IFeatureCursor;

                                                                            }
                                                                            else
                                                                            {
                                                                                fCursor = sourceLayer.Search(sFilter, false);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            fCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                        }

                                                                        sourceFeature = fCursor.NextFeature();
                                                                        nearestFeature = null;

                                                                        proxOp = (IProximityOperator)inFeature.Shape;
                                                                        lastDistance = searchDistance;
                                                                        if (sourceFeature != null)
                                                                        {
                                                                            AAState.WriteLine("                  Features Found, looping for closest");

                                                                            while (sourceFeature != null)
                                                                            {
                                                                                if (sourceFeature.Class != inFeature.Class)
                                                                                {

                                                                                    IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                    pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                    distance = proxOp.ReturnDistance(pTempGeo);
                                                                                    pTempGeo = null;
                                                                                    if (distance <= lastDistance)
                                                                                    {
                                                                                        nearestFeature = sourceFeature;
                                                                                        lastDistance = distance;
                                                                                    }
                                                                                }
                                                                                else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                                {

                                                                                    IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                    pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                    distance = proxOp.ReturnDistance(pTempGeo);
                                                                                    pTempGeo = null;
                                                                                    if (distance <= lastDistance)
                                                                                    {
                                                                                        nearestFeature = sourceFeature;
                                                                                        lastDistance = distance;
                                                                                    }
                                                                                }
                                                                                sourceFeature = fCursor.NextFeature();
                                                                            }
                                                                        }
                                                                        if (nearestFeature != null)
                                                                        {
                                                                            AAState.WriteLine("                  Closest Feature is " + lastDistance + " Away with OID of " + nearestFeature.OID);

                                                                            for (int i = 0; i < sourceFieldNums.Length; i++)
                                                                            {
                                                                                try
                                                                                {
                                                                                    AAState.WriteLine("                  Trying to copy " + sourceFieldNames[i] + " to " + destFieldNames[i]);

                                                                                    inObject.set_Value(destFieldNums[i], nearestFeature.get_Value(sourceFieldNums[i]));
                                                                                }
                                                                                catch
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: copying " + sourceFieldNames[i] + " to " + destFieldNames[i]);

                                                                                }
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  No Feature was found, default fields");

                                                                            for (int i = 0; i < destFieldNums.Length; i++)
                                                                            {
                                                                                IField field = inObject.Fields.get_Field(destFieldNums[i]);
                                                                                object newval = field.DefaultValue;
                                                                                if (newval == null)
                                                                                {
                                                                                    if (field.IsNullable)
                                                                                    {
                                                                                        inObject.set_Value(destFieldNums[i], null);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    inObject.set_Value(destFieldNums[i], newval);
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: Cant find field " + missingFieldMess);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayerName + " data source is not set");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: " + sourceLayerName + " was not found");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Invalid Value Info: " + valData);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Not a feature or missing Value Info");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: NEAREST_FEATURE_ATTRIBUTES" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: NEAREST_FEATURE_ATTRIBUTES");
                                                }
                                                break;
                                            }
                                        case "MINIMUM_LENGTH":
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying MINIMUM_LENGTH");

                                                    double minlength;
                                                    AAState.WriteLine("                  Evaluating Minimum length value");

                                                    if (Double.TryParse(valData, out minlength))
                                                    {
                                                        if (inFeature != null)
                                                        {
                                                            ICurve curve = inFeature.Shape as ICurve;
                                                            if (curve != null)
                                                            {
                                                                if (curve.Length < minlength)
                                                                {
                                                                    String mess = "Line is shorter than " +
                                                                        String.Format("{0:0.00}", minlength) + " " + Globals.GetSpatRefUnitName(inFeature.Shape.SpatialReference, true) +
                                                                        ", aborting edit.";
                                                                    AAState.WriteLine("                  " + mess);

                                                                    MessageBox.Show(mess, "Line too short");
                                                                    AAState._editor.AbortOperation();
                                                                    return false;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR:  Feature is not a Line");

                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  Error MINIMUM_LENGTH \n" + ex.Message);
                                                }
                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished MINIMUM_LENGTH");

                                                }

                                                break;
                                            }
                                        case "LINK_TABLE_ASSET":

                                            try
                                            {
                                                intersectLayerName = "";
                                                intersectTable = null;
                                                intersectLayer = null;
                                                List<string> intersectLayerFieldNameList = new List<string>();
                                                List<int> intersectFieldPosList = new List<int>();
                                                AAState.WriteLine("                  Trying LINK_TABLE_ASSET");
                                                args = valData.Split('|');
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:  // Feature Layer only
                                                        intersectLayerName = args[0].ToString();
                                                        break;
                                                    case 2:  // Feature Layer| Field to copy
                                                        intersectLayerName = args[0].ToString();

                                                        intersectLayerFieldNameList = new List<string>(args[1].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

                                                        break;
                                                    case 3:  // Feature Layer| Field to copy | for future
                                                        intersectLayerName = args[0].ToString();
                                                        intersectLayerFieldNameList = new List<string>(args[1].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

                                                        break;
                                                    default:
                                                        AAState.WriteLine("                  ERROR: Unsupported Value Method: " + valData);
                                                        continue;

                                                }
                                                bool FCorLayerIntersect = true;
                                                intersectLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, intersectLayerName, ref FCorLayerIntersect);
                                                intersectTable = Globals.FindStandAloneTable(AAState._editor.Map, intersectLayerName);

                                                if (intersectLayer != null)
                                                {
                                                    //Find Area Field

                                                    foreach (string intersectLayerFieldName in intersectLayerFieldNameList)
                                                    {

                                                        intersectFieldPos = intersectLayer.FeatureClass.Fields.FindField(intersectLayerFieldName);
                                                        if (intersectFieldPos < 0)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Asset feature Layer Field(" + intersectLayerFieldName + ") not found");
                                                            break;
                                                        }

                                                        else
                                                        {
                                                            intersectFieldPosList.Add(intersectFieldPos);
                                                        }
                                                    }
                                                    intersectLayerSelection = (IFeatureSelection)intersectLayer;
                                                    if (intersectLayerSelection.SelectionSet.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: No assests selected in " + intersectLayerName);

                                                        break;
                                                    }
                                                    if (intersectLayerSelection.SelectionSet.Count > 1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: To many assests are selected in " + intersectLayerName);

                                                        break;
                                                    }

                                                    intersectLayerSelection.SelectionSet.Search(null, true, out cCurs);
                                                }
                                                else if (intersectTable != null)
                                                {
                                                    if (intersectTable.Table == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Asset  Layer(" + intersectLayerName + ") not found");
                                                        break;
                                                    }

                                                    foreach (string intersectLayerFieldName in intersectLayerFieldNameList)
                                                    {

                                                        intersectFieldPos = intersectTable.Table.Fields.FindField(intersectLayerFieldName);
                                                        if (intersectFieldPos < 0)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Asset  Layer Field(" + intersectLayerFieldName + ") not found");
                                                            break;
                                                        }
                                                        else
                                                        {
                                                            intersectFieldPosList.Add(intersectFieldPos);
                                                        }
                                                    }

                                                    intersectTableSelection = (ITableSelection)intersectTable;
                                                    if (intersectTableSelection.SelectionSet.Count == 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: No assests selected in " + intersectLayerName);

                                                        break;
                                                    }
                                                    if (intersectTableSelection.SelectionSet.Count > 1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: To many assests are selected in " + intersectLayerName);

                                                        break;
                                                    }

                                                    intersectTableSelection.SelectionSet.Search(null, true, out cCurs);
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: Asset  Layer(" + intersectLayerName + ") not found");
                                                    break;
                                                }

                                                IRow row;

                                                while ((row = cCurs.NextRow()) != null)
                                                {
                                                    int idx = 0;
                                                    foreach (int fldIdxInt in intersectFieldPosList)
                                                    {
                                                        if (idx >= intFldIdxs.Count)
                                                            continue;

                                                        string val = row.get_Value(fldIdxInt).ToString();
                                                        if (inObject.Fields.get_Field(intFldIdxs[idx]).Type == esriFieldType.esriFieldTypeString)
                                                            inObject.set_Value(intFldIdxs[idx], val);
                                                        else if (inObject.Fields.get_Field(intFldIdxs[idx]).Type == esriFieldType.esriFieldTypeSmallInteger || inObject.Fields.get_Field(intFldIdxs[idx]).Type == esriFieldType.esriFieldTypeInteger)
                                                        {
                                                            if (Globals.IsNumeric(val))
                                                            {
                                                                inObject.set_Value(intFldIdxs[idx], Convert.ToInt32(val));

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Field is a number and Value is not" + val);

                                                            }
                                                        }
                                                        else if (inObject.Fields.get_Field(intFldIdxs[idx]).Type == esriFieldType.esriFieldTypeSingle || inObject.Fields.get_Field(intFldIdxs[idx]).Type == esriFieldType.esriFieldTypeDouble)
                                                        {
                                                            if (Globals.IsNumeric(val))
                                                            {
                                                                inObject.set_Value(intFldIdxs[idx], Convert.ToDouble(val));

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Field is a number and Value is not:" + val);

                                                            }
                                                        }
                                                        else
                                                        {
                                                            inObject.set_Value(intFldIdxs[idx], val);
                                                        }
                                                        idx++;

                                                    }

                                                }
                                                if (row != null)
                                                    Marshal.ReleaseComObject(cCurs);

                                                row = null;

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LINK_TABLE_ASSET" + Environment.NewLine + ex.Message);
                                            }

                                            finally
                                            {
                                                if (cCurs != null)
                                                {
                                                    Marshal.ReleaseComObject(cCurs);
                                                    GC.Collect(300);
                                                    GC.WaitForFullGCComplete();
                                                    cCurs = null;

                                                }
                                                AAState.WriteLine("                  Finished: LINK_TABLE_ASSET");
                                            }
                                            break;

                                        case "GET_ADDRESS_FROM_CENTERLINE":

                                            AAState.WriteLine("                  Trying GET_ADDRESS_FROM_CENTERLINE");
                                            List<IPoint> pPnts = null;
                                            try
                                            {
                                                if ((valData != null) && (inFeature != null))
                                                {
                                                    sourceLayerName = "";
                                                    string[] sourceFieldNames = null;

                                                    searchDistance = 0;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.Length == 2)
                                                    {
                                                        sourceLayerName = args[0].ToString().Trim();
                                                        sourceFieldNames = args[1].ToString().Split(',');
                                                        searchDistance = 2;
                                                        AAState.WriteLine("                  WARNING:  search distance as not specified, defaulting to 0");

                                                    }
                                                    else if (args.Length == 3)
                                                    {
                                                        sourceLayerName = args[0].ToString().Trim();
                                                        sourceFieldNames = args[1].ToString().Split(',');
                                                        Double.TryParse(args[2], out searchDistance);

                                                    }

                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR:  the valuemethod is not defined properly for this rule");
                                                        continue;

                                                    }

                                                    if (sourceFieldNames.Length != 5)
                                                    {
                                                        AAState.WriteLine("                  ERROR:  the valuemethod fields part does not have enough fields listed");
                                                        continue;

                                                    }

                                                    boolLayerOrFC = false;
                                                    if (sourceLayerName.Contains("("))
                                                    {
                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                        sourceLayerName = tempSplt[0];
                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                    }
                                                    pPnts = Globals.GetGeomCenter(inObject as IFeature);
                                                    if (pPnts.Count != 0)
                                                    {

                                                        AddressInfo pRetValu = Globals.GetAddressInfo(ArcMap.Application, pPnts[0] as IPoint, sourceLayerName,
                                                            sourceFieldNames[0].Trim(), sourceFieldNames[1].Trim(), sourceFieldNames[2].Trim(), sourceFieldNames[3].Trim(), sourceFieldNames[4].Trim(), false, searchDistance);
                                                        if (pRetValu != null)
                                                        {
                                                            if (pRetValu.Messages == "")
                                                            {

                                                                bool rightSide = true;
                                                                IPoint pPnt = Globals.GetPointOnLine((inObject as IFeature).Shape as IPoint, pRetValu.StreetGeometry as IPolyline, 400, out rightSide);

                                                                try
                                                                {
                                                                    if (strFldNames.Count == 2)
                                                                    {
                                                                        if (intFldIdxs[0] != -1)
                                                                        {
                                                                            if (rightSide)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRetValu.RightAddress);
                                                                            }
                                                                            else
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRetValu.LeftAddress);
                                                                            }
                                                                        }
                                                                        if (intFldIdxs[1] != -1)
                                                                            inObject.set_Value(intFldIdxs[1], pRetValu.StreetName);

                                                                    }
                                                                    else
                                                                    {
                                                                        if (intFldIdxs[0] != -1)
                                                                        {
                                                                            if (rightSide)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRetValu.RightAddress + " " + pRetValu.StreetName);
                                                                            }
                                                                            else
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRetValu.LeftAddress + " " + pRetValu.StreetName);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Error setting field values, GET_ADDRESS_FROM_CENTERLINE" + Environment.NewLine + ex.Message);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Error getting address info from the centerline: " + pRetValu.Messages);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Error getting address info from the centerline, GET_ADDRESS_FROM_CENTERLINE");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Error getting Location, GET_ADDRESS_FROM_CENTERLINE");
                                                    }

                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GET_ADDRESS_FROM_CENTERLINE" + Environment.NewLine + ex.Message);
                                            }

                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GET_ADDRESS_FROM_CENTERLINE");
                                                pPnts = null;

                                            }

                                            break;

                                        case "GET_ADDRESS_USING_GEOCODER":
                                            {
                                                IReverseGeocoding reverseGeocoding = null;
                                                IAddressGeocoding addressGeocoding = null;
                                                IPoint revGCLoc = null;
                                                IFields matchFields = null;
                                                IField shapeField = null;

                                                IReverseGeocodingProperties reverseGeocodingProperties = null;
                                                IPropertySet addressProperties = null;

                                                IAddressInputs addressInputs = null;
                                                IFields addressFields = null;
                                                object key = null;
                                                object value = null;
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying GET_ADDRESS_USING_GEOCODER");

                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 2)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    AAState.WriteLine("                  Trying to get address locator");
                                                    reverseGeocoding = Globals.OpenLocator(args[0], args[1]);

                                                    if (reverseGeocoding == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Reverse Address not locator found");
                                                        break;
                                                    }
                                                    AAState.WriteLine("                  Reverse Address locator found");
                                                    AAState.WriteLine("                  Retrieving Location to reverse geocode");
                                                    revGCLoc = Globals.GetGeomCenter(inFeature)[0];
                                                    AAState.WriteLine("                  Location retrieved");
                                                    // Create a Point at which to find the address.
                                                    addressGeocoding = (IAddressGeocoding)reverseGeocoding;

                                                    matchFields = addressGeocoding.MatchFields;
                                                    int shpFld = matchFields.FindField("Shape");

                                                    shapeField = matchFields.get_Field(shpFld);
                                                    AAState.WriteLine("                  Setting distance");
                                                    // Set the search tolerance for reverse geocoding.
                                                    reverseGeocodingProperties = (IReverseGeocodingProperties)reverseGeocoding;
                                                    reverseGeocodingProperties.SearchDistance = 100;
                                                    reverseGeocodingProperties.SearchDistanceUnits = esriUnits.esriFeet;
                                                    reverseGeocoding.InitDefaults();

                                                    // Find the address nearest the Point.
                                                    addressProperties = reverseGeocoding.ReverseGeocode(revGCLoc, false);

                                                    // Print the address properties.
                                                    addressInputs = (IAddressInputs)reverseGeocoding;
                                                    addressFields = addressInputs.AddressFields;

                                                    addressProperties.GetAllProperties(out key, out value);

                                                    string tempVal = "";
                                                    for (int i = 0; i < addressFields.FieldCount; i++)
                                                    {
                                                        IField addressField = addressFields.get_Field(i);
                                                        if (tempVal == "")
                                                        {
                                                            tempVal = addressProperties.GetProperty(addressField.Name).ToString();
                                                        }
                                                        else
                                                        {
                                                            tempVal = tempVal + ", " + addressProperties.GetProperty(addressField.Name).ToString();
                                                        }

                                                    }
                                                    inFeature.set_Value(intFldIdxs[0], tempVal);

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: GET_ADDRESS_USING_GEOCODER" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: GET_ADDRESS_USING_GEOCODER");
                                                    reverseGeocoding = null;
                                                    addressGeocoding = null;
                                                    revGCLoc = null;
                                                    matchFields = null;
                                                    shapeField = null;

                                                    reverseGeocodingProperties = null;
                                                    addressProperties = null;

                                                    addressInputs = null;
                                                    addressFields = null;
                                                    key = null;
                                                    value = null;
                                                }
                                                break;

                                            }

                                        case "GET_ADDRESS_USING_ARCGIS_SERVICE":  //ARGS: url

                                            try
                                            {
                                                IPoint revGCLoc = null;
                                                AAState.WriteLine("                  Trying GET_ADDRESS_USING_ARCGIS_SERVICE");
                                                if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                {
                                                    if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                    {
                                                        args = valData.Split('|');
                                                        revGCLoc = Globals.GetGeomCenter(inFeature)[0];
                                                        int wkid = inFeature.Shape.SpatialReference.FactoryCode;
                                                        if (revGCLoc != null)
                                                        {
                                                            //Test for user specified URL
                                                            if (valData.Trim() != "")
                                                            {
                                                                if (args.Length == 2)
                                                                {
                                                                    wkid = Convert.ToInt32(args[1]);
                                                                }
                                                                if (Globals.IsUrl(args[0]))
                                                                {
                                                                    locatorURL = args[0];

                                                                    if (!(locatorURL.EndsWith(reverseGeocodeStr)))
                                                                    {
                                                                        if (!(locatorURL.EndsWith(GeocodeStr)))
                                                                        {
                                                                            if (!(locatorURL.EndsWith("/")))
                                                                            {
                                                                                locatorURL += "/" + GeocodeStr + "/" + reverseGeocodeStr;
                                                                            }
                                                                            else
                                                                            {
                                                                                locatorURL += GeocodeStr + "/" + reverseGeocodeStr;
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            if (!(locatorURL.EndsWith("/")))
                                                                            {
                                                                                locatorURL += "/" + reverseGeocodeStr;
                                                                            }
                                                                            else
                                                                            {
                                                                                locatorURL += reverseGeocodeStr;
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                                //else if (args[0] == "TA_Streets_US_10")
                                                                //{
                                                                //    locatorURL = _agsOnlineLocators + args[0] + GeocodeStr + "/" + reverseGeocodeStr;
                                                                //    //       wkid = 102100;
                                                                //}
                                                                //else if (args[0] == "TA_Address_NA_10" || args[0] == "TA_Address_EU")
                                                                //{
                                                                //    locatorURL = _agsOnlineLocators + args[0] + GeocodeStr + "/" + reverseGeocodeStr;
                                                                //    //    wkid = 4326;
                                                                //}
                                                                ////Default to AGS Online USA geocode service
                                                                //else if (_agsOnlineLocators.Substring(_agsOnlineLocators.LastIndexOf('/', _agsOnlineLocators.Length - 2)).Contains("Locator"))
                                                                //{
                                                                //    locatorURL = _agsOnlineLocators + "TA_Address_NA_10" + GeocodeStr + "/" + reverseGeocodeStr;
                                                                //    //        wkid = 4326;
                                                                //}
                                                                else
                                                                {
                                                                    locatorURL = _agsOnlineLocators + GeocodeStr + "/" + reverseGeocodeStr; ;
                                                                    //     wkid = 4326;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if (_agsOnlineLocators.Substring(_agsOnlineLocators.LastIndexOf('/', _agsOnlineLocators.Length - 2)).Contains(GeocodeStr))
                                                                {
                                                                    locatorURL = _agsOnlineLocators + "/" + reverseGeocodeStr;
                                                                    //      wkid = 4326;
                                                                }
                                                                else
                                                                {
                                                                    _agsOnlineLocators = _agsOnlineLocators + "/" + GeocodeStr;
                                                                    locatorURL = _agsOnlineLocators + "/" + reverseGeocodeStr;
                                                                    // wkid = 4326;
                                                                }
                                                            }

                                                            if (!locatorURL.ToUpper().Contains("/REST/"))
                                                            {
                                                                AAState.WriteLine("                  ERROR: Thre url to the geocoder is not to the rest endpoint");
                                                            }
                                                            else
                                                            {
                                                                //Copy point from this current feature
                                                                _copyPoint = revGCLoc;//inFeature.ShapeCopy as IPoint;

                                                                StreamReader reader = null;
                                                                HttpWebRequest request = null;
                                                                try
                                                                {
                                                                    // Create the web request
                                                                    request = WebRequest.Create(_agsOnlineLocators) as HttpWebRequest;

                                                                    // Get response

                                                                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                                                                    {
                                                                        // Get the response stream
                                                                        reader = new StreamReader(response.GetResponseStream());
                                                                        string resp = reader.ReadToEnd();
                                                                        resp = resp.Substring(resp.IndexOf("Spatial Reference:"));
                                                                        resp = resp.Substring(0, resp.IndexOf("<br/>"));
                                                                        resp = resp.Substring(resp.IndexOf("</b>") + 4);
                                                                        wkid = Convert.ToInt32(resp.Split(' ')[0]);

                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  Error getting service projection information");
                                                                    wkid = 4326;
                                                                }
                                                                finally
                                                                {

                                                                    reader = null;
                                                                    request = null;
                                                                }

                                                                _copyPoint.Project(Globals.CreateSpatRef(wkid));
                                                                //Include location parameters in URL
                                                                string results = Globals.FormatLocationRequest(locatorURL, _copyPoint.X, _copyPoint.Y, 100);
                                                                //Send and receieve the request
                                                                WebRequest req = null;
                                                                WebResponse res = null;

                                                                XmlDictionaryReader xr = null;
                                                                XmlDocument doc = null;
                                                                try
                                                                {
                                                                    req = WebRequest.Create(results);
                                                                    res = req.GetResponse();

                                                                    //Convert response from JSON to XML
                                                                    doc = new XmlDocument();
                                                                    using (Stream s = res.GetResponseStream())
                                                                    {
                                                                        xr = JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max);
                                                                        doc.Load(xr);
                                                                        xr.Close();
                                                                        s.Close();
                                                                        string val = "";

                                                                        for (int h = 0; h < doc.DocumentElement.FirstChild.ChildNodes.Count - 1; h++)
                                                                        {
                                                                            if (doc.DocumentElement.FirstChild.ChildNodes[h].Name.Contains("Match") == false)
                                                                            {
                                                                                if (val == "")
                                                                                {
                                                                                    val = doc.DocumentElement.FirstChild.ChildNodes[h].InnerText;
                                                                                }
                                                                                else
                                                                                {
                                                                                    if (val.EndsWith(","))
                                                                                        val = val + " " + doc.DocumentElement.FirstChild.ChildNodes[h].InnerText;
                                                                                    else
                                                                                        val = val + ", " + doc.DocumentElement.FirstChild.ChildNodes[h].InnerText;

                                                                                }
                                                                            }

                                                                            val = val.Trim();
                                                                        }

                                                                        inFeature.set_Value(intFldIdxs[0], val);

                                                                    }
                                                                }
                                                                catch
                                                                {
                                                                }
                                                                finally
                                                                {
                                                                    req = null;
                                                                    res = null;

                                                                    xr = null;
                                                                    doc = null;
                                                                }

                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Could not get location to Reverse Geocode");
                                                        }
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GET_ADDRESS_USING_ARCGIS_SERVICE: " + ex.Message);
                                            }

                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GET_ADDRESS_USING_ARCGIS_SERVICE");
                                            }
                                            break;
                                        case "TIMESTAMP":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TIMESTAMP");

                                                if (!String.IsNullOrEmpty(valData))
                                                {
                                                    args = valData.Split('|');
                                                    if (args.Length > 0)
                                                    {

                                                        try
                                                        {

                                                            if (fieldObj.Type == esriFieldType.esriFieldTypeDate)
                                                            {
                                                                if (args[0].ToString().ToUpper() == "DATE")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.Date);
                                                                }
                                                                else if (args[0].ToString().Trim() != "")
                                                                {
                                                                    try
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString(args[0]));
                                                                    }
                                                                    catch
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString());
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now);
                                                                }
                                                            }
                                                            else if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                            {
                                                                if (args[0].ToString().ToUpper() == "DATE")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.Date);
                                                                }
                                                                else if (args[0].ToString().ToUpper() == "TIME")
                                                                {

                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString("hh:mm:ss tt"));
                                                                }
                                                                else if (args[0].ToString().ToUpper() == "TIME24")
                                                                {
                                                                    //  ReadOnlyCollection<System.TimeZoneInfo> timeZones = System.TimeZoneInfo.GetSystemTimeZones();
                                                                    //  string s = System.TimeZoneInfo.ConvertTime(DateTime.Now, timeZones[0]).ToString("HH:mm:ss");

                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString("HH:mm:ss"));
                                                                }
                                                                else if (args[0].ToString().ToUpper() == "YEAR")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.Year.ToString());
                                                                }
                                                                else if (args[0].ToString().ToUpper() == "MONTH")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.Month.ToString());
                                                                }
                                                                else if (args[0].ToString().ToUpper() == "DAY")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.DayOfWeek.ToString());
                                                                }
                                                                else if (args[0].ToString().Trim() != "")
                                                                {
                                                                    try
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString(args[0]));
                                                                    }
                                                                    catch
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString());
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString());
                                                                }
                                                            }

                                                        }
                                                        catch
                                                        {
                                                            AAState.WriteLine("                  ERROR: Date/Time Format is invalid");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Value info is empty");
                                                        if (fieldObj.Type == esriFieldType.esriFieldTypeDate)
                                                            inObject.set_Value(intFldIdxs[0], DateTime.Now);
                                                        else if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                            inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString());

                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  Value info is empty");
                                                    if (fieldObj.Type == esriFieldType.esriFieldTypeDate)
                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now);
                                                    else if (fieldObj.Type == esriFieldType.esriFieldTypeString)
                                                        inObject.set_Value(intFldIdxs[0], DateTime.Now.ToString());

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TIMESTAMP " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TIMESTAMP");
                                            }
                                            break;

                                        case "LAST_VALUE":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: LAST_VALUE");
                                                bool CheckForValue = false;
                                                if (!String.IsNullOrEmpty(valData))
                                                {
                                                    args = valData.Split('|');
                                                    if (args.Length > 0)
                                                    {
                                                        if (args[0].ToString().ToUpper() == "TRUE")
                                                        {
                                                            CheckForValue = true;
                                                        }
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  Value info is empty");
                                                }
                                                if (CheckForValue && (inObject.get_Value(intFldIdxs[0]) != null && inObject.get_Value(intFldIdxs[0]) != DBNull.Value))
                                                {

                                                }
                                                else
                                                {
                                                    if (mode == "ON_CREATE")
                                                    {

                                                        lastValue = AAState.lastValueProperties.GetProperty(strFldNames[0]) as LastValueEntry;
                                                        if (lastValue == null)
                                                        {
                                                            if (inObject.get_Value(intFldIdxs[0]) != null)
                                                            {
                                                                if (inObject.get_Value(intFldIdxs[0]) != DBNull.Value)
                                                                {
                                                                    AAState.lastValueProperties.SetProperty(strFldNames[0], inObject.get_Value(intFldIdxs[0]));
                                                                }
                                                            }
                                                        }
                                                        else if (lastValue.Value != null)
                                                        {
                                                            if (lastValue.Value != DBNull.Value)
                                                            {
                                                                inObject.set_Value(intFldIdxs[0], lastValue.Value);

                                                                AAState.WriteLine("                  " + strFldNames[0] + ": " + lastValue.Value);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (inObject.get_Value(intFldIdxs[0]) != null)
                                                            {
                                                                if (inObject.get_Value(intFldIdxs[0]) != DBNull.Value)
                                                                {
                                                                    AAState.lastValueProperties.SetProperty(strFldNames[0], inObject.get_Value(intFldIdxs[0]));
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else if (mode == "ON_CHANGE")
                                                    {
                                                        IRowChanges pRowCh = inObject as IRowChanges;
                                                        changed = pRowCh.get_ValueChanged(intFldIdxs[0]);
                                                        if (!changed)
                                                        {
                                                            lastValue = AAState.lastValueProperties.GetProperty(strFldNames[0]) as LastValueEntry;
                                                            if (lastValue != null)
                                                            {
                                                                if (lastValue.Value != null)
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], lastValue.Value);
                                                                    AAState.WriteLine("                  " + strFldNames[0] + ": " + lastValue.Value);
                                                                }

                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                            catch (Exception ex)
                                            {

                                                AAState.WriteLine("                  ERROR: LAST_VALUE " + ex.Message);

                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LAST_VALUE");
                                            }
                                            break;

                                        case "X_COORDINATE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: X_COORDINATE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {
                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.Shape as IPoint;
                                                        inFeature.set_Value(intFldIdxs[0], _copyPoint.X);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        if (valData.Trim() == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolyline)[0].X);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolyline.FromPoint.X);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolyline.ToPoint.X);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolyline)[0].X);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {

                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;
                                                        if (valData.Trim() == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolygon)[0].X);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolygon.FromPoint.X);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolygon.ToPoint.X);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolygon)[0].X);
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: X_COORDINATE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: X_COORDINATE");
                                            }
                                            break;

                                        case "Y_COORDINATE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: Y_COORDINATE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {
                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.Shape as IPoint;
                                                        inFeature.set_Value(intFldIdxs[0], _copyPoint.Y);
                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolyline)[0].Y);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolyline.FromPoint.Y);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolyline.ToPoint.Y);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolyline)[0].Y);
                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;

                                                        if (valData.Trim() == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolygon)[0].Y);
                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolygon.FromPoint.Y);
                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], _copyPolygon.ToPoint.Y);
                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.GetGeomCenter(_copyPolygon)[0].Y);
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: Y_COORDINATE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: Y_COORDINATE");
                                            }
                                            break;

                                        case "LATITUDE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LATITUDE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {

                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.ShapeCopy as IPoint;
                                                        _copyPoint.Project(AAState._sr1);
                                                        inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPoint.Y.ToString()));

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.ShapeCopy as IPolyline;
                                                        _copyPolyline.Project(AAState._sr1);

                                                        if (valData == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolyline)[0].Y.ToString()));

                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolyline.FromPoint.Y.ToString()));

                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolyline.ToPoint.Y.ToString()));

                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolyline)[0].Y.ToString()));

                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;
                                                        _copyPolygon.Project(AAState._sr1);

                                                        if (valData.Trim() == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolygon)[0].Y.ToString()));

                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolygon.FromPoint.Y.ToString()));

                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolygon.ToPoint.Y.ToString()));

                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolygon)[0].Y.ToString()));

                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  Error: LATITUDE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LATITUDE");
                                            }
                                            break;

                                        case "LONGITUDE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LONGITUDE");
                                                if ((inFeature != null) && (inFeature.Shape != null) && !(inFeature.Shape.IsEmpty))
                                                {

                                                    if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                                                    {
                                                        _copyPoint = inFeature.ShapeCopy as IPoint;
                                                        _copyPoint.Project(AAState._sr1);

                                                        inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]),_copyPoint.X.ToString()));

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                    {
                                                        _copyPolyline = inFeature.Shape as IPolyline;
                                                        _copyPolyline.Project(AAState._sr1);

                                                        if (valData == "")
                                                        {

                                                            inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolyline)[0].X.ToString()));

                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolyline.FromPoint.X.ToString()));

                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolyline.ToPoint.X.ToString()));

                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolyline)[0].X.ToString()));

                                                            }

                                                        }

                                                    }
                                                    else if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                                                    {
                                                        _copyPolygon = inFeature.ShapeCopy as IPolygon;
                                                        _copyPolygon.Project(AAState._sr1);

                                                        if (valData.Trim() == "")
                                                        {
                                                            inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolygon)[0].X.ToString()));

                                                        }
                                                        else
                                                        {
                                                            args = valData.Split('|');
                                                            if (args[0].ToUpper() == "S")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolygon.FromPoint.X.ToString()));

                                                            }
                                                            else if (args[0].ToUpper() == "E")
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), _copyPolygon.ToPoint.X.ToString()));

                                                            }
                                                            else
                                                            {
                                                                inFeature.set_Value(intFldIdxs[0], Globals.FormatValueToFieldLength(inFeature.Fields.get_Field(intFldIdxs[0]), Globals.GetGeomCenter(_copyPolygon)[0].X.ToString()));

                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Unsupported Geometry");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LONGITUDE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LONGITUDE");
                                            }
                                            break;

                                        case "FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: Field");
                                                // verify that field to copy exists

                                                if (!String.IsNullOrEmpty(valData))
                                                {
                                                    args = valData.Split('|');
                                                    fieldCopy = inObject.Fields.FindField(args[0] as string);

                                                    if (fieldCopy > -1)
                                                    {
                                                        bool useDisplayValue = true;
                                                        if (args.Length == 2)
                                                        {
                                                            if (args[1].ToUpper() == "CODE")
                                                                useDisplayValue = false;
                                                        }

                                                        try
                                                        {
                                                            if (useDisplayValue)
                                                            {

                                                                inObject.set_Value(intFldIdxs[0], Globals.GetDomainDisplay(inObject.get_Value(fieldCopy), inObject as IFeature, inObject.Fields.get_Field(fieldCopy)));
                                                                AAState.WriteLine("                  Value set");
                                                            }

                                                            else
                                                            {
                                                                inObject.set_Value(intFldIdxs[0], inObject.get_Value(fieldCopy));
                                                                AAState.WriteLine("                  Value set");
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            AAState.WriteLine("                  ERROR: " + ex.Message);
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  " + valData + " is not found");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: Field: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: Field");
                                            }
                                            break;

                                        //CURRENT_USER
                                        //Value Data options:
                                        //U - windows username only
                                        //W or (blank) - full username including domain i.e. domain\username
                                        //D - database user if available and not dbo
                                        case "CURRENT_USER":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: CURRENT_USER");

                                                lastEditorName = AAState._currentUserInfo.GetCurrentUser(valData, fieldObj.Length);
                                                AAState.WriteLine("                  Usernmae: " + lastEditorName);

                                                if (!String.IsNullOrEmpty(lastEditorName))
                                                {
                                                    inObject.set_Value(intFldIdxs[0], lastEditorName);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: CURRENT_USER: "******"                  Finished: CURRENT_USER");
                                            }
                                            break;

                                        case "JUNCTION_ROTATION":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: JUNCTION_ROTATION");
                                                if ((inFeature != null))
                                                {
                                                    AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolGeographic;
                                                    args = null;
                                                    AAState.rCalc.UseDiameter = false;
                                                    AAState.rCalc.DiameterFieldName = "";
                                                    AAState.rCalc.SpinAngle = 0;

                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length == 0)
                                                        {

                                                            AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolGeographic;
                                                        }
                                                        else if (args.Length == 1)
                                                        {
                                                            if (args[0].Substring(0, 1).ToLower() == "a")
                                                                AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;

                                                        }
                                                        else if (args.Length == 2)
                                                        {
                                                            if (args[0].Substring(0, 1).ToLower() == "a")
                                                                AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                                                            if (Globals.IsNumeric(args[1].ToString()))
                                                                AAState.rCalc.SpinAngle = Convert.ToDouble(args[1]);

                                                        }
                                                        else if (args.Length == 3)
                                                        {
                                                            if (args[0].Substring(0, 1).ToLower() == "a")
                                                                AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                                                            if (Globals.IsNumeric(args[1].ToString()))
                                                                AAState.rCalc.SpinAngle = Convert.ToDouble(args[1]);
                                                            AAState.rCalc.UseDiameter = true;
                                                            AAState.rCalc.DiameterFieldName = args[2].ToString();

                                                        }
                                                        else
                                                        {
                                                            AAState.rCalc.RotationType = esriSymbolRotationType.esriRotateSymbolGeographic;
                                                        }

                                                    }
                                                    AAState.WriteLine("                  " + AAState.rCalc.RotationType.ToString() + " is being used");
                                                    rotationAngle = AAState.rCalc.GetRotationUsingConnectedEdges(inFeature);
                                                    if (rotationAngle == null)
                                                    {
                                                        AAState.WriteLine("                  Rotation Angle not found or errored out");
                                                        continue;
                                                    }

                                                    //Accept optional second argument to provide extra rotation

                                                    if (rotationAngle != -1)
                                                    {
                                                        AAState.WriteLine("                  Rotation Angle set to: " + rotationAngle.ToString());

                                                        inObject.set_Value(intFldIdxs[0], rotationAngle);
                                                        AAState.WriteLine("                  Rotation Angle set");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: JUNCTION_ROTATION \r\n" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: JUNCTION_ROTATION");
                                            }
                                            break;

                                        //For Release: 1.2
                                        //New Dynamic Value Method: Length - stores calculated length of line feature
                                        case "LENGTH":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: LENGTH");
                                                if (inFeature != null)
                                                {
                                                    curve = (ICurve)inFeature.Shape;
                                                    if (curve != null)
                                                    {
                                                        inObject.set_Value(intFldIdxs[0], curve.Length);
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: LENGTH: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: LENGTH");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: SET_MEASURES - stores calculated M values (from 0 to length of line) for line feature
                                        //Value Data options:
                                        //P = Percent - Ms will be zero to 100
                                        //default - Ms will be zero to length of line
                                        case "SET_MEASURES":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: SET_MEASURES");
                                                if (inFeature != null)
                                                {
                                                    curve = inFeature.Shape as ICurve;
                                                    mseg = inFeature.Shape as IMSegmentation;
                                                    if (curve != null && mseg != null)
                                                        if (valData != null && valData != "" && valData.Substring(0, 1).ToUpper() == "P")
                                                            mseg.SetAndInterpolateMsBetween(0, 100);
                                                        else
                                                            mseg.SetAndInterpolateMsBetween(0, curve.Length);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: SET_MEASURES: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: SET_MEASURES");
                                            }
                                            break;
                                        //case "EDGE_INTERSECT_SECOND":
                                        //    try
                                        //    {
                                        //        if (inFeature != null)
                                        //        {
                                        //            netFeat = inFeature as INetworkFeature;
                                        //            if (netFeat != null)
                                        //            {
                                        //                if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                        //                {

                                        //                    iJuncFeat = (IJunctionFeature)netFeat;
                                        //                    // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                        //                    ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                        //                    if (iSJunc == null)
                                        //                        break;
                                        //                    if (iSJunc.EdgeFeatureCount <= 1)
                                        //                        break;
                                        //                    iEdgeFeat = iSJunc.get_EdgeFeature(1);

                                        //                    // verify that field (in junction) to copy exists

                                        //                    IRow pRow = iEdgeFeat as IRow;

                                        //                    juncField = pRow.Fields.FindField(valData as string);
                                        //                    if (juncField > -1)
                                        //                    {
                                        //                        inObject.set_Value(intFldIdxs[0], pRow.get_Value(juncField));
                                        //                    }
                                        //                }
                                        //            }
                                        //        }
                                        //    }
                                        //    catch
                                        //    {
                                        //    }
                                        //    break;
                                        //case "EDGE_INTERSECT_FIRST":
                                        //    try
                                        //    {
                                        //        if (inFeature != null)
                                        //        {
                                        //            netFeat = inFeature as INetworkFeature;
                                        //            if (netFeat != null)
                                        //            {
                                        //                if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                        //                {

                                        //                    iJuncFeat = (IJunctionFeature)netFeat;
                                        //                    // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                        //                    ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                        //                    if (iSJunc == null)
                                        //                        break;
                                        //                    if (iSJunc.EdgeFeatureCount <= 0)
                                        //                        break;
                                        //                    iEdgeFeat = iSJunc.get_EdgeFeature(0);

                                        //                    IRow pRow = iEdgeFeat as IRow;

                                        //                    juncField = pRow.Fields.FindField(valData as string);
                                        //                    if (juncField > -1)
                                        //                    {
                                        //                        inObject.set_Value(intFldIdxs[0], pRow.get_Value(juncField));
                                        //                    }
                                        //                }
                                        //            }
                                        //        }
                                        //    }
                                        //    catch
                                        //    {
                                        //    }
                                        //    break;

                                        //Release: 2.0
                                        //New Dynamic Value Method: TO_EDGE_FIELD transfers a field value from a connected egde feature to a junction feature
                                        //Takes value from the frist edge whose "TO" point connects with this junction
                                        case "TO_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TO_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            string netField = "";
                                                            string netRestrictFC = "";
                                                            string netRestrictField = "";
                                                            string netRestrictValue = "";
                                                            args = valData.Split('|');
                                                            switch (args.GetLength(0))
                                                            {
                                                                case 1:  // sequenceColumnName only
                                                                    netField = args[0].ToString().Trim();
                                                                    break;
                                                                case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    break;
                                                                case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    break;
                                                                case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    netRestrictValue = args[3].ToString().Trim();
                                                                    break;
                                                                default: break;
                                                            }

                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {

                                                                        if (netRestrictFC != "")
                                                                        {
                                                                            string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                            AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                            if (strClsName != netRestrictFC)
                                                                            {
                                                                                AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                continue;
                                                                            }
                                                                            AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                            if (netRestrictField != "" && netRestrictValue != "")
                                                                            {
                                                                                int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                if (intTmpFld > -1)
                                                                                {
                                                                                    //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                    if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                    {
                                                                                        AAState.WriteLine("                  Values Match");
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  Values dont match Match");
                                                                                        continue;

                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Missing Field restriction and value info");
                                                                            }
                                                                        }

                                                                        iJuncFeat = (IJunctionFeature)iEdgeFeat.FromJunctionFeature;
                                                                        if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                        {
                                                                            IRow pRow = iEdgeFeat as IRow;

                                                                            // verify that field (in junction) to copy exists
                                                                            juncField = Globals.GetFieldIndex(pRow.Fields, netField);

                                                                            if (juncField > -1)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRow.get_Value(juncField));
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  " + netField + " field not found in edge");
                                                                            }
                                                                            pRow = null;
                                                                            break;

                                                                        }
                                                                    }
                                                                    catch
                                                                    {
                                                                        AAState.WriteLine("                  error ");
                                                                    }

                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }
                                                            iSJunc = null;
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_FIELD");
                                            }
                                            break;

                                        //Release: 2.0
                                        //New Dynamic Value Method: FROM_EDGE_FIELD transfers a field value from a connected egde feature to a junction feature
                                        //Takes value from the frist edge whose "FROM" point connects with this junction
                                        case "FROM_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FROM_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            string netField = "";
                                                            string netRestrictFC = "";
                                                            string netRestrictField = "";
                                                            string netRestrictValue = "";
                                                            args = valData.Split('|');
                                                            switch (args.GetLength(0))
                                                            {
                                                                case 1:  // sequenceColumnName only
                                                                    netField = args[0].ToString().Trim();
                                                                    break;
                                                                case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    break;
                                                                case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    break;
                                                                case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    netRestrictValue = args[3].ToString().Trim();
                                                                    break;
                                                                default: break;
                                                            }

                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {
                                                                        if (netRestrictFC != "")
                                                                        {
                                                                            string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                            AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                            if (strClsName != netRestrictFC)
                                                                            {
                                                                                AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                continue;
                                                                            }
                                                                            AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                            if (netRestrictField != "" && netRestrictValue != "")
                                                                            {
                                                                                int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                if (intTmpFld > -1)
                                                                                {
                                                                                    //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                    if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                    {
                                                                                        AAState.WriteLine("                  Values Match");
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  Values dont match Match");
                                                                                        continue;

                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Missing Field restriction and value info");
                                                                            }
                                                                        }

                                                                        iJuncFeat = iEdgeFeat.ToJunctionFeature;
                                                                        if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                        {
                                                                            IRow pRow = iEdgeFeat as IRow;

                                                                            // verify that field (in junction) to copy exists
                                                                            juncField = Globals.GetFieldIndex(pRow.Fields, netField);

                                                                            if (juncField > -1)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], pRow.get_Value(juncField));
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  " + iSJunc + " field not found");
                                                                            }
                                                                            pRow = null;

                                                                            break;

                                                                        }
                                                                    }
                                                                    catch
                                                                    {
                                                                        AAState.WriteLine("                  error ");
                                                                    }

                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }
                                                            iSJunc = null;
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FROM_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FROM_EDGE_FIELD");
                                            }
                                            break;

                                        case "TO_EDGE_STATS":
                                            try
                                            {
                                                if (valData == null) break;
                                                args = valData.Split('|');
                                                string statType = "MAX";
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:
                                                        sourceFieldName = args[0].ToString();
                                                        break;
                                                    case 2:
                                                        sourceFieldName = args[0].ToString();
                                                        statType = args[1].ToString();
                                                        break;

                                                    default: break;
                                                }

                                                AAState.WriteLine("                  Trying: TO_EDGE_STATS");

                                                int AverageCount = 0;
                                                double result = -999999.1;
                                                string textRes = "";
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        AAState.WriteLine("                  Feature is a network feature");
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            AAState.WriteLine("                  Feature is a junction feature");
                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);

                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {
                                                                        AAState.WriteLine("                  Checking if Edge is From or To");

                                                                        iJuncFeat = iEdgeFeat.FromJunctionFeature;

                                                                        if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                        {
                                                                            AAState.WriteLine("                  Edge is a To-Edge");

                                                                            IRow pRow = iEdgeFeat as IRow;

                                                                            // verify that field (in junction) to copy exists
                                                                            AAState.WriteLine("                  Getting Field From To-Edge");
                                                                            juncField = pRow.Fields.FindField(sourceFieldName);
                                                                            string test = pRow.get_Value(juncField).ToString();
                                                                            if (Globals.IsNumeric(test))
                                                                            {

                                                                                double valToTest = Convert.ToDouble(test);
                                                                                if (result == -999999.1)
                                                                                {
                                                                                    result = valToTest;

                                                                                }
                                                                                else
                                                                                {
                                                                                    switch (statType.ToUpper())
                                                                                    {
                                                                                        case "MAX":
                                                                                            if (result < valToTest)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            break;
                                                                                        case "MIN":
                                                                                            if (result > valToTest)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            break;
                                                                                        case "SUM":
                                                                                            result += valToTest;

                                                                                            break;
                                                                                        case "AVERAGE":
                                                                                            result += valToTest;
                                                                                            AverageCount++;
                                                                                            break;
                                                                                        case "MEAN":
                                                                                            result += valToTest;
                                                                                            AverageCount++;

                                                                                            break;
                                                                                        case "CONCAT":
                                                                                            if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                            {
                                                                                            }
                                                                                            else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                            {
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                if (textRes == "")
                                                                                                {
                                                                                                    textRes += valToTest.ToString();
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    textRes += ConcatDelim + valToTest.ToString();
                                                                                                }
                                                                                            }

                                                                                            break;
                                                                                        default:
                                                                                            AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                            break;
                                                                                    }

                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                switch (statType.ToUpper())
                                                                                {

                                                                                    case "CONCAT":
                                                                                        if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                        {
                                                                                        }
                                                                                        else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                        {
                                                                                        }
                                                                                        else
                                                                                        {

                                                                                            if (textRes == "")
                                                                                            {
                                                                                                textRes += test;
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                textRes += ConcatDelim + test;
                                                                                            }
                                                                                        }

                                                                                        break;
                                                                                    default:
                                                                                        AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                        break;
                                                                                }

                                                                            }

                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Checking if Edge is From Edge, skipping");

                                                                        }
                                                                    }
                                                                    catch
                                                                    {
                                                                    }
                                                                }//end loop
                                                                try
                                                                {
                                                                    if (textRes != "")
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], textRes);
                                                                    }
                                                                    else if (result != -999999.1)
                                                                    {
                                                                        if (AverageCount != 0)
                                                                        {
                                                                            result = result / AverageCount;
                                                                        }
                                                                        inObject.set_Value(intFldIdxs[0], result);

                                                                    }
                                                                    else
                                                                    {
                                                                        IField field = inObject.Fields.get_Field(intFldIdxs[0]);
                                                                        object newval = field.DefaultValue;
                                                                        if (newval == null)
                                                                        {
                                                                            if (field.IsNullable)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], null);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[0], newval);
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_STATS");
                                            }
                                            break;

                                        case "FROM_EDGE_STATS":
                                            try
                                            {
                                                if (valData == null) break;
                                                args = valData.Split('|');
                                                string statType = "MAX";
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:
                                                        sourceFieldName = args[0].ToString();
                                                        break;
                                                    case 2:
                                                        sourceFieldName = args[0].ToString();
                                                        statType = args[1].ToString();
                                                        break;

                                                    default: break;
                                                }

                                                AAState.WriteLine("                  Trying: FROM_EDGE_STATS");

                                                int AverageCount = 0;
                                                double result = -999999.1;
                                                string textRes = "";
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        AAState.WriteLine("                  Feature is a network feature");
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            AAState.WriteLine("                  Feature is a junction feature");
                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);

                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {
                                                                        AAState.WriteLine("                  Checking if Edge is From or To");

                                                                        iJuncFeat = iEdgeFeat.ToJunctionFeature;

                                                                        if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                        {
                                                                            AAState.WriteLine("                  Edge is a From-Edge");

                                                                            IRow pRow = iEdgeFeat as IRow;

                                                                            // verify that field (in junction) to copy exists
                                                                            AAState.WriteLine("                  Getting Field From From-Edge");
                                                                            juncField = pRow.Fields.FindField(sourceFieldName);
                                                                            string test = pRow.get_Value(juncField).ToString();
                                                                            if (Globals.IsNumeric(test))
                                                                            {

                                                                                double valToTest = Convert.ToDouble(test);
                                                                                if (result == -999999.1)
                                                                                {
                                                                                    result = valToTest;

                                                                                }
                                                                                else
                                                                                {
                                                                                    switch (statType.ToUpper())
                                                                                    {
                                                                                        case "MAX":
                                                                                            if (result < valToTest)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            break;
                                                                                        case "MIN":
                                                                                            if (result > valToTest)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            break;
                                                                                        case "SUM":
                                                                                            result += valToTest;

                                                                                            break;
                                                                                        case "AVERAGE":
                                                                                            result += valToTest;
                                                                                            AverageCount++;
                                                                                            break;
                                                                                        case "MEAN":
                                                                                            result += valToTest;
                                                                                            AverageCount++;

                                                                                            break;
                                                                                        case "CONCAT":
                                                                                            if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                            {
                                                                                            }
                                                                                            else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                            {
                                                                                            }
                                                                                            else
                                                                                            {

                                                                                                if (textRes == "")
                                                                                                {
                                                                                                    textRes += valToTest.ToString();
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    textRes += ConcatDelim + valToTest.ToString();
                                                                                                }

                                                                                            }

                                                                                            break;
                                                                                        default:
                                                                                            AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                            break;
                                                                                    }

                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                switch (statType.ToUpper())
                                                                                {

                                                                                    case "CONCAT":
                                                                                        if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                        {
                                                                                        }
                                                                                        else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                        {
                                                                                        }
                                                                                        else
                                                                                        {

                                                                                            if (textRes == "")
                                                                                            {
                                                                                                textRes += test;
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                textRes += ConcatDelim + test;
                                                                                            }

                                                                                        }

                                                                                        break;
                                                                                    default:
                                                                                        AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                        break;
                                                                                }

                                                                            }

                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Checking if Edge is To Edge, skipping");

                                                                        }
                                                                    }
                                                                    catch
                                                                    {
                                                                    }
                                                                }//end loop
                                                                try
                                                                {
                                                                    if (textRes != "")
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], textRes);
                                                                    }
                                                                    else if (result != -999999.1)
                                                                    {
                                                                        if (AverageCount != 0)
                                                                        {
                                                                            result = result / AverageCount;
                                                                        }
                                                                        inObject.set_Value(intFldIdxs[0], result);

                                                                    }
                                                                    else
                                                                    {
                                                                        IField field = inObject.Fields.get_Field(intFldIdxs[0]);
                                                                        object newval = field.DefaultValue;
                                                                        if (newval == null)
                                                                        {
                                                                            if (field.IsNullable)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], null);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[0], newval);
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_STATS");
                                            }
                                            break;

                                        case "EDGE_STATS":
                                            try
                                            {
                                                if (valData == null) break;
                                                args = valData.Split('|');
                                                string statType = "MAX";
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:
                                                        sourceFieldName = args[0].ToString();
                                                        break;
                                                    case 2:
                                                        sourceFieldName = args[0].ToString();
                                                        statType = args[1].ToString();
                                                        break;

                                                    default: break;
                                                }

                                                AAState.WriteLine("                  Trying: EDGE_STATS");

                                                int AverageCount = 0;
                                                double result = -999999.1;
                                                string textRes = "";
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        AAState.WriteLine("                  Feature is a network feature");
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            AAState.WriteLine("                  Feature is a junction feature");
                                                            iJuncFeat = (IJunctionFeature)netFeat;
                                                            // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {
                                                                    AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);

                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {

                                                                        IRow pRow = iEdgeFeat as IRow;

                                                                        // verify that field (in junction) to copy exists
                                                                        AAState.WriteLine("                  Getting Field From Edge");
                                                                        juncField = pRow.Fields.FindField(sourceFieldName);
                                                                        string test = pRow.get_Value(juncField).ToString();
                                                                        if (Globals.IsNumeric(test))
                                                                        {

                                                                            double valToTest = Convert.ToDouble(test);
                                                                            if (result == -999999.1)
                                                                            {
                                                                                result = valToTest;

                                                                            }
                                                                            else
                                                                            {
                                                                                switch (statType.ToUpper())
                                                                                {
                                                                                    case "MAX":
                                                                                        if (result < valToTest)
                                                                                        {
                                                                                            result = valToTest;

                                                                                        }
                                                                                        break;
                                                                                    case "MIN":
                                                                                        if (result > valToTest)
                                                                                        {
                                                                                            result = valToTest;

                                                                                        }
                                                                                        break;
                                                                                    case "SUM":
                                                                                        result += valToTest;

                                                                                        break;
                                                                                    case "AVERAGE":
                                                                                        result += valToTest;
                                                                                        AverageCount++;
                                                                                        break;
                                                                                    case "MEAN":
                                                                                        result += valToTest;
                                                                                        AverageCount++;

                                                                                        break;
                                                                                    case "CONCAT":
                                                                                        if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                        {
                                                                                        }
                                                                                        else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                        {
                                                                                        }
                                                                                        else
                                                                                        {

                                                                                            if (textRes == "")
                                                                                            {
                                                                                                textRes += valToTest.ToString();
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                textRes += ConcatDelim + valToTest.ToString();
                                                                                            }

                                                                                        }

                                                                                        break;
                                                                                    default:
                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                        break;
                                                                                }

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            switch (statType.ToUpper())
                                                                            {

                                                                                case "CONCAT":
                                                                                    if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                    {
                                                                                    }
                                                                                    else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                    {
                                                                                    }
                                                                                    else
                                                                                    {

                                                                                        if (textRes == "")
                                                                                        {
                                                                                            textRes += test;
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            textRes += ConcatDelim + test;
                                                                                        }
                                                                                    }

                                                                                    break;
                                                                                default:
                                                                                    AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                    AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                    break;
                                                                            }

                                                                        }

                                                                    }
                                                                    catch
                                                                    {
                                                                    }
                                                                }//end loop
                                                                try
                                                                {
                                                                    if (textRes != "")
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], textRes);
                                                                    }
                                                                    else if (result != -999999.1)
                                                                    {
                                                                        if (AverageCount != 0)
                                                                        {
                                                                            result = result / AverageCount;
                                                                        }
                                                                        inObject.set_Value(intFldIdxs[0], result);

                                                                    }
                                                                    else
                                                                    {
                                                                        IField field = inObject.Fields.get_Field(intFldIdxs[0]);
                                                                        object newval = field.DefaultValue;
                                                                        if (newval == null)
                                                                        {
                                                                            if (field.IsNullable)
                                                                            {
                                                                                inObject.set_Value(intFldIdxs[0], null);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[0], newval);
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_STATS");
                                            }
                                            break;
                                        case "TO_EDGE_MULTI_FIELD_INTERSECT":
                                            try
                                            {
                                                if (valData == null) break;

                                                sourceFieldName = "";
                                                sourceField = -1;
                                                found = false;
                                                //LayerToIntersect|Field To Elevate
                                                // Parse arguments
                                                args = valData.Split('|');
                                                int popFldIdx = 0;
                                                if (args.GetLength(0) >= 2)
                                                {
                                                    AAState.WriteLine("                  Parsing Valueinfo");

                                                    sourceFieldName = args[0].ToString();
                                                    string[] fieldsToPop = args[1].ToString().Split(',');

                                                    AAState.WriteLine("                  Trying: TO_EDGE_MULTI_FIELD_INTERSECT");

                                                    if (inFeature != null)
                                                    {
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            AAState.WriteLine("                  Feature is a network feature");
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                AAState.WriteLine("                  Feature is a junction feature");
                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);

                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {
                                                                            AAState.WriteLine("                  Checking if Edge is From or To");

                                                                            iJuncFeat = iEdgeFeat.FromJunctionFeature;

                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {
                                                                                AAState.WriteLine("                  Edge is a To-Edge");

                                                                                IRow pRow = iEdgeFeat as IRow;

                                                                                // verify that field (in junction) to copy exists
                                                                                AAState.WriteLine("                  Getting Field From To-Edge");
                                                                                juncField = pRow.Fields.FindField(sourceFieldName);
                                                                                string test = pRow.get_Value(juncField).ToString();
                                                                                if (fieldsToPop.Length == popFldIdx)
                                                                                    break;

                                                                                int tempFieldNum = inObject.Fields.FindField(fieldsToPop[popFldIdx]);

                                                                                if (tempFieldNum > -1)
                                                                                {
                                                                                    inObject.set_Value(tempFieldNum, test);
                                                                                    popFldIdx++;
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Checking if Edge is From Edge, skipping");

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                        }
                                                                    }//end loop

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_STATS");
                                            }
                                            break;
                                        case "FROM_EDGE_MULTI_FIELD_INTERSECT":
                                            try
                                            {
                                                if (valData == null) break;
                                                sourceFieldName = "";
                                                sourceField = -1;
                                                found = false;
                                                //LayerToIntersect|Field To Elevate
                                                // Parse arguments
                                                args = valData.Split('|');
                                                int popFldIdx = 0;
                                                if (args.GetLength(0) >= 2)
                                                {
                                                    AAState.WriteLine("                  Parsing Valueinfo");

                                                    sourceFieldName = args[0].ToString();
                                                    string[] fieldsToPop = args[1].ToString().Split(',');

                                                    AAState.WriteLine("                  Trying: FROM_EDGE_MULTI_FIELD_INTERSECT");

                                                    if (inFeature != null)
                                                    {
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            AAState.WriteLine("                  Feature is a network feature");
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                AAState.WriteLine("                  Feature is a junction feature");
                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);

                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {
                                                                            AAState.WriteLine("                  Checking if Edge is From or To");

                                                                            iJuncFeat = iEdgeFeat.ToJunctionFeature;

                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {
                                                                                AAState.WriteLine("                  Edge is a From-Edge");

                                                                                IRow pRow = iEdgeFeat as IRow;

                                                                                // verify that field (in junction) to copy exists
                                                                                AAState.WriteLine("                  Getting Field From From-Edge");
                                                                                juncField = pRow.Fields.FindField(sourceFieldName);
                                                                                string test = pRow.get_Value(juncField).ToString();
                                                                                if (fieldsToPop.Length == popFldIdx)
                                                                                    break;

                                                                                int tempFieldNum = inObject.Fields.FindField(fieldsToPop[popFldIdx]);

                                                                                if (tempFieldNum > -1)
                                                                                {
                                                                                    inObject.set_Value(tempFieldNum, test);
                                                                                    popFldIdx++;
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Checking if Edge is To Edge, skipping");

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                        }
                                                                    }//end loop

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_EDGE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_EDGE_STATS");
                                            }
                                            break;

                                        case "FROM_JUNCTION_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FROM_JUNCTION_FIELD");
                                                if (valData == null)
                                                {
                                                    AAState.WriteLine("                  Value info is null");
                                                    break;
                                                }
                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                        {
                                                            string netField = "";
                                                            string netRestrictFC = "";
                                                            string netRestrictField = "";
                                                            string netRestrictValue = "";
                                                            args = valData.Split('|');
                                                            switch (args.GetLength(0))
                                                            {
                                                                case 1:  // sequenceColumnName only
                                                                    netField = args[0].ToString().Trim();
                                                                    break;
                                                                case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    break;
                                                                case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    break;
                                                                case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    netRestrictValue = args[3].ToString().Trim();
                                                                    break;
                                                                default: break;
                                                            }

                                                            iEdgeFeat = (IEdgeFeature)netFeat;
                                                            iJuncFeat = iEdgeFeat.FromJunctionFeature;
                                                            if (netRestrictFC != "")
                                                            {
                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                if (strClsName != netRestrictFC)
                                                                {
                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                    break;
                                                                }
                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                {
                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                    if (intTmpFld > -1)
                                                                    {
                                                                        if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                        {
                                                                            AAState.WriteLine("                  Values Match");
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                            break;

                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                }
                                                            }
                                                            // verify that field (in junction) to copy exists
                                                            juncField = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netField);
                                                            if (juncField > -1)
                                                            {
                                                                inObject.set_Value(intFldIdxs[0], ((IFeature)iJuncFeat).get_Value(juncField));
                                                            }
                                                            else
                                                                AAState.WriteLine("                  " + netField + " field not found");
                                                        }
                                                        else
                                                            AAState.WriteLine("                  not an edge feature");
                                                    }
                                                    else
                                                        AAState.WriteLine("                  Not a network feature");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FROM_JUNCTION_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FROM_JUNCTION_FIELD");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: TO_JUNCTION_FIELD transfers a field value from a junction connected at terminal end of a line feature
                                        case "TO_JUNCTION_FIELD":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: TO_JUNCTION_FIELD");
                                                if (valData == null)
                                                {
                                                    AAState.WriteLine("                  Value info is null");
                                                    break;
                                                }
                                                if (inFeature != null)
                                                {

                                                    netFeat = inFeature as INetworkFeature;
                                                    if (netFeat != null)
                                                    {
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                        {

                                                            string netField = "";
                                                            string netRestrictFC = "";
                                                            string netRestrictField = "";
                                                            string netRestrictValue = "";
                                                            args = valData.Split('|');
                                                            switch (args.GetLength(0))
                                                            {
                                                                case 1:  // sequenceColumnName only
                                                                    netField = args[0].ToString().Trim();
                                                                    break;
                                                                case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    break;
                                                                case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    break;
                                                                case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                    netField = args[0].ToString().Trim();
                                                                    netRestrictFC = args[1].ToString().Trim();
                                                                    netRestrictField = args[2].ToString().Trim();
                                                                    netRestrictValue = args[3].ToString().Trim();
                                                                    break;
                                                                default: break;
                                                            }

                                                            iEdgeFeat = (IEdgeFeature)netFeat;
                                                            iJuncFeat = iEdgeFeat.ToJunctionFeature;

                                                            if (netRestrictFC != "")
                                                            {
                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                if (strClsName != netRestrictFC)
                                                                {
                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                    break;
                                                                }
                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                {
                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                    if (intTmpFld > -1)
                                                                    {
                                                                        if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                        {
                                                                            AAState.WriteLine("                  Values Match");
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                            break;

                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                }
                                                            }
                                                            // verify that field (in junction) to copy exists
                                                            juncField = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netField);

                                                            //juncField = ((IFeature)iJuncFeat).Fields.FindField(valData as string);
                                                            if (juncField > -1)
                                                            {
                                                                inObject.set_Value(intFldIdxs[0], ((IFeature)iJuncFeat).get_Value(juncField));
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  " + netField + " field not found");
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an edge feature");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  not an Geometric Network feature");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TO_JUNCTION_FIELD:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TO_JUNCTION_FIELD");
                                            }
                                            break;
                                        case "UPDATE_TO_JUNCTION_FIELD":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: UPDATE_TO_JUNCTION_FIELD");
                                                IRowChanges pRowCh = null;

                                                pRowCh = inObject as IRowChanges;

                                                if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                {

                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    if (inFeature != null)
                                                    {

                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                            {

                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iEdgeFeat = (IEdgeFeature)netFeat;
                                                                iJuncFeat = iEdgeFeat.ToJunctionFeature;

                                                                if (netRestrictFC != "")
                                                                {
                                                                    string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                    AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                    if (strClsName != netRestrictFC)
                                                                    {
                                                                        AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                        break;
                                                                    }
                                                                    AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                    if (netRestrictField != "" && netRestrictValue != "")
                                                                    {
                                                                        int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                        if (intTmpFld > -1)
                                                                        {
                                                                            if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                            {
                                                                                AAState.WriteLine("                  Values Match");
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Values dont match Match");
                                                                                break;

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Missing Field restriction and value info");
                                                                    }
                                                                }
                                                                // verify that field (in junction) to copy exists
                                                                juncField = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netField);

                                                                //juncField = ((IFeature)iJuncFeat).Fields.FindField(valData as string);
                                                                if (juncField > -1)
                                                                {
                                                                    if (ChangeFeatureList == null)
                                                                    {
                                                                        ChangeFeatureList = new List<IObject>();
                                                                    }
                                                                    ((IFeature)iJuncFeat).set_Value(juncField, inObject.get_Value(intFldIdxs[0]));
                                                                    ChangeFeatureList.Add(((IFeature)iJuncFeat));

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  " + netField + " field not found");
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an edge feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an Geometric Network feature");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  field was not changed");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: UPDATE_TO_JUNCTION_FIELD:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: UPDATE_TO_JUNCTION_FIELD");
                                            }
                                            break;
                                        case "UPDATE_FROM_JUNCTION_FIELD":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: UPDATE_FROM_JUNCTION_FIELD");
                                                IRowChanges pRowCh = null;

                                                pRowCh = inObject as IRowChanges;

                                                if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                {

                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    if (inFeature != null)
                                                    {

                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                            {

                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iEdgeFeat = (IEdgeFeature)netFeat;
                                                                iJuncFeat = iEdgeFeat.FromJunctionFeature;

                                                                if (netRestrictFC != "")
                                                                {
                                                                    string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                    AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                    if (strClsName != netRestrictFC)
                                                                    {
                                                                        AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                        break;
                                                                    }
                                                                    AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                    if (netRestrictField != "" && netRestrictValue != "")
                                                                    {
                                                                        int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                        if (intTmpFld > -1)
                                                                        {
                                                                            if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                            {
                                                                                AAState.WriteLine("                  Values Match");
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Values dont match Match");
                                                                                break;

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Missing Field restriction and value info");
                                                                    }
                                                                }
                                                                // verify that field (in junction) to copy exists
                                                                juncField = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netField);

                                                                //juncField = ((IFeature)iJuncFeat).Fields.FindField(valData as string);
                                                                if (juncField > -1)
                                                                {
                                                                    if (ChangeFeatureList == null)
                                                                    {
                                                                        ChangeFeatureList = new List<IObject>();
                                                                    }
                                                                    ((IFeature)iJuncFeat).set_Value(juncField, inObject.get_Value(intFldIdxs[0]));
                                                                    ChangeFeatureList.Add(((IFeature)iJuncFeat));

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  " + netField + " field not found");
                                                                }
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an edge feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an Geometric Network feature");
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  field was not changed");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: UPDATE_FROM_JUNCTION_FIELD:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: UPDATE_FROM_JUNCTION_FIELD");
                                            }
                                            break;
                                        case "UPDATE_FROM_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: UPDATE_FROM_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    IRowChanges pRowCh = null;

                                                    pRowCh = inObject as IRowChanges;

                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                    {

                                                        if (valData == null)
                                                        {
                                                            AAState.WriteLine("                  Value info is null");
                                                            break;
                                                        }
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {
                                                                            if (netRestrictFC != "")
                                                                            {
                                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                                if (strClsName != netRestrictFC)
                                                                                {
                                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                    continue;
                                                                                }
                                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                                {
                                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                    if (intTmpFld > -1)
                                                                                    {
                                                                                        //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                        if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                        {
                                                                                            AAState.WriteLine("                  Values Match");
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                                            continue;

                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                                }
                                                                            }

                                                                            iJuncFeat = iEdgeFeat.ToJunctionFeature;
                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {
                                                                                IFeature pRow = iEdgeFeat as IFeature;

                                                                                // verify that field (in junction) to copy exists
                                                                                juncField = Globals.GetFieldIndex(pRow.Fields, netField);

                                                                                if (juncField > -1)
                                                                                {
                                                                                    if (ChangeFeatureList == null)
                                                                                    {
                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                    }
                                                                                    pRow.set_Value(juncField, inObject.get_Value(intFldIdxs[0]));
                                                                                    ChangeFeatureList.Add(((IFeature)pRow));

                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  " + iSJunc + " field not found");
                                                                                }
                                                                                pRow = null;

                                                                                break;

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                            AAState.WriteLine("                  error ");
                                                                        }

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }
                                                                iSJunc = null;
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  field was not changed");
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: UPDATE_FROM_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: UPDATE_FROM_EDGE_FIELD");
                                            }
                                            break;
                                        case "UPDATE_TO_EDGE_FIELD":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: UPDATE_TO_EDGE_FIELD");
                                                if (inFeature != null)
                                                {
                                                    IRowChanges pRowCh = null;

                                                    pRowCh = inObject as IRowChanges;

                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                    {

                                                        if (valData == null)
                                                        {
                                                            AAState.WriteLine("                  Value info is null");
                                                            break;
                                                        }
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {

                                                                            if (netRestrictFC != "")
                                                                            {
                                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                                if (strClsName != netRestrictFC)
                                                                                {
                                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                    continue;
                                                                                }
                                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                                {
                                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                    if (intTmpFld > -1)
                                                                                    {
                                                                                        //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                        if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                        {
                                                                                            AAState.WriteLine("                  Values Match");
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                                            continue;

                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                                }
                                                                            }

                                                                            iJuncFeat = (IJunctionFeature)iEdgeFeat.FromJunctionFeature;
                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {
                                                                                IFeature pRow = iEdgeFeat as IFeature;

                                                                                // verify that field (in junction) to copy exists
                                                                                juncField = Globals.GetFieldIndex(pRow.Fields, netField);

                                                                                if (juncField > -1)
                                                                                {
                                                                                    if (ChangeFeatureList == null)
                                                                                    {
                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                    }
                                                                                    pRow.set_Value(juncField, inObject.get_Value(intFldIdxs[0]));
                                                                                    ChangeFeatureList.Add(((IFeature)pRow));

                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  " + netField + " field not found in edge");
                                                                                }
                                                                                pRow = null;
                                                                                break;

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                            AAState.WriteLine("                  error ");
                                                                        }

                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }
                                                                iSJunc = null;
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  field was not changed");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: UPDATE_TO_EDGE_FIELD: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: UPDATE_TO_EDGE_FIELD");
                                            }
                                            break;
                                        //***************8

                                        case "TRIGGER_UPDATE_INTERSECTING_FEATURE"://Intersected Feature|FieldIntersectingFeatureToChange|FromFieldinModifiedFeature
                                            {
                                                try
                                                {
                                                    IFeatureCursor fLocalCursor = null;
                                                    IFeature sourceFeatureLocal = null;
                                                    AAState.WriteLine("                  Trying: TRIGGER_UPDATE_INTERSECTING_FEATURE");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 3)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inFeature == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    bool cont = true;
                                                    if (intFldIdxs.Count > 1)
                                                    {
                                                        IRowChanges inChanges = inObject as IRowChanges;
                                                        if (inChanges.get_ValueChanged(intFldIdxs[0]))
                                                        {
                                                            cont = true;
                                                        }
                                                        else
                                                        {
                                                            cont = false;
                                                        }

                                                        inChanges = null;

                                                    }
                                                    if (cont)
                                                    {

                                                        sourceLayerName = "";
                                                        sourceFieldName = "";
                                                        sourceField = -1;
                                                        found = false;
                                                        AAState.WriteLine("                  Getting Value Info");
                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString().Trim();
                                                        string targetFieldName = args[2].ToString().Trim();
                                                        AAState.WriteLine("                  Checking values");
                                                        if (sourceFieldName != null)
                                                        {
                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                                if (sourceLayerName != "")
                                                                {

                                                                    boolLayerOrFC = true;
                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0].Trim();
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                    }
                                                                    if (sourceLayer != null)
                                                                    {

                                                                        if (Globals.IsEditable(ref sourceLayer, ref AAState._editor))
                                                                        {

                                                                            if (inObject.Class.ObjectClassID != sourceLayer.FeatureClass.ObjectClassID)
                                                                            {

                                                                                sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, false);

                                                                                pFS = (IFeatureSelection)sourceLayer;
                                                                                if (boolLayerOrFC)
                                                                                {
                                                                                    if (pFS.SelectionSet.Count > 0)
                                                                                    {
                                                                                        pFS.SelectionSet.Search(sFilter, false, out cCurs);
                                                                                        fLocalCursor = cCurs as IFeatureCursor;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        fLocalCursor = sourceLayer.Search(sFilter, false);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    fLocalCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                                }

                                                                                while ((sourceFeatureLocal = fLocalCursor.NextFeature()) != null)
                                                                                {
                                                                                    try
                                                                                    {
                                                                                        if (sourceFeatureLocal.Class.ObjectClassID != inFeature.Class.ObjectClassID)
                                                                                        {
                                                                                            if (sourceFieldName == "CREATE")
                                                                                            {
                                                                                                if (NewFeatureList == null)
                                                                                                {
                                                                                                    NewFeatureList = new List<IObject>();
                                                                                                }

                                                                                                NewFeatureList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }
                                                                                            else if (sourceFieldName == "CHANGEGEO")
                                                                                            {
                                                                                                if (ChangeFeatureGeoList == null)
                                                                                                {
                                                                                                    ChangeFeatureGeoList = new List<IObject>();
                                                                                                }

                                                                                                ChangeFeatureGeoList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                if (ChangeFeatureList == null)
                                                                                                {
                                                                                                    ChangeFeatureList = new List<IObject>();
                                                                                                }

                                                                                                ChangeFeatureList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }

                                                                                        }
                                                                                        else if (sourceFeatureLocal.Class == inFeature.Class && sourceFeatureLocal.OID != inFeature.OID)
                                                                                        {
                                                                                            if (sourceFieldName == "CREATE")
                                                                                            {
                                                                                                if (NewFeatureList == null)
                                                                                                {
                                                                                                    NewFeatureList = new List<IObject>();
                                                                                                }

                                                                                                NewFeatureList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }
                                                                                            else if (sourceFieldName == "CHANGEGEO")
                                                                                            {
                                                                                                if (ChangeFeatureGeoList == null)
                                                                                                {
                                                                                                    ChangeFeatureGeoList = new List<IObject>();
                                                                                                }

                                                                                                ChangeFeatureGeoList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                if (ChangeFeatureList == null)
                                                                                                {
                                                                                                    ChangeFeatureList = new List<IObject>();
                                                                                                }

                                                                                                ChangeFeatureList.Add(((IFeature)sourceFeatureLocal));
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR setting value");
                                                                                    }
                                                                                    finally
                                                                                    {

                                                                                    }

                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer is not editable: " + sourceLayerName);
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                }
                                                            }
                                                        }
                                                        if (found)
                                                        {
                                                            break;

                                                        }

                                                    }
                                                    fLocalCursor = null;
                                                    sourceFeatureLocal = null;
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: TRIGGER_UPDATE_INTERSECTING_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: TRIGGER_UPDATE_INTERSECTING_FEATURE");

                                                }
                                                break;

                                            }

                                        case "TRIGGER_UPDATE_TO_JUNCTION":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: TRIGGER_UPDATE_TO_JUNCTION");
                                                IRowChanges pRowCh = null;

                                                pRowCh = inObject as IRowChanges;

                                                if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                {

                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    if (inFeature != null)
                                                    {

                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                            {

                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iEdgeFeat = (IEdgeFeature)netFeat;
                                                                iJuncFeat = iEdgeFeat.ToJunctionFeature;

                                                                if (netRestrictFC != "")
                                                                {
                                                                    string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                    AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                    if (strClsName != netRestrictFC)
                                                                    {
                                                                        AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                        break;
                                                                    }
                                                                    AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                    if (netRestrictField != "" && netRestrictValue != "")
                                                                    {
                                                                        int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                        if (intTmpFld > -1)
                                                                        {
                                                                            if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                            {
                                                                                AAState.WriteLine("                  Values Match");
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Values dont match Match");
                                                                                break;

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Missing Field restriction and value info");
                                                                    }
                                                                }
                                                                // verify that field (in junction) to copy exists
                                                                if (netField == "CREATE")
                                                                {
                                                                    if (NewFeatureList == null)
                                                                    {
                                                                        NewFeatureList = new List<IObject>();
                                                                    }

                                                                    NewFeatureList.Add(((IFeature)iJuncFeat));
                                                                }
                                                                else if (netField == "CHANGEGEO")
                                                                {
                                                                    if (ChangeFeatureGeoList == null)
                                                                    {
                                                                        ChangeFeatureGeoList = new List<IObject>();
                                                                    }

                                                                    ChangeFeatureGeoList.Add(((IFeature)iJuncFeat));
                                                                }
                                                                else
                                                                {
                                                                    if (ChangeFeatureList == null)
                                                                    {
                                                                        ChangeFeatureList = new List<IObject>();
                                                                    }

                                                                    ChangeFeatureList.Add(((IFeature)iJuncFeat));
                                                                }

                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an edge feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an Geometric Network feature");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  field was not changed");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TRIGGER_UPDATE_TO_JUNCTION:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TRIGGER_UPDATE_TO_JUNCTION");
                                            }
                                            break;
                                        case "TRIGGER_UPDATE_FROM_JUNCTION":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: TRIGGER_UPDATE_FROM_JUNCTION");
                                                IRowChanges pRowCh = null;

                                                pRowCh = inObject as IRowChanges;

                                                if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                {

                                                    if (valData == null)
                                                    {
                                                        AAState.WriteLine("                  Value info is null");
                                                        break;
                                                    }
                                                    if (inFeature != null)
                                                    {

                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexEdge || inFeature.FeatureType == esriFeatureType.esriFTSimpleEdge)
                                                            {

                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iEdgeFeat = (IEdgeFeature)netFeat;
                                                                iJuncFeat = iEdgeFeat.FromJunctionFeature;

                                                                if (netRestrictFC != "")
                                                                {
                                                                    string strClsName = Globals.getClassName(((IDataset)((IFeature)iJuncFeat).Class));

                                                                    AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                    if (strClsName != netRestrictFC)
                                                                    {
                                                                        AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                        break;
                                                                    }
                                                                    AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                    if (netRestrictField != "" && netRestrictValue != "")
                                                                    {
                                                                        int intTmpFld = Globals.GetFieldIndex(((IFeature)iJuncFeat).Fields, netRestrictField);

                                                                        if (intTmpFld > -1)
                                                                        {
                                                                            if (((IFeature)iJuncFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                            {
                                                                                AAState.WriteLine("                  Values Match");
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Values dont match Match");
                                                                                break;

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Missing Field restriction and value info");
                                                                    }
                                                                }
                                                                if (netField == "CREATE")
                                                                {
                                                                    if (NewFeatureList == null)
                                                                    {
                                                                        NewFeatureList = new List<IObject>();
                                                                    }

                                                                    NewFeatureList.Add(((IFeature)iJuncFeat));
                                                                }
                                                                else if (netField == "CHANGEGEO")
                                                                {
                                                                    if (ChangeFeatureGeoList == null)
                                                                    {
                                                                        ChangeFeatureGeoList = new List<IObject>();
                                                                    }

                                                                    ChangeFeatureGeoList.Add(((IFeature)iJuncFeat));
                                                                }
                                                                else
                                                                {
                                                                    if (ChangeFeatureList == null)
                                                                    {
                                                                        ChangeFeatureList = new List<IObject>();
                                                                    }

                                                                    ChangeFeatureList.Add(((IFeature)iJuncFeat));
                                                                }
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an edge feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  not an Geometric Network feature");
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  field was not changed");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TRIGGER_UPDATE_FROM_JUNCTION:" + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TRIGGER_UPDATE_FROM_JUNCTION");
                                            }
                                            break;
                                        case "TRIGGER_UPDATE_FROM_EDGE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TRIGGER_UPDATE_FROM_EDGE");
                                                if (inFeature != null)
                                                {
                                                    IRowChanges pRowCh = null;

                                                    pRowCh = inObject as IRowChanges;

                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                    {

                                                        if (valData == null)
                                                        {
                                                            AAState.WriteLine("                  Value info is null");
                                                            break;
                                                        }
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {
                                                                            if (netRestrictFC != "")
                                                                            {
                                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                                if (strClsName != netRestrictFC)
                                                                                {
                                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                    continue;
                                                                                }
                                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                                {
                                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                    if (intTmpFld > -1)
                                                                                    {
                                                                                        //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                        if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                        {
                                                                                            AAState.WriteLine("                  Values Match");
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                                            continue;

                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                                }
                                                                            }

                                                                            iJuncFeat = iEdgeFeat.ToJunctionFeature;
                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {

                                                                                if (netField == "CREATE")
                                                                                {
                                                                                    if (NewFeatureList == null)
                                                                                    {
                                                                                        NewFeatureList = new List<IObject>();
                                                                                    }

                                                                                    NewFeatureList.Add(((IFeature)iEdgeFeat));
                                                                                }
                                                                                else if (netField == "CHANGEGEO")
                                                                                {
                                                                                    if (ChangeFeatureGeoList == null)
                                                                                    {
                                                                                        ChangeFeatureGeoList = new List<IObject>();
                                                                                    }

                                                                                    ChangeFeatureGeoList.Add(((IFeature)iEdgeFeat));
                                                                                }
                                                                                else
                                                                                {
                                                                                    if (ChangeFeatureList == null)
                                                                                    {
                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                    }

                                                                                    ChangeFeatureList.Add(((IFeature)iEdgeFeat));
                                                                                }

                                                                                break;

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                            AAState.WriteLine("                  error ");
                                                                        }

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }
                                                                iSJunc = null;
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  field was not changed");
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TRIGGER_UPDATE_FROM_EDGE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TRIGGER_UPDATE_FROM_EDGE");
                                            }
                                            break;
                                        case "TRIGGER_UPDATE_TO_EDGE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: TRIGGER_UPDATE_TO_EDGE");
                                                if (inFeature != null)
                                                {
                                                    IRowChanges pRowCh = null;

                                                    pRowCh = inObject as IRowChanges;

                                                    if (pRowCh.get_ValueChanged(intFldIdxs[0]) == true)
                                                    {

                                                        if (valData == null)
                                                        {
                                                            AAState.WriteLine("                  Value info is null");
                                                            break;
                                                        }
                                                        netFeat = inFeature as INetworkFeature;
                                                        if (netFeat != null)
                                                        {
                                                            if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                            {
                                                                string netField = "";
                                                                string netRestrictFC = "";
                                                                string netRestrictField = "";
                                                                string netRestrictValue = "";
                                                                args = valData.Split('|');
                                                                switch (args.GetLength(0))
                                                                {
                                                                    case 1:  // sequenceColumnName only
                                                                        netField = args[0].ToString().Trim();
                                                                        break;
                                                                    case 2:  // sequenceColumnName|sequenceFixedWidth
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        break;
                                                                    case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        break;
                                                                    case 4:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                                        netField = args[0].ToString().Trim();
                                                                        netRestrictFC = args[1].ToString().Trim();
                                                                        netRestrictField = args[2].ToString().Trim();
                                                                        netRestrictValue = args[3].ToString().Trim();
                                                                        break;
                                                                    default: break;
                                                                }

                                                                iJuncFeat = (IJunctionFeature)netFeat;
                                                                // IComplexJunctionFeature iCEd = iJuncFeat as IComplexJunctionFeature;
                                                                ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                                if (iSJunc == null)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount <= 0)
                                                                    break;
                                                                if (iSJunc.EdgeFeatureCount > 0)
                                                                {
                                                                    for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                    {
                                                                        iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                        try
                                                                        {

                                                                            if (netRestrictFC != "")
                                                                            {
                                                                                string strClsName = Globals.getClassName(((IDataset)((IFeature)iEdgeFeat).Class));

                                                                                AAState.WriteLine("                  Layer restriction found, Class name of junction is: " + strClsName);
                                                                                if (strClsName != netRestrictFC)
                                                                                {
                                                                                    AAState.WriteLine("                  Layer restriction does not match, breaking");
                                                                                    continue;
                                                                                }
                                                                                AAState.WriteLine("                  Layer restriction matches, checking for field restriction");
                                                                                if (netRestrictField != "" && netRestrictValue != "")
                                                                                {
                                                                                    int intTmpFld = Globals.GetFieldIndex(((IFeature)iEdgeFeat).Fields, netRestrictField);

                                                                                    if (intTmpFld > -1)
                                                                                    {
                                                                                        //IFeature pTest = ((IFeature)iEdgeFeat);

                                                                                        if (((IFeature)iEdgeFeat).get_Value(intTmpFld).ToString() == netRestrictValue)
                                                                                        {
                                                                                            AAState.WriteLine("                  Values Match");
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  Values dont match Match");
                                                                                            continue;

                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  " + netRestrictField + " was not found");
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  Missing Field restriction and value info");
                                                                                }
                                                                            }

                                                                            iJuncFeat = (IJunctionFeature)iEdgeFeat.FromJunctionFeature;
                                                                            if (((IFeature)iJuncFeat).Shape.Equals(inFeature.Shape))
                                                                            {
                                                                                if (netField == "CREATE")
                                                                                {
                                                                                    if (NewFeatureList == null)
                                                                                    {
                                                                                        NewFeatureList = new List<IObject>();
                                                                                    }

                                                                                    NewFeatureList.Add(((IFeature)iEdgeFeat));
                                                                                }
                                                                                else if (netField == "CHANGEGEO")
                                                                                {
                                                                                    if (ChangeFeatureGeoList == null)
                                                                                    {
                                                                                        ChangeFeatureGeoList = new List<IObject>();
                                                                                    }

                                                                                    ChangeFeatureGeoList.Add(((IFeature)iEdgeFeat));
                                                                                }
                                                                                else
                                                                                {
                                                                                    if (ChangeFeatureList == null)
                                                                                    {
                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                    }

                                                                                    ChangeFeatureList.Add(((IFeature)iEdgeFeat));
                                                                                }

                                                                                break;
                                                                                break;

                                                                            }
                                                                        }
                                                                        catch
                                                                        {
                                                                            AAState.WriteLine("                  error ");
                                                                        }

                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  No Connected Edges Found");
                                                                }
                                                                iSJunc = null;
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  not an junction feature");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Not a Geometric Network Feature");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  field was not changed");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: TRIGGER_UPDATE_TO_EDGE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: TRIGGER_UPDATE_TO_EDGE");
                                            }
                                            break;
                                        //***********8
                                        //Release: 1.2
                                        //New Dynamic Value Method: GENERATE_ID - uses value in specificed table and increments it as specified
                                        case "GENERATE_ID":

                                            try
                                            {
                                                AAState.WriteLine("                  Trying: GENERATE_ID");
                                                if (AAState._gentab != null)
                                                {
                                                    sequenceColumnName = "";
                                                    sequenceColumnNum = -1;
                                                    sequenceValue = -1;
                                                    sequenceFixedWidth = "";
                                                    sequencePadding = 0;
                                                    formatString = "";

                                                    // Parse arguments
                                                    if (valData == null) break;
                                                    args = valData.Split('|');
                                                    switch (args.GetLength(0))
                                                    {
                                                        case 1:  // sequenceColumnName only
                                                            sequenceColumnName = args[0].ToString(); break;
                                                        case 2:  // sequenceColumnName|sequenceFixedWidth
                                                            sequenceColumnName = args[0].ToString();
                                                            sequenceFixedWidth = args[1].ToString();
                                                            break;
                                                        case 3:  // sequenceColumnName|sequenceFixedWidth|formatString
                                                            sequenceColumnName = args[0].ToString();
                                                            sequenceFixedWidth = args[1].ToString();
                                                            formatString = args[2].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    //Check for requested zero padding of sequence number
                                                    if (sequenceFixedWidth != "")
                                                        int.TryParse(sequenceFixedWidth.ToString(), out sequencePadding);
                                                    if (sequencePadding > 25)
                                                    {

                                                        AAState.WriteLine("                  WARNING: you are trying to pad your id with a more than 25 - 0's");
                                                        AAState.WriteLine("                  WARNING: " + sequencePadding + " 0's is what you have");

                                                    }
                                                    else if (sequencePadding > 50)
                                                    {
                                                        MessageBox.Show("You are trying to add 50 places to your ID, this is not supported, please fix your dynamic value table");
                                                    }
                                                    qFilter = new QueryFilterClass();
                                                    qFilter.WhereClause = "SEQNAME = '" + sequenceColumnName + "'";
                                                    cCurs = AAState._gentab.Update(qFilter, false);
                                                    sequenceColumnNum = AAState._gentab.Fields.FindField("SEQCOUNTER");
                                                    //get value of first row, increment it, and return incremented value
                                                    for (int j = 0; j < 51; j++)
                                                    {
                                                        row = cCurs.NextRow();
                                                        if (row == null)
                                                        {
                                                            break;
                                                        }
                                                        if (row.get_Value(sequenceColumnNum) == null)
                                                        {
                                                            sequenceValue = 0;
                                                        }
                                                        else if (row.get_Value(sequenceColumnNum).ToString() == "")
                                                        {
                                                            sequenceValue = 0;
                                                        }
                                                        else
                                                            sequenceValue = Convert.ToInt32(row.get_Value(sequenceColumnNum));

                                                        // _editEvents.OnChangeFeature -= OnChangeFeature;
                                                        // _editEvents.OnCreateFeature -= OnCreateFeature;
                                                        int sequenceInt = 1;

                                                        if (AAState._gentab.Fields.FindField("SEQINTERV") > 0)
                                                        {
                                                            if (row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")) != null)
                                                            {
                                                                if (row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")) != DBNull.Value)
                                                                    sequenceInt = Convert.ToInt32(row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")));
                                                            }
                                                        }
                                                        sequenceValue = sequenceValue + sequenceInt;

                                                        row.set_Value(sequenceColumnNum, sequenceValue);
                                                        AAState.WriteLine("                  " + row.Fields.get_Field(sequenceColumnNum).AliasName + " changed to " + sequenceValue);
                                                        //AAState.changeFeature -= OnChangeFeature;
                                                        //AAState.createFeature -= OnCreateFeature;

                                                        row.Store();
                                                        //AAState.changeFeature += OnChangeFeature;
                                                        //AAState.createFeature += OnCreateFeature;

                                                        //  _editEvents.OnChangeFeature += OnChangeFeature;
                                                        //  _editEvents.OnCreateFeature += OnCreateFeature;
                                                        if (Convert.ToInt32(row.get_Value(sequenceColumnNum)) == sequenceValue)
                                                            break;

                                                    }
                                                    if (sequenceValue == -1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: GENERATE_ID: Sequence Not Found");
                                                    }

                                                    else
                                                    {
                                                        if (inObject.Fields.get_Field(intFldIdxs[0]).Type == esriFieldType.esriFieldTypeString)
                                                            if (formatString == null || formatString == "" || formatString.ToLower().IndexOf("[seq]") == -1)
                                                            {
                                                                string setVal = (sequenceValue.ToString("D" + sequencePadding) + sequencePostfix).ToString();

                                                                if (inObject.Fields.get_Field(intFldIdxs[0]).Length < setVal.Length && inObject.Fields.get_Field(intFldIdxs[0]).Length != 0)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sequenceValue + " is to long for field " + row.Fields.get_Field(sequenceColumnNum).AliasName);
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], (sequenceValue.ToString("D" + sequencePadding) + sequencePostfix).Trim());
                                                                    AAState.WriteLine("                  " + inObject.Fields.get_Field(intFldIdxs[0]).AliasName + " set to " + sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);

                                                                }

                                                            }
                                                            else
                                                            {

                                                                int locIdx = formatString.ToUpper().IndexOf("[SEQ]");
                                                                if (locIdx >= 0)
                                                                {
                                                                    formatString = formatString.Remove(locIdx, 5);
                                                                    formatString = formatString.Insert(locIdx, sequenceValue.ToString("D" + sequencePadding));
                                                                }
                                                                //formatString = formatString.Replace("[seq]", sequenceValue.ToString("D" + sequencePadding));

                                                                if (inObject.Fields.get_Field(intFldIdxs[0]).Length < formatString.Length && inObject.Fields.get_Field(intFldIdxs[0]).Length != 0)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + formatString + " is to long for field " + row.Fields.get_Field(sequenceColumnNum).AliasName);
                                                                }
                                                                else
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], formatString.Trim());
                                                                    AAState.WriteLine("                  " + inObject.Fields.get_Field(intFldIdxs[0]).AliasName + " set to " + formatString);
                                                                }

                                                            }
                                                        else
                                                        {

                                                            inObject.set_Value(intFldIdxs[0], sequenceValue);
                                                            AAState.WriteLine("                  " + sequenceColumnNum + " changed to " + sequenceValue);
                                                        }
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: GENERATE_ID table is not found");

                                                }

                                            }

                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GENERATE_ID: " + ex.Message);
                                            }
                                            finally
                                            {
                                                if (cCurs != null)
                                                {
                                                    Marshal.ReleaseComObject(cCurs);
                                                    GC.Collect(300);
                                                    GC.WaitForFullGCComplete();
                                                    cCurs = null;

                                                }
                                                AAState.WriteLine("                  Finished: GENERATE_ID");
                                            }
                                            break;

                                        case "GENERATE_ID_BY_INTERSECT":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: GENERATE_ID_BY_INTERSECT");
                                                if (AAState._gentab != null && inFeature != null && !(inFeature.Shape.IsEmpty))
                                                {
                                                    sequenceColumnName = "";
                                                    sequenceColumnNum = -1;
                                                    sequenceValue = -1;
                                                    sequenceFixedWidth = "";
                                                    sequencePadding = 0;
                                                    //genIdAreaFieldName = "";
                                                    intersectLayerName = "";
                                                    intersectLayerFieldName = "";
                                                    formatString = "";
                                                    intersectFieldPos = -1;

                                                    // Parse arguments
                                                    if (valData == null) break;

                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) < 3)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Improper value method");
                                                        break;
                                                    }
                                                    switch (args.GetLength(0))
                                                    {
                                                        case 3:  //columnName
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            // genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            break;
                                                        case 4:  // columnName|sequenceFixedWidth
                                                            //sequenceFixedWidth formats the sequence with leading zeros to create specified width
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            //genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            sequenceFixedWidth = Convert.ToString(0);
                                                            formatString = args[3].ToString();

                                                            break;
                                                        case 5:  // columnName|sequenceFixedWidth|formatString
                                                            //formatString must contain [seq] and [id]  and may contain [area] plus any desired text
                                                            intersectLayerName = args[0].ToString();
                                                            intersectLayerFieldName = args[1].ToString();
                                                            //genIdAreaFieldName = args[2].ToString();
                                                            sequenceColumnName = args[2].ToString();
                                                            sequenceFixedWidth = args[3].ToString();
                                                            formatString = args[4].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    //Find Area Layer
                                                    // FindLayerByName(areaLayerName, out areaLayer);

                                                    boolLayerOrFC = true;
                                                    if (intersectLayerName.Contains("("))
                                                    {
                                                        string[] tempSplt = intersectLayerName.Split('(');
                                                        intersectLayerName = tempSplt[0];
                                                        intersectLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, intersectLayerName, ref boolLayerOrFC);
                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                        {
                                                            boolLayerOrFC = false;
                                                        }
                                                        else
                                                        {
                                                            boolLayerOrFC = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        intersectLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, intersectLayerName, ref boolLayerOrFC);

                                                    }
                                                    if (intersectLayer == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature Layer(" + intersectLayerName + ") not found");
                                                        break;
                                                    }
                                                    //Find Area Field
                                                    intersectFieldPos = intersectLayer.FeatureClass.FindField(intersectLayerFieldName);
                                                    if (intersectFieldPos < 0)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature Layer Field(" + intersectLayerFieldName + ") not found");
                                                        break;
                                                    }

                                                    //Perform spatial search
                                                    IGeometry pSearchGeo = Globals.GetGeomCenter((IGeometry)inFeature.ShapeCopy)[0];
                                                    pSearchGeo.SpatialReference = (inFeature.Class as IGeoDataset).SpatialReference;
                                                    pSearchGeo.Project((intersectLayer as IGeoDataset).SpatialReference);

                                                    sFilter = Globals.createSpatialFilter(intersectLayer, inFeature, false);

                                                    pFS = (IFeatureSelection)intersectLayer;
                                                    if (boolLayerOrFC)
                                                    {
                                                        if (pFS.SelectionSet.Count > 0)
                                                        {
                                                            pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                            fCursor = cCurs as IFeatureCursor;

                                                        }
                                                        else
                                                        {
                                                            fCursor = intersectLayer.Search(sFilter, true);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        fCursor = intersectLayer.FeatureClass.Search(sFilter, true);
                                                    }

                                                    sourceFeature = fCursor.NextFeature();
                                                    intersectValue = "-9999.1";
                                                    if (sourceFeature == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature not found");
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        while (sourceFeature != null)
                                                        {
                                                            if (sourceFeature.Class != inFeature.Class)
                                                            {
                                                                intersectValue = sourceFeature.get_Value(intersectFieldPos).ToString();
                                                                break;
                                                            }
                                                            else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                            {
                                                                intersectValue = sourceFeature.get_Value(intersectFieldPos).ToString();
                                                                break;
                                                            }
                                                            sourceFeature = fCursor.NextFeature();
                                                        }
                                                    }
                                                    if (intersectValue == "-9999.1")
                                                    {
                                                        AAState.WriteLine("                  ERROR: Intersecting feature not found");
                                                        break;
                                                    }
                                                    //Check for requested zero padding of sequence number
                                                    if (sequenceFixedWidth != "")
                                                        int.TryParse(sequenceFixedWidth.ToString(), out sequencePadding);

                                                    if (sequencePadding > 25)
                                                    {
                                                        AAState.WriteLine("                  WARNING: you are trying to pad your id with a more than 25 - 0's");
                                                        AAState.WriteLine("                  WARNING: " + sequencePadding + " 0's is what you have");

                                                    }
                                                    sequenceColumnName = sequenceColumnName + intersectValue;
                                                    AAState.WriteLine("                  Looking for a field called " + sequenceColumnName + " in the generate ID table");

                                                    qFilter = new QueryFilterClass();
                                                    qFilter.WhereClause = "SEQNAME = '" + sequenceColumnName + "'";
                                                    cCurs = AAState._gentab.Update(qFilter, false);
                                                    sequenceColumnNum = AAState._gentab.Fields.FindField("SEQCOUNTER");

                                                    //get value of first row, increment it, and return incremented value
                                                    for (int j = 0; j < 51; j++)
                                                    {
                                                        row = cCurs.NextRow();
                                                        if (row == null)
                                                        {
                                                            break;
                                                        }
                                                        if (row.get_Value(sequenceColumnNum) == null)
                                                        {
                                                            sequenceValue = 0;
                                                        }
                                                        else if (row.get_Value(sequenceColumnNum).ToString() == "")
                                                        {
                                                            sequenceValue = 0;
                                                        }
                                                        else
                                                            sequenceValue = Convert.ToInt32(row.get_Value(sequenceColumnNum));

                                                        int sequenceInt = 1;

                                                        if (AAState._gentab.Fields.FindField("SEQINTERV") > 0)
                                                        {
                                                            if (row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")) != null)
                                                            {
                                                                if (row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")) != DBNull.Value)
                                                                    sequenceInt = Convert.ToInt32(row.get_Value(AAState._gentab.Fields.FindField("SEQINTERV")));
                                                            }
                                                        }
                                                        sequenceValue = sequenceValue + sequenceInt;

                                                        row.set_Value(sequenceColumnNum, sequenceValue);

                                                        row.Store();

                                                        if (Convert.ToInt32(row.get_Value(sequenceColumnNum)) == sequenceValue)
                                                            break;

                                                    }
                                                    if (sequenceValue == -1)
                                                    {
                                                        AAState.WriteLine("                  ERROR: Sequence number not found");
                                                    }
                                                    else
                                                    {
                                                        if (inObject.Fields.get_Field(intFldIdxs[0]).Type == esriFieldType.esriFieldTypeString)
                                                            if (formatString == null || formatString == "" || (formatString.ToUpper().IndexOf("[SEQ]") == -1 && formatString.ToUpper().IndexOf("[ID]") == -1))
                                                                inObject.set_Value(intFldIdxs[0], intersectValue + sequenceValue.ToString("D" + sequencePadding) + sequencePostfix);
                                                            else
                                                            {

                                                                int locIdx = formatString.ToUpper().IndexOf("[ID]");
                                                                if (locIdx >= 0)
                                                                {
                                                                    formatString = formatString.Remove(locIdx, 4);
                                                                    formatString = formatString.Insert(locIdx, intersectValue);
                                                                }

                                                                locIdx = formatString.ToUpper().IndexOf("[SEQ]");
                                                                if (locIdx >= 0)
                                                                {
                                                                    string sequenceValuePad = sequenceValue.ToString("D" + sequencePadding);
                                                                    formatString = formatString.Remove(locIdx, 5);
                                                                    formatString = formatString.Insert(locIdx, sequenceValuePad.ToString());
                                                                }
                                                                //
                                                                inObject.set_Value(intFldIdxs[0], formatString);
                                                            }
                                                        else
                                                            inObject.set_Value(intFldIdxs[0], sequenceValue);
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: GENERATE_ID table is not found");

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: GENERATE_ID_BY_INTERSECT: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: GENERATE_ID_BY_INTERSECT");
                                            }
                                            break;

                                        //Modified for Release 1.2  (No longer uses ICalculator)
                                        //Requires valid VBScript expression
                                        //Can include string, numeric, and date fields by name in square brackets []
                                        //Example: DateDiff("yyyy",[INSTALLDATE],Now())
                                        case "EXPRESSION":
                                            try
                                            {

                                                AAState.WriteLine("                  Trying: EXPRESSION");
                                                if (inObject != null & valData != null)
                                                {
                                                    int intTargetFld = -1;
                                                    if (intFldIdxs.Count == 0)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        intTargetFld = intFldIdxs[0];
                                                    }

                                                    newValue = valData;
                                                    for (int i = 0; i <= inObject.Fields.FieldCount; i++)
                                                    {

                                                        string strTmpFldName;
                                                        int intTmpIdx;
                                                        if (i == inObject.Fields.FieldCount)
                                                        {
                                                            testField = inObject.Fields.get_Field(intFldIdxs[0]);
                                                            strTmpFldName = "#";
                                                            intTmpIdx = intFldIdxs[0];
                                                        }
                                                        else
                                                        {
                                                            testField = inObject.Fields.get_Field(i);
                                                            strTmpFldName = testField.Name;
                                                            intTmpIdx = i;
                                                        }

                                                        int indFld = newValue.ToUpper().IndexOf("[" + strTmpFldName.ToUpper() + "]");
                                                        while (indFld >= 0)
                                                        {
                                                            AAState.WriteLine("                  replace field: " + testField.Name + " with a value");
                                                            int fldLen = strTmpFldName.Length;
                                                            string tmpStr1 = newValue.Substring(0, indFld + 1);
                                                            string tmpStr2 = newValue.Substring(indFld + fldLen + 1);
                                                            newValue = tmpStr1 + "_REPLACE_VAL_" + tmpStr2;

                                                            switch (testField.Type)
                                                            {
                                                                case esriFieldType.esriFieldTypeString:

                                                                    if (inObject.get_Value(intTmpIdx) == null || inObject.get_Value(intTmpIdx).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("isNull"))
                                                                        {
                                                                            newValue = newValue.Replace("isNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("ISNULL"))
                                                                        {
                                                                            newValue = newValue.Replace("ISNULL([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == DBNull.Value)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                    }

                                                                    break;
                                                                case esriFieldType.esriFieldTypeDate:

                                                                    if (inObject.get_Value(intTmpIdx) == null || inObject.get_Value(intTmpIdx).ToString() == "" || inObject.get_Value(intTmpIdx) == DBNull.Value)
                                                                    {
                                                                        if (newValue.Contains("IsNull([" + "_REPLACE_VAL_" + "])"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("isNull([" + "_REPLACE_VAL_" + "])"))
                                                                        {
                                                                            newValue = newValue.Replace("isNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("ISNULL([" + "_REPLACE_VAL_" + "])"))
                                                                        {
                                                                            newValue = newValue.Replace("ISNULL([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == DBNull.Value)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");//"\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + inObject.get_Value(intTmpIdx).ToString() + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "CDATE(\"" + inObject.get_Value(intTmpIdx).ToString() + "\")");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "CDATE(\"" + inObject.get_Value(intTmpIdx).ToString() + "\")");
                                                                        }
                                                                    }

                                                                    break;
                                                                case esriFieldType.esriFieldTypeDouble:

                                                                    if (inObject.get_Value(intTmpIdx) == null || inObject.get_Value(intTmpIdx).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("isNull"))
                                                                        {
                                                                            newValue = newValue.Replace("isNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("ISNULL"))
                                                                        {
                                                                            newValue = newValue.Replace("ISNULL([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == DBNull.Value)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "" + inObject.get_Value(intTmpIdx).ToString() + "");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {

                                                                            double val;
                                                                            Double.TryParse(inObject.get_Value(intTmpIdx).ToString(), out val);

                                                                            // '  string test2 = test.ToString("N",nfi);
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", val.ToString("N", nfi));
                                                                        }
                                                                    }

                                                                    break;

                                                                default:
                                                                    if (inObject.get_Value(intTmpIdx) == null || inObject.get_Value(intTmpIdx).ToString() == "")
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("isNull"))
                                                                        {
                                                                            newValue = newValue.Replace("isNull([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (newValue.Contains("ISNULL"))
                                                                        {
                                                                            newValue = newValue.Replace("ISNULL([" + "_REPLACE_VAL_" + "])", "True");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == null)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx) == DBNull.Value)
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else if (inObject.get_Value(intTmpIdx).ToString() == "")
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "\"" + "\"");
                                                                        }
                                                                        else
                                                                        {
                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", "" + inObject.get_Value(intTmpIdx).ToString() + "");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (newValue.Contains("IsNull"))
                                                                        {
                                                                            newValue = newValue.Replace("IsNull([" + "_REPLACE_VAL_" + "])", "False");
                                                                        }

                                                                        else
                                                                        {

                                                                            newValue = newValue.Replace("[" + "_REPLACE_VAL_" + "]", inObject.get_Value(intTmpIdx).ToString());
                                                                        }
                                                                    }

                                                                    break;
                                                            }
                                                            indFld = newValue.ToUpper().IndexOf("[" + testField.Name.ToUpper() + "]");
                                                        }
                                                    }

                                                    try
                                                    {
                                                        AAState.WriteLine("                  Checking to verify there is a field to store the expression");
                                                        if (intTargetFld > -1)
                                                        {
                                                            AAState.WriteLine("Expression to be eval: " + newValue);

                                                            newValue = script.Eval(newValue).ToString();
                                                            if (newValue.ToUpper() == "<Null>".ToUpper())
                                                            {
                                                                AAState.WriteLine("                  Setting Null");
                                                                inObject.set_Value(intTargetFld, DBNull.Value);
                                                            }
                                                            else if (inObject.get_Value(intTargetFld).ToString() != newValue)
                                                            {
                                                                AAState.WriteLine("                  Setting Value to: " + newValue.Trim());
                                                                inObject.set_Value(intTargetFld, newValue.Trim());
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        AAState.WriteLine("                  ERROR: evaluating the expression for feature in " + inObject.Class.AliasName + " with OID of " + inObject.OID);
                                                        AAState.WriteLine("                         " + ex.Message);
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: EXPRESSION: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: EXPRESSION");
                                            }
                                            break;

                                        // GUID values are calculated into text fields or into native GUID field types
                                        // When using text field you have an optional argument (valdata) to specify the format
                                        // N-none 32 chars, D-dash 36, B-braces 38, P-Parenthesis 38
                                        case "GUID":
                                            try
                                            {
                                                if (inObject != null)
                                                {
                                                    if (inObject.Fields.get_Field(intFldIdxs[0]).Type == esriFieldType.esriFieldTypeGUID)
                                                        inObject.set_Value(intFldIdxs[0], System.Guid.NewGuid().ToString("B"));
                                                    else if (inObject.Fields.get_Field(intFldIdxs[0]).Type == esriFieldType.esriFieldTypeString &&
                                                             inObject.Fields.get_Field(intFldIdxs[0]).Length >= 32)
                                                    {

                                                        valData = valData.Trim();
                                                        if (valData != "N" && valData != "D" && valData != "B" && valData != "P")
                                                            if (inObject.Fields.get_Field(intFldIdxs[0]).Length >= 38)
                                                                valData = "B";  //Default to braces
                                                            else if (inObject.Fields.get_Field(intFldIdxs[0]).Length < 36)
                                                                valData = "N";
                                                            else
                                                                valData = "D";
                                                        inObject.set_Value(intFldIdxs[0], System.Guid.NewGuid().ToString(valData));
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: EXPRESSION: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: EXPRESSION");
                                            }
                                            break;

                                        case "CREATE_LINKED_RECORD"://Feature Layer|Field To Copy|Field To Populate|Primary Key Field|Foreign Key Field
                                            {
                                                try
                                                {
                                                    AAState.WriteLine("                  Trying: CREATE_LINKED_RECORD");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length < 5)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inObject == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    AAState.WriteLine("                  Getting Value Info");
                                                    sourceLayerNames = args[0].ToString().Split(',');
                                                    sourceFieldName = args[1].ToString().Trim();
                                                    string targetFieldName = args[2].ToString().Trim();
                                                    string sourceIDFieldName = args[3].ToString().Trim();
                                                    string targetIDFieldName = args[4].ToString().Trim();
                                                    int countFld = 1;
                                                    if (args.Length == 6)
                                                    {

                                                        if (!Globals.IsNumeric(args[5].ToString().Trim()))
                                                        {
                                                            int fldx = Globals.GetFieldIndex(inObject.Fields, args[5].ToString().Trim());

                                                            if (fldx > 0)
                                                            {
                                                                string tempVal = inObject.get_Value(fldx).ToString();
                                                                if (Globals.IsNumeric(tempVal))
                                                                    countFld = Convert.ToInt32(tempVal);

                                                            }

                                                        }
                                                        else
                                                        {
                                                            countFld = Convert.ToInt32(args[5].ToString().Trim());

                                                        }

                                                    }
                                                    AAState.WriteLine("                  Checking values");
                                                    if (sourceFieldName != null)
                                                    {
                                                        AAState.WriteLine("                  Checking Fields in Source Layer");
                                                        int fldValToCopyIdx = Globals.GetFieldIndex(inObject.Fields, sourceFieldName);
                                                        int fldIDToCopyIdx = Globals.GetFieldIndex(inObject.Fields, sourceIDFieldName);
                                                        if (fldValToCopyIdx > -1 && fldIDToCopyIdx > -1)
                                                        {

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();

                                                                if (sourceLayerName != "")
                                                                {

                                                                    // Get layer
                                                                    AAState.WriteLine("                  Checking for table to populate");
                                                                    bool FCorLayerSource = true;
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref FCorLayerSource);

                                                                    if (sourceLayer != null)
                                                                    {
                                                                        AAState.WriteLine("                  " + sourceLayerName + " Was not found");

                                                                    }
                                                                    else
                                                                    {
                                                                        ITable pTable = Globals.FindTable(AAState._editor.Map, sourceLayerName);
                                                                        if (pTable != null)
                                                                        {
                                                                            int fldValToPopIdx = Globals.GetFieldIndex(pTable.Fields, targetFieldName);
                                                                            int fldIDToPopIdx = Globals.GetFieldIndex(pTable.Fields, targetIDFieldName);
                                                                            if (fldValToPopIdx > -1 && fldIDToPopIdx > -1)
                                                                            {
                                                                                AAState.WriteLine("                  Trying to create a row in the target table");
                                                                                IRow pNewRow;
                                                                                for (int j = 0; j < countFld; j++)
                                                                                {
                                                                                    pNewRow = pTable.CreateRow();
                                                                                    AAState.WriteLine("                  Row Created");
                                                                                    AAState.WriteLine("                  Trying to Copy ID");
                                                                                    try
                                                                                    {
                                                                                        pNewRow.set_Value(fldIDToPopIdx, inObject.get_Value(fldIDToCopyIdx));

                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldIDToCopyIdx) + " to field: " + targetIDFieldName);
                                                                                    }
                                                                                    AAState.WriteLine("                  ID successfully copied");
                                                                                    AAState.WriteLine("                  Trying to Copy Value");
                                                                                    try
                                                                                    {
                                                                                        pNewRow.set_Value(fldValToPopIdx, inObject.get_Value(fldValToCopyIdx));

                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        AAState.WriteLine("                  ERROR: Could not Copy: " + inObject.get_Value(fldValToCopyIdx) + " to field: " + targetFieldName);
                                                                                    }
                                                                                    if (NewFeatureList == null)
                                                                                    {
                                                                                        NewFeatureList = new List<IObject>();
                                                                                    }
                                                                                    IObject featobj = pNewRow as IObject;

                                                                                    if (featobj != null)
                                                                                    {
                                                                                        NewFeatureList.Add(featobj);
                                                                                    }

                                                                                    AAState.WriteLine("                  Row successfully stored");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: ID or Field to populate was not found");
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR: Table to populate not found: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: ID or Field to Copy was not found");
                                                        }

                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: CREATE_LINKED_RECORD" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: CREATE_LINKED_RECORD");

                                                }
                                                break;

                                            }

                                        case "UPDATE_INTERSECTING_FEATURE"://Intersected Feature|FieldIntersectingFeatureToChange|FromFieldinModifiedFeature
                                            {
                                                try
                                                {
                                                    IFeatureCursor fLocalCursor = null;
                                                    IFeature sourceFeatureLocal = null;
                                                    AAState.WriteLine("                  Trying: UPDATE_INTERSECTING_FEATURE");
                                                    if (!String.IsNullOrEmpty(valData))
                                                    {
                                                        args = valData.Split('|');
                                                        if (args.Length != 3)
                                                        {
                                                            AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Format of valdata incorrect");
                                                        break;
                                                    }
                                                    if (inFeature == null)
                                                    {
                                                        AAState.WriteLine("                  ERROR: The input features is null");
                                                        break;
                                                    }
                                                    bool cont = true;
                                                    if (intFldIdxs.Count > 1)
                                                    {
                                                        IRowChanges inChanges = inObject as IRowChanges;
                                                        if (inChanges.get_ValueChanged(intFldIdxs[0]))
                                                        {
                                                            cont = true;
                                                        }
                                                        else
                                                        {
                                                            cont = false;
                                                        }

                                                        inChanges = null;

                                                    }
                                                    if (cont)
                                                    {

                                                        sourceLayerName = "";
                                                        sourceFieldName = "";
                                                        sourceField = -1;
                                                        found = false;
                                                        AAState.WriteLine("                  Getting Value Info");
                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString().Trim();
                                                        string targetFieldName = args[2].ToString().Trim();
                                                        AAState.WriteLine("                  Checking values");
                                                        if (sourceFieldName != null)
                                                        {
                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                                if (sourceLayerName != "")
                                                                {

                                                                    boolLayerOrFC = true;
                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0].Trim();
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                    }
                                                                    if (sourceLayer != null)
                                                                    {

                                                                        if (Globals.IsEditable(ref sourceLayer, ref AAState._editor))
                                                                        {

                                                                            if (inObject.Class.ObjectClassID != sourceLayer.FeatureClass.ObjectClassID)
                                                                            {
                                                                                sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);

                                                                                if (sourceField > -1)
                                                                                {
                                                                                    sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, false);

                                                                                    int fldIdx = Globals.GetFieldIndex(inFeature.Fields, targetFieldName);
                                                                                    AAState.WriteLine("                  " + targetFieldName + " at index " + fldIdx);
                                                                                    string test = targetFieldName;
                                                                                    if (fldIdx > -1)
                                                                                    {
                                                                                        test = inFeature.get_Value(fldIdx).ToString().Trim();
                                                                                        AAState.WriteLine("                  Value Found " + test);
                                                                                    }
                                                                                    AAState.WriteLine("                  Value used " + test);

                                                                                    pFS = (IFeatureSelection)sourceLayer;
                                                                                    if (boolLayerOrFC)
                                                                                    {
                                                                                        if (pFS.SelectionSet.Count > 0)
                                                                                        {
                                                                                            pFS.SelectionSet.Search(sFilter, false, out cCurs);
                                                                                            fLocalCursor = cCurs as IFeatureCursor;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            fLocalCursor = sourceLayer.Search(sFilter, false);
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        fLocalCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                                    }

                                                                                    while ((sourceFeatureLocal = fLocalCursor.NextFeature()) != null)
                                                                                    {
                                                                                        try
                                                                                        {
                                                                                            if (sourceFeatureLocal.Class.ObjectClassID != inFeature.Class.ObjectClassID)
                                                                                            {
                                                                                                if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeString)
                                                                                                {
                                                                                                    sourceFeatureLocal.set_Value(sourceField, test);

                                                                                                    if (ChangeFeatureList == null)
                                                                                                    {
                                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                                    }
                                                                                                    ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                    found = true;

                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    if (Globals.IsNumeric(test))
                                                                                                    {
                                                                                                        if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSmallInteger ||
                                                                                                            sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeInteger)
                                                                                                        {

                                                                                                            sourceFeatureLocal.set_Value(sourceField, Convert.ToInt32(test));

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;
                                                                                                            //break;
                                                                                                        }
                                                                                                        else if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeDouble ||
                                                                                                            sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSingle)
                                                                                                        {
                                                                                                            sourceFeatureLocal.set_Value(sourceField, Convert.ToDouble(test));

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;

                                                                                                        }
                                                                                                        else
                                                                                                        {
                                                                                                            sourceFeatureLocal.set_Value(sourceField, test as object);

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;

                                                                                                        }
                                                                                                    }
                                                                                                    else
                                                                                                    {
                                                                                                        sourceFeatureLocal.set_Value(sourceField, test as object);

                                                                                                        if (ChangeFeatureList == null)
                                                                                                        {
                                                                                                            ChangeFeatureList = new List<IObject>();
                                                                                                        }
                                                                                                        ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                        found = true;

                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                            else if (sourceFeatureLocal.Class == inFeature.Class && sourceFeatureLocal.OID != inFeature.OID)
                                                                                            {
                                                                                                if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeString)
                                                                                                {
                                                                                                    sourceFeatureLocal.set_Value(sourceField, test);

                                                                                                    if (ChangeFeatureList == null)
                                                                                                    {
                                                                                                        ChangeFeatureList = new List<IObject>();
                                                                                                    }
                                                                                                    ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                    found = true;

                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    if (Globals.IsNumeric(test))
                                                                                                    {
                                                                                                        if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSmallInteger ||
                                                                                                            sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeInteger)
                                                                                                        {

                                                                                                            sourceFeatureLocal.set_Value(sourceField, Convert.ToInt32(test));

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;

                                                                                                        }
                                                                                                        else if (sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeDouble ||
                                                                                                            sourceFeatureLocal.Fields.get_Field(sourceField).Type == esriFieldType.esriFieldTypeSingle)
                                                                                                        {
                                                                                                            sourceFeatureLocal.set_Value(sourceField, Convert.ToDouble(test));

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;

                                                                                                        }
                                                                                                        else
                                                                                                        {
                                                                                                            sourceFeatureLocal.set_Value(sourceField, test as object);

                                                                                                            if (ChangeFeatureList == null)
                                                                                                            {
                                                                                                                ChangeFeatureList = new List<IObject>();
                                                                                                            }
                                                                                                            ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                            found = true;

                                                                                                        }
                                                                                                    }
                                                                                                    else
                                                                                                    {
                                                                                                        sourceFeatureLocal.set_Value(sourceField, test as object);

                                                                                                        if (ChangeFeatureList == null)
                                                                                                        {
                                                                                                            ChangeFeatureList = new List<IObject>();
                                                                                                        }
                                                                                                        ChangeFeatureList.Add(sourceFeatureLocal);
                                                                                                        found = true;

                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                        catch
                                                                                        {
                                                                                            AAState.WriteLine("                  ERROR setting value");
                                                                                        }
                                                                                        finally
                                                                                        {

                                                                                        }

                                                                                    }

                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Source Layer is not editable: " + sourceLayerName);
                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                            }
                                                            if (found)
                                                            {
                                                                break;

                                                            }

                                                        }

                                                    }
                                                    fLocalCursor = null;
                                                    sourceFeatureLocal = null;
                                                }
                                                catch (Exception ex)
                                                {
                                                    AAState.WriteLine("                  ERROR: UPDATE_INTERSECTING_FEATURE" + Environment.NewLine + ex.Message);
                                                }

                                                finally
                                                {
                                                    AAState.WriteLine("                  Finished: UPDATE_INTERSECTING_FEATURE");

                                                }
                                                break;

                                            }
                                        case "MULTI_FIELD_INTERSECT":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: MULTI_FIELD_INTERSECT");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int popFldIdx = 0;
                                                    if (args.GetLength(0) > 2)
                                                    {
                                                        AAState.WriteLine("                  Parsing Valueinfo");

                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString().Trim();
                                                        string[] fieldsToPop = args[2].ToString().Split(',');
                                                        if (args.GetLength(0) == 4)
                                                        {
                                                            AAState.WriteLine("                  Search distance specified");

                                                            if (Globals.IsDouble(args[3]))
                                                            {
                                                                searchDistance = Convert.ToDouble(args[3]);
                                                            }
                                                            else
                                                            {
                                                                searchDistance = 0.0;
                                                            }
                                                        }
                                                        else
                                                        {

                                                            searchDistance = 0.0;
                                                        }

                                                        if (sourceFieldName != null)
                                                        {
                                                            AAState.WriteLine("                  Looping Through Layers");

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                if (fieldsToPop.Length == popFldIdx)
                                                                    break;

                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                                if (sourceLayerName != "")
                                                                {

                                                                    boolLayerOrFC = true;
                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0].Trim();
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                    }

                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                    }
                                                                    if (sourceLayer != null)
                                                                    {
                                                                        if (sourceLayer.FeatureClass != null)
                                                                        {
                                                                            sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);

                                                                            if (sourceField > -1)
                                                                            {

                                                                                sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, false);

                                                                                pFS = (IFeatureSelection)sourceLayer;
                                                                                if (boolLayerOrFC)
                                                                                {
                                                                                    if (pFS.SelectionSet.Count > 0)
                                                                                    {
                                                                                        pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                                        fCursor = cCurs as IFeatureCursor;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        fCursor = sourceLayer.Search(sFilter, true);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                }

                                                                                while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                                {
                                                                                    if (sourceFeature.Class != inFeature.Class)
                                                                                    {
                                                                                        if (fieldsToPop.Length == popFldIdx)
                                                                                            break;

                                                                                        string test = sourceFeature.get_Value(sourceField).ToString().Trim();

                                                                                        int tempFieldNum = Globals.GetFieldIndex(inObject.Fields, fieldsToPop[popFldIdx]);
                                                                                        popFldIdx++;
                                                                                        if (tempFieldNum > -1)
                                                                                        {
                                                                                            inObject.set_Value(tempFieldNum, sourceFeature.get_Value(sourceField));
                                                                                        }

                                                                                    }
                                                                                    else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                                    {
                                                                                        if (fieldsToPop.Length == popFldIdx)
                                                                                            break;

                                                                                        string test = sourceFeature.get_Value(sourceField).ToString().Trim();

                                                                                        int tempFieldNum = Globals.GetFieldIndex(inObject.Fields, fieldsToPop[popFldIdx]);
                                                                                        popFldIdx++;
                                                                                        if (tempFieldNum > -1)
                                                                                        {
                                                                                            inObject.set_Value(tempFieldNum, sourceFeature.get_Value(sourceField));
                                                                                        }

                                                                                    }
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Datasource is invalid: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer string is empty");

                                                                }
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field name is invalid");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Invalid Value method definition");

                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: MULTI_FIELD_INTERSECT: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: MULTI_FIELD_INTERSECT");
                                            }
                                            break;
                                        case "INTERSECT_STATS":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECT_STATS");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    //LayerToIntersect|Field To Elevate
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int AverageCount = 0;
                                                    if (args.GetLength(0) > 2)
                                                    {
                                                        AAState.WriteLine("                  Parsing Valueinfo");

                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString().Trim();
                                                        string statType = args[2].ToString().Trim();
                                                        if (args.GetLength(0) == 4)
                                                        {
                                                            AAState.WriteLine("                  Search distance specified");

                                                            if (Globals.IsDouble(args[3]))
                                                                searchDistance = Convert.ToDouble(args[3]);
                                                            else
                                                                searchDistance = 0.0;
                                                        }
                                                        else
                                                        {

                                                            searchDistance = 0.0;
                                                        }
                                                        double result = -999999.1;
                                                        string textRes = "";
                                                        if (sourceFieldName != null)
                                                        {
                                                            AAState.WriteLine("                  Looping Through Layers");

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {

                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                                if (sourceLayerName != "")
                                                                {
                                                                    boolLayerOrFC = true;
                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0].Trim();
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                    }

                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);
                                                                    }

                                                                    if (sourceLayer != null)
                                                                    {
                                                                        if (sourceLayer.FeatureClass != null)
                                                                        {
                                                                            sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);

                                                                            if (sourceField > -1)
                                                                            {

                                                                                sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, false);

                                                                                pFS = (IFeatureSelection)sourceLayer;
                                                                                if (boolLayerOrFC)
                                                                                {
                                                                                    if (pFS.SelectionSet.Count > 0)
                                                                                    {
                                                                                        pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                                        fCursor = cCurs as IFeatureCursor;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        fCursor = sourceLayer.Search(sFilter, true);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                }
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                while (sourceFeature != null)
                                                                                {
                                                                                    if (sourceFeature.Class != inFeature.Class)
                                                                                    {
                                                                                        string test = sourceFeature.get_Value(sourceField).ToString().Trim();
                                                                                        if (Globals.IsNumeric(test))
                                                                                        {

                                                                                            double valToTest = Convert.ToDouble(test);
                                                                                            if (result == -999999.1)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                switch (statType.ToUpper())
                                                                                                {
                                                                                                    case "MAX":
                                                                                                        if (result < valToTest)
                                                                                                        {
                                                                                                            result = valToTest;

                                                                                                        }
                                                                                                        break;
                                                                                                    case "MIN":
                                                                                                        if (result > valToTest)
                                                                                                        {
                                                                                                            result = valToTest;

                                                                                                        }
                                                                                                        break;
                                                                                                    case "SUM":
                                                                                                        result += valToTest;

                                                                                                        break;
                                                                                                    case "AVERAGE":
                                                                                                        result += valToTest;
                                                                                                        AverageCount++;
                                                                                                        break;
                                                                                                    case "MEAN":
                                                                                                        result += valToTest;
                                                                                                        AverageCount++;

                                                                                                        break;
                                                                                                    case "CONCAT":
                                                                                                        if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                                        {
                                                                                                        }
                                                                                                        else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                                        {
                                                                                                        }
                                                                                                        else
                                                                                                        {

                                                                                                            if (textRes == "")
                                                                                                            {
                                                                                                                textRes += valToTest.ToString();
                                                                                                            }
                                                                                                            else
                                                                                                            {
                                                                                                                textRes += ConcatDelim + valToTest.ToString();
                                                                                                            }

                                                                                                        }

                                                                                                        break;
                                                                                                    default:
                                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                                        break;
                                                                                                }

                                                                                            }
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            switch (statType.ToUpper())
                                                                                            {

                                                                                                case "CONCAT":
                                                                                                    if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                                    {
                                                                                                    }
                                                                                                    else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                                    {
                                                                                                    }
                                                                                                    else
                                                                                                    {

                                                                                                        if (textRes == "")
                                                                                                        {
                                                                                                            textRes += test;
                                                                                                        }
                                                                                                        else
                                                                                                        {
                                                                                                            textRes += ConcatDelim + test;
                                                                                                        }
                                                                                                    }

                                                                                                    break;
                                                                                                default:
                                                                                                    AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                                    AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                                    break;
                                                                                            }

                                                                                        }

                                                                                    }
                                                                                    else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                                    {
                                                                                        string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                        if (Globals.IsNumeric(test))
                                                                                        {

                                                                                            double valToTest = Convert.ToDouble(test);
                                                                                            if (result == -999999.1)
                                                                                            {
                                                                                                result = valToTest;

                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                switch (statType.ToUpper())
                                                                                                {
                                                                                                    case "MAX":
                                                                                                        if (result < valToTest)
                                                                                                        {
                                                                                                            result = valToTest;

                                                                                                        }
                                                                                                        break;
                                                                                                    case "MIN":
                                                                                                        if (result > valToTest)
                                                                                                        {
                                                                                                            result = valToTest;

                                                                                                        }
                                                                                                        break;
                                                                                                    case "SUM":
                                                                                                        result += valToTest;

                                                                                                        break;
                                                                                                    case "AVERAGE":
                                                                                                        result += valToTest;
                                                                                                        AverageCount++;
                                                                                                        break;
                                                                                                    case "MEAN":
                                                                                                        result += valToTest;
                                                                                                        AverageCount++;

                                                                                                        break;
                                                                                                    case "CONCAT":
                                                                                                        if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                                        {
                                                                                                        }
                                                                                                        else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                                        {
                                                                                                        }
                                                                                                        else
                                                                                                        {

                                                                                                            if (textRes == "")
                                                                                                            {
                                                                                                                textRes += valToTest.ToString();
                                                                                                            }
                                                                                                            else
                                                                                                            {
                                                                                                                textRes += ConcatDelim + valToTest.ToString();
                                                                                                            }

                                                                                                        }
                                                                                                        break;
                                                                                                    default:
                                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                                        break;
                                                                                                }

                                                                                            }
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            switch (statType.ToUpper())
                                                                                            {

                                                                                                case "CONCAT":
                                                                                                    if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                                    {
                                                                                                    }
                                                                                                    else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                                    {
                                                                                                    }
                                                                                                    else
                                                                                                    {

                                                                                                        if (textRes == "")
                                                                                                        {
                                                                                                            textRes += test;
                                                                                                        }
                                                                                                        else
                                                                                                        {
                                                                                                            textRes += ConcatDelim + test;
                                                                                                        }

                                                                                                    }
                                                                                                    break;
                                                                                                default:
                                                                                                    AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                                    AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                                    break;
                                                                                            }

                                                                                        }
                                                                                    }
                                                                                    sourceFeature = fCursor.NextFeature();

                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR/WARNING: Datasource is invalid: " + sourceLayerName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer string is empty");

                                                                }
                                                            }
                                                            try
                                                            {
                                                                if (textRes != "")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], textRes);
                                                                }
                                                                else if (result != -999999.1)
                                                                {
                                                                    if (AverageCount != 0)
                                                                    {
                                                                        result = result / AverageCount;
                                                                    }
                                                                    inObject.set_Value(intFldIdxs[0], result);

                                                                }
                                                                else
                                                                {
                                                                    IField field = inObject.Fields.get_Field(intFldIdxs[0]);
                                                                    object newval = field.DefaultValue;
                                                                    if (newval == null)
                                                                    {
                                                                        if (field.IsNullable)
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[0], null);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], newval);
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field name is invalid");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Invalid Value method definition");

                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECT_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECT_STATS");
                                            }
                                            break;
                                        case "FEATURE_STATS":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: FEATURE_STATS");
                                                if (inFeature != null & valData != null)
                                                {

                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    //LayerToIntersect|Field To Elevate
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    int AverageCount = 0;
                                                    if (args.GetLength(0) > 1)
                                                    {
                                                        AAState.WriteLine("                  Parsing Valueinfo");

                                                        string[] sourceFieldNames = args[0].ToString().Split(',');
                                                        string statType = args[1].ToString();

                                                        double result = -999999.1;
                                                        string textRes = "";
                                                        if (sourceFieldNames != null)
                                                        {
                                                            AAState.WriteLine("                  Looping Through Fields");

                                                            for (int i = 0; i < sourceFieldNames.Length; i++)
                                                            {

                                                                sourceFieldName = sourceFieldNames[i].ToString();
                                                                if (sourceFieldName != "")
                                                                {

                                                                    sourceField = Globals.GetFieldIndex(inObject.Fields, sourceFieldName);

                                                                    if (sourceField > -1)
                                                                    {
                                                                        string test = inObject.get_Value(sourceField).ToString();
                                                                        if (Globals.IsNumeric(test))
                                                                        {

                                                                            double valToTest = Convert.ToDouble(test);
                                                                            if (result == -999999.1)
                                                                            {
                                                                                result = valToTest;

                                                                            }
                                                                            else
                                                                            {
                                                                                switch (statType.ToUpper())
                                                                                {
                                                                                    case "MAX":
                                                                                        if (result < valToTest)
                                                                                        {
                                                                                            result = valToTest;

                                                                                        }
                                                                                        break;
                                                                                    case "MIN":
                                                                                        if (result > valToTest)
                                                                                        {
                                                                                            result = valToTest;

                                                                                        }
                                                                                        break;
                                                                                    case "SUM":
                                                                                        result += valToTest;

                                                                                        break;
                                                                                    case "AVERAGE":
                                                                                        result += valToTest;
                                                                                        AverageCount++;
                                                                                        break;
                                                                                    case "MEAN":
                                                                                        result += valToTest;
                                                                                        AverageCount++;

                                                                                        break;
                                                                                    case "CONCAT":
                                                                                        if (textRes.Contains(valToTest.ToString() + ConcatDelim))
                                                                                        {
                                                                                        }
                                                                                        else if (textRes.Contains(ConcatDelim + valToTest.ToString()))
                                                                                        {
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            if (textRes == "")
                                                                                            {
                                                                                                textRes += valToTest.ToString();
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                textRes += ConcatDelim + valToTest.ToString();
                                                                                            }
                                                                                        }

                                                                                        break;
                                                                                    default:
                                                                                        AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                        break;
                                                                                }

                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            switch (statType.ToUpper())
                                                                            {

                                                                                case "CONCAT":
                                                                                    if (textRes.Contains(test.ToString() + ConcatDelim))
                                                                                    {
                                                                                    }
                                                                                    else if (textRes.Contains(ConcatDelim + test.ToString()))
                                                                                    {
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        if (textRes == "")
                                                                                        {
                                                                                            textRes += test;
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            textRes += ConcatDelim + test;
                                                                                        }
                                                                                    }

                                                                                    break;
                                                                                default:
                                                                                    AAState.WriteLine("                  ERROR/WARNING: Non numeric value returned: " + test);

                                                                                    AAState.WriteLine("                  ERROR: Unsupported stat type: " + test);
                                                                                    break;
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                            }
                                                            try
                                                            {
                                                                if (textRes != "")
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], textRes);
                                                                }
                                                                else if (result != -999999.1)
                                                                {
                                                                    if (AverageCount != 0)
                                                                    {
                                                                        result = result / AverageCount;
                                                                    }
                                                                    inObject.set_Value(intFldIdxs[0], result);

                                                                }
                                                                else
                                                                {
                                                                    IField field = inObject.Fields.get_Field(intFldIdxs[0]);
                                                                    object newval = field.DefaultValue;
                                                                    if (newval == null)
                                                                    {
                                                                        if (field.IsNullable)
                                                                        {
                                                                            inObject.set_Value(intFldIdxs[0], null);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        inObject.set_Value(intFldIdxs[0], newval);
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: Field name is invalid");

                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Invalid Value method definition");

                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: FEATURE_STATS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: FEATURE_STATS");
                                            }
                                            break;
                                        case "INTERSECTING_EDGE":
                                            try
                                            {
                                                if (valData == null) break;
                                                args = valData.Split('|');
                                                switch (args.GetLength(0))
                                                {
                                                    case 1:
                                                        sourceFieldName = args[0].ToString();
                                                        break;
                                                    case 2:
                                                        sourceFieldName = args[1].ToString();
                                                        break;

                                                    default: break;
                                                }

                                                AAState.WriteLine("                  Trying: INTERSECTING_EDGE");

                                                if (inFeature != null)
                                                {
                                                    netFeat = inFeature as INetworkFeature;
                                                    AAState.WriteLine("                  Checking if it is a network feature");
                                                    if (netFeat != null)
                                                    {
                                                        AAState.WriteLine("                  Feature is a network feature");
                                                        if (inFeature.FeatureType == esriFeatureType.esriFTComplexJunction || inFeature.FeatureType == esriFeatureType.esriFTSimpleJunction)
                                                        {
                                                            AAState.WriteLine("                  Feature is a junction feature");
                                                            iJuncFeat = (IJunctionFeature)netFeat;

                                                            ISimpleJunctionFeature iSJunc = iJuncFeat as ISimpleJunctionFeature;
                                                            if (iSJunc == null)
                                                                break;
                                                            AAState.WriteLine("                  Edge Count: " + iSJunc.EdgeFeatureCount);
                                                            if (iSJunc.EdgeFeatureCount <= 0)
                                                                break;
                                                            if (iSJunc.EdgeFeatureCount > 0)
                                                            {
                                                                for (int i = 0; i < iSJunc.EdgeFeatureCount; i++)
                                                                {

                                                                    iEdgeFeat = iSJunc.get_EdgeFeature(i);
                                                                    try
                                                                    {

                                                                        IRow pRow = iEdgeFeat as IRow;

                                                                        // verify that field (in junction) to copy exists
                                                                        AAState.WriteLine("                  Getting Field From Edge");
                                                                        juncField = Globals.GetFieldIndex(pRow.Fields, sourceFieldName);
                                                                        string test = pRow.get_Value(juncField).ToString();
                                                                        AAState.WriteLine("                  Attempting to store: " + test);
                                                                        inObject.set_Value(intFldIdxs[0], test);
                                                                        continue;
                                                                    }
                                                                    catch
                                                                    {
                                                                    }
                                                                }//end loop
                                                                try
                                                                {

                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    AAState.WriteLine("                  ERROR: Value was not set on feature: " + ex.Message);

                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  No Connected Edges Found");
                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  not an junction feature");
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  Not a Geometric Network Feature");
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_EDGE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_EDGE");
                                            }
                                            break;
                                        case "INTERSECTING_FEATURE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_FEATURE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    AAState.WriteLine("                  Starting to process rule");
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;
                                                    found = false;
                                                    AAState.WriteLine("                  Value Info is: " + valData);
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    //if (args.GetLength(0) >= 2)
                                                    if (args.Length >= 2)
                                                    {
                                                        AAState.intersectOptions strOpt = AAState.intersectOptions.First;
                                                        switch (args.Length)
                                                        {
                                                            case 2:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                sourceFieldName = args[1].ToString();
                                                                break;
                                                            case 3:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                sourceFieldName = args[1].ToString();
                                                                switch (args[2].ToString().ToUpper())
                                                                {
                                                                    case "PROMPT":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "P":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "CENTROID":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "C":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "F":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                    case "L":
                                                                        strOpt = AAState.intersectOptions.Last;
                                                                        break;
                                                                    case "FIRST":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                }
                                                                break;
                                                            default: break;
                                                        }

                                                        if (sourceFieldName != null)
                                                        {
                                                            List<Globals.OptionsToPresent> pFoundFeat = new List<Globals.OptionsToPresent>();

                                                            for (int i = 0; i < sourceLayerNames.Length; i++)
                                                            {
                                                                sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                                if (sourceLayerName != "")
                                                                {
                                                                    boolLayerOrFC = true;

                                                                    if (sourceLayerName.Contains("("))
                                                                    {
                                                                        string[] tempSplt = sourceLayerName.Split('(');
                                                                        sourceLayerName = tempSplt[0].Trim();
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                                        if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }

                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                        {
                                                                            boolLayerOrFC = true;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }
                                                                        else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                        {
                                                                            boolLayerOrFC = false;
                                                                        }

                                                                    }
                                                                    else
                                                                    {
                                                                        sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                                    }
                                                                    // Get layer

                                                                    if (sourceLayer != null)
                                                                    {
                                                                        AAState.WriteLine("                  Layer Found: " + sourceLayer.Name);

                                                                        sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);
                                                                        AAState.WriteLine("                  " + sourceFieldName + ": at " + sourceField);
                                                                        if (sourceField > -1)
                                                                        {

                                                                            sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, strOpt == AAState.intersectOptions.Centroid);
                                                                            if (sFilter == null)
                                                                            {
                                                                                AAState.WriteLine("                  Filter is null, this will cause an error");
                                                                                continue;
                                                                            }

                                                                            pFS = (IFeatureSelection)sourceLayer;
                                                                            if (boolLayerOrFC)
                                                                            {
                                                                                AAState.WriteLine("                  Searching on Layer");
                                                                                if (pFS.SelectionSet.Count > 0)
                                                                                {
                                                                                    AAState.WriteLine("                  Searching on Selection Set");
                                                                                    pFS.SelectionSet.Search(sFilter, true, out cCurs);

                                                                                    fCursor = cCurs as IFeatureCursor;

                                                                                    AAState.WriteLine("                  Cursor created");
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  No Selected Features");
                                                                                    fCursor = sourceLayer.Search(sFilter, true);
                                                                                    AAState.WriteLine("                  Cursor created");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Searching on feature Class");
                                                                                fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                AAState.WriteLine("                  Cursor created");
                                                                            }
                                                                            if (fCursor == null)
                                                                            {
                                                                                AAState.WriteLine("                  Cursor is null");
                                                                                continue;
                                                                            }
                                                                            AAState.WriteLine("                  Starting Loop of found features");
                                                                            while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                            {
                                                                                AAState.WriteLine("                  Checking Class");
                                                                                if (sourceFeature.Class != inFeature.Class)
                                                                                {
                                                                                    AAState.WriteLine("                  Different FCs");
                                                                                    if (strOpt == AAState.intersectOptions.PromptMulti)
                                                                                    {

                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);
                                                                                    }
                                                                                    else if (strOpt == AAState.intersectOptions.Last)
                                                                                    {

                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);
                                                                                    }

                                                                                    else
                                                                                    {
                                                                                        string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                        AAState.WriteLine("                  Setting Value: " + test);
                                                                                        inObject.set_Value(intFldIdxs[0], sourceFeature.get_Value(sourceField));
                                                                                        AAState.WriteLine("                  Value Set");
                                                                                        found = true;
                                                                                    }
                                                                                }
                                                                                else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                                {
                                                                                    AAState.WriteLine("                  Same FC");
                                                                                    if (strOpt == AAState.intersectOptions.PromptMulti)
                                                                                    {
                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);
                                                                                    }
                                                                                    else if (strOpt == AAState.intersectOptions.Last)
                                                                                    {
                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                        AAState.WriteLine("                  Setting Value: " + test);

                                                                                        inObject.set_Value(intFldIdxs[0], sourceFeature.get_Value(sourceField));
                                                                                        AAState.WriteLine("                  Value Set");

                                                                                        found = true;
                                                                                    }
                                                                                }
                                                                                if (found == true)
                                                                                    break;

                                                                            }

                                                                            if (found == false && AAState._CheckEnvelope && pFoundFeat.Count == 0)
                                                                            {
                                                                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects;

                                                                                pFS = (IFeatureSelection)sourceLayer;
                                                                                if (boolLayerOrFC)
                                                                                {
                                                                                    if (pFS.SelectionSet.Count > 0)
                                                                                    {
                                                                                        pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                                        fCursor = cCurs as IFeatureCursor;

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        fCursor = sourceLayer.Search(sFilter, true);
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                                }
                                                                                sourceFeature = fCursor.NextFeature();
                                                                                while (sourceFeature != null)
                                                                                {
                                                                                    if (strOpt == AAState.intersectOptions.PromptMulti)
                                                                                    {
                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);

                                                                                    }
                                                                                    else if (strOpt == AAState.intersectOptions.Last)
                                                                                    {
                                                                                        Globals.OptionsToPresent pOp = new Globals.OptionsToPresent();
                                                                                        pOp.Display = sourceFeature.get_Value(Globals.GetFieldIndex(sourceFeature.Fields, sourceLayer.DisplayField)).ToString();
                                                                                        if (pOp.Display.Trim() != "")
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + pOp.Display;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            pOp.Display = sourceLayer.Name + ": " + sourceFeature.OID;

                                                                                        }
                                                                                        pOp.OID = sourceFeature.OID;
                                                                                        pOp.LayerName = sourceLayer.Name;

                                                                                        pFoundFeat.Add(pOp);

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        if (found)
                                                                                        {
                                                                                            break;
                                                                                        }
                                                                                        string test = sourceFeature.get_Value(sourceField).ToString();
                                                                                        AAState.WriteLine("                  Setting Value: " + test);

                                                                                        inObject.set_Value(intFldIdxs[0], sourceFeature.get_Value(sourceField));
                                                                                        AAState.WriteLine("                  Value Set");

                                                                                        found = true;

                                                                                    }
                                                                                    sourceFeature = fCursor.NextFeature();
                                                                                }

                                                                            }

                                                                            if (found)
                                                                            {
                                                                                break;
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  ERROR: Source field not found: " + sourceFieldName);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                    }
                                                                }

                                                            }
                                                            if (pFoundFeat.Count > 0 && strOpt == AAState.intersectOptions.PromptMulti)
                                                            {
                                                                Globals.OptionsToPresent strRetVal = Globals.showOptionsForm(pFoundFeat, "Select A feature for " + sourceFieldName, "Select A feature for " + sourceFieldName, ComboBoxStyle.DropDownList);
                                                                if (strRetVal != null)
                                                                {
                                                                    sourceFeature = sourceLayer.FeatureClass.GetFeature(strRetVal.OID);

                                                                    string test = sourceFeature.get_Value(sourceField).ToString();
                                                                    AAState.WriteLine("                  Setting Value: " + test);

                                                                    inObject.set_Value(intFldIdxs[0], sourceFeature.get_Value(sourceField));
                                                                    AAState.WriteLine("                  Value Set");

                                                                    found = true;

                                                                }
                                                            }
                                                            else if (pFoundFeat.Count > 0 && strOpt == AAState.intersectOptions.Last)
                                                            {

                                                                sourceFeature = sourceLayer.FeatureClass.GetFeature(pFoundFeat[pFoundFeat.Count - 1].OID);

                                                                string test = sourceFeature.get_Value(sourceField).ToString();
                                                                AAState.WriteLine("                  Setting Value: " + test);

                                                                inObject.set_Value(intFldIdxs[0], sourceFeature.get_Value(sourceField));
                                                                AAState.WriteLine("                  Value Set");

                                                                found = true;

                                                            }

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE: source field name is null");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE: Value Info is not in the expected format");
                                                    }
                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE: Input Feature or Value Info is null");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_FEATURE");
                                            }
                                            break;
                                        case "INTERSECTING_BOOLEAN":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_BOOLEAN");
                                                if (inFeature != null & valData != null)
                                                {
                                                    AAState.WriteLine("                  Starting to process rule");
                                                    sourceLayerName = "";
                                                    string valTrue = "";
                                                    string valFalse = "";

                                                    found = false;
                                                    AAState.WriteLine("                  Value Info is: " + valData);
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    //if (args.GetLength(0) >= 2)
                                                    if (args.Length == 3)
                                                    {
                                                        AAState.intersectOptions strOpt = AAState.intersectOptions.First;
                                                        switch (args.Length)
                                                        {

                                                            case 3:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                valTrue = args[1].ToString();
                                                                valFalse = args[2].ToString();

                                                                break;
                                                            default: break;
                                                        }

                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                            if (sourceLayerName != "")
                                                            {
                                                                boolLayerOrFC = true;

                                                                if (sourceLayerName.Contains("("))
                                                                {
                                                                    string[] tempSplt = sourceLayerName.Split('(');
                                                                    sourceLayerName = tempSplt[0].Trim();
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                                    if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                    {
                                                                        boolLayerOrFC = true;
                                                                    }

                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                    {
                                                                        boolLayerOrFC = true;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }
                                                                    else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                    {
                                                                        boolLayerOrFC = false;
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                                }
                                                                // Get layer

                                                                if (sourceLayer != null)
                                                                {
                                                                    AAState.WriteLine("                  Layer Found: " + sourceLayer.Name);

                                                                    sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, strOpt == AAState.intersectOptions.Centroid);
                                                                    if (sFilter == null)
                                                                    {
                                                                        AAState.WriteLine("                  Filter is null, this will cause an error");
                                                                        continue;
                                                                    }

                                                                    pFS = (IFeatureSelection)sourceLayer;
                                                                    if (boolLayerOrFC)
                                                                    {
                                                                        AAState.WriteLine("                  Searching on Layer");
                                                                        if (pFS.SelectionSet.Count > 0)
                                                                        {
                                                                            AAState.WriteLine("                  Searching on Selection Set");
                                                                            pFS.SelectionSet.Search(sFilter, true, out cCurs);

                                                                            fCursor = cCurs as IFeatureCursor;

                                                                            AAState.WriteLine("                  Cursor created");
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  No Selected Features");
                                                                            fCursor = sourceLayer.Search(sFilter, true);
                                                                            AAState.WriteLine("                  Cursor created");
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  Searching on feature Class");
                                                                        fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                        AAState.WriteLine("                  Cursor created");
                                                                    }
                                                                    if (fCursor == null)
                                                                    {
                                                                        AAState.WriteLine("                  Cursor is null");
                                                                        continue;
                                                                    }
                                                                    AAState.WriteLine("                  Starting Loop of found features");
                                                                    while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                    {
                                                                        AAState.WriteLine("                  Checking Class");
                                                                        if (sourceFeature.Class != inFeature.Class)
                                                                        {
                                                                            AAState.WriteLine("                  Different FCs");

                                                                            found = true;

                                                                        }
                                                                        else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                        {
                                                                            AAState.WriteLine("                  Same FC");

                                                                            found = true;

                                                                        }
                                                                        if (found == true)
                                                                            break;

                                                                    }

                                                                    if (found == false && AAState._CheckEnvelope)
                                                                    {
                                                                        sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects;

                                                                        pFS = (IFeatureSelection)sourceLayer;
                                                                        if (boolLayerOrFC)
                                                                        {
                                                                            if (pFS.SelectionSet.Count > 0)
                                                                            {
                                                                                pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                                fCursor = cCurs as IFeatureCursor;

                                                                            }
                                                                            else
                                                                            {
                                                                                fCursor = sourceLayer.Search(sFilter, true);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                        }
                                                                        sourceFeature = fCursor.NextFeature();
                                                                        while (sourceFeature != null)
                                                                        {

                                                                            found = true;
                                                                            break;

                                                                        }

                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                                }

                                                                if (found)
                                                                {
                                                                    break;
                                                                }

                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR/WARNING: Source Layer not found: " + sourceLayerName);
                                                            }

                                                        }

                                                        if (found)
                                                        {

                                                            AAState.WriteLine("                  Setting Value: " + valTrue);

                                                            inObject.set_Value(intFldIdxs[0], valTrue);
                                                            AAState.WriteLine("                  Value Set");

                                                        }
                                                        else
                                                        {
                                                            AAState.WriteLine("                  Setting Value: " + valFalse);

                                                            inObject.set_Value(intFldIdxs[0], valFalse);
                                                            AAState.WriteLine("                  Value Set");

                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: INTERSECTING_BOOLEAN: Value Info is not in the expected format");
                                                    }

                                                }
                                                else
                                                {
                                                    AAState.WriteLine("                  ERROR: INTERSECTING_BOOLEAN: Input Feature or Value Info is null");
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_BOOLEAN: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_BOOLEAN");
                                            }
                                            break;
                                        case "INTERSECTING_RASTER":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_RASTER");
                                                if (inFeature != null & valData != null)
                                                {

                                                    sourceLayerName = "";
                                                    formatString = "";
                                                    found = false;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.Length < 1) break;
                                                    switch (args.Length)
                                                    {
                                                        case 1:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            break;
                                                        case 2:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            formatString = args[1].ToString();
                                                            break;
                                                        default: break;
                                                    }

                                                    // Get layer
                                                    for (int i = 0; i < sourceLayerNames.Length; i++)
                                                    {
                                                        sourceLayerName = sourceLayerNames[i].ToString().Trim();
                                                        IPoint pLoc = Globals.GetGeomCenter(inFeature)[0];

                                                        if (pLoc != null)
                                                        {
                                                            string cellVal = Globals.GetCellValue(sourceLayerName, pLoc, AAState._editor.Map);
                                                            AAState.WriteLine("                  ERROR/WARING: No cell value or raster was found: " + sourceLayerName);
                                                            if (cellVal != null && cellVal != "" && cellVal != "No Raster")
                                                            {

                                                                if (formatString == null || formatString == "" || (inObject.Fields.get_Field(intFldIdxs[0]).Type != esriFieldType.esriFieldTypeString))
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], cellVal);
                                                                    found = true;
                                                                    break;
                                                                }
                                                                else
                                                                {
                                                                    formatString = formatString + cellVal;
                                                                    inObject.set_Value(intFldIdxs[0], formatString);

                                                                    found = true;
                                                                    break;
                                                                }

                                                            }

                                                        }
                                                    }
                                                    if (!(found) && inObject.Fields.get_Field(intFldIdxs[0]).IsNullable)
                                                        inObject.set_Value(intFldIdxs[0], null);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_RASTER: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_RASTER");
                                            }
                                            break;
                                        case "INTERSECTING_LAYER_DETAILS":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_LAYER_DETAILS");
                                                if (inFeature != null & valData != null)
                                                {

                                                    sourceLayerName = "";
                                                    formatString = "";
                                                    found = false;
                                                    List<string> matchPattern = null;
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.Length >= 1)
                                                    {
                                                        AAState.intersectOptions strOpt = AAState.intersectOptions.First;

                                                        switch (args.Length)
                                                        {
                                                            case 1:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                formatString = "P";
                                                                break;
                                                            case 2:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                formatString = args[1].ToString();
                                                                break;
                                                            case 3:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                formatString = args[1].ToString();
                                                                switch (args[2].ToString().ToUpper())
                                                                {
                                                                    case "PROMPT":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "P":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "CENTROID":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "C":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "F":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                    case "FIRST":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                }
                                                                break;
                                                            case 4:
                                                                sourceLayerNames = args[0].ToString().Split(',');
                                                                formatString = args[1].ToString();
                                                                switch (args[2].ToString().ToUpper())
                                                                {
                                                                    case "PROMPT":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "P":
                                                                        strOpt = AAState.intersectOptions.PromptMulti;
                                                                        break;
                                                                    case "CENTROID":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "C":
                                                                        strOpt = AAState.intersectOptions.Centroid;
                                                                        break;
                                                                    case "F":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                    case "FIRST":
                                                                        strOpt = AAState.intersectOptions.First;
                                                                        break;
                                                                }
                                                                matchPattern = new List<string>(args[3].ToString().Split(','));

                                                                break;
                                                            default: break;

                                                        }
                                                        List<Globals.OptionsToPresent> strFiles = new List<Globals.OptionsToPresent>();
                                                        // Get layer
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString().Trim();

                                                            IGeometry pGeo = inFeature.ShapeCopy;
                                                            List<IGeometry> pGeos = new List<IGeometry>();

                                                            if (pGeo != null)
                                                            {
                                                                if (strOpt == AAState.intersectOptions.Centroid)
                                                                {
                                                                    List<IPoint> pGeoPnts = Globals.GetGeomCenter(pGeo);
                                                                    pGeos = pGeoPnts.ConvertAll(new Converter<IPoint, IGeometry>(Globals.PointToGeometry));

                                                                }
                                                                else
                                                                {
                                                                    pGeos.Add(pGeo);
                                                                }
                                                                AAState.WriteLine("                  Getting list of " + sourceLayerName + " Layers");
                                                                IEnumLayer pEnum = Globals.GetLayers(AAState._editor.Map, sourceLayerName);

                                                                if (pEnum != null)
                                                                {
                                                                    AAState.WriteLine("                  List retrieved of " + sourceLayerName + " Layers");
                                                                    AAState.WriteLine("                  Starting Loop");
                                                                    ILayer pLay = pEnum.Next();

                                                                    while (pLay != null)
                                                                    {

                                                                        intersectLayerDetailsFunctions(pLay, pGeos, strOpt, ref found, ref strFiles, ref inObject, intFldIdxs[0], matchPattern);

                                                                        if (found)
                                                                        {
                                                                            AAState.WriteLine("                  Exiting Layer Loop");
                                                                            break;
                                                                        }

                                                                        pLay = pEnum.Next();
                                                                    }
                                                                    pLay = null;
                                                                    pEnum = null;
                                                                }
                                                                else
                                                                {
                                                                    bool FCorLayerTemp = true;
                                                                    ILayer pLay = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref FCorLayerTemp);
                                                                    if (pLay != null)
                                                                    {

                                                                        intersectLayerDetailsFunctions(pLay, pGeos, strOpt, ref found, ref strFiles, ref inObject, intFldIdxs[0], matchPattern);

                                                                    }
                                                                    pLay = null;
                                                                }

                                                                if (pEnum != null)
                                                                    Marshal.ReleaseComObject(pEnum);
                                                                pEnum = null;
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Geo not Found");
                                                            }
                                                            if (found)
                                                            {
                                                                AAState.WriteLine("                  Exiting Layer Loop");
                                                                break;
                                                            }
                                                            pGeo = null;
                                                            pGeos = null;
                                                        }
                                                        if (strOpt == AAState.intersectOptions.PromptMulti && strFiles.Count > 0)
                                                        {
                                                            Globals.OptionsToPresent strRetVal = Globals.showOptionsForm(strFiles, "Select a intersect layer for " + strFldNames[0], "Select a intersect layer" + strFldNames[0], ComboBoxStyle.DropDownList);
                                                            if (strRetVal != null)
                                                            {
                                                                try
                                                                {
                                                                    inObject.set_Value(intFldIdxs[0], strRetVal.Display);
                                                                }
                                                                catch
                                                                {
                                                                    MessageBox.Show("Error Setting the value in the Intersecting_Layer_Details");

                                                                }
                                                                found = true;
                                                            }
                                                        }

                                                    }
                                                    else
                                                    {
                                                        AAState.WriteLine("                  ERROR: Value info is not correct");
                                                    }

                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_LAYER_DETAILS: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_LAYER_DETAILS");
                                            }
                                            break;
                                        case "INTERSECTING_FEATURE_DISTANCE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: INTERSECTING_FEATURE_DISTANCE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    sourceField = -1;

                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    if (args.GetLength(0) >= 2)
                                                    {

                                                        sourceLayerNames = args[0].ToString().Split(',');
                                                        sourceFieldName = args[1].ToString().Trim();
                                                    }
                                                    // Get layer

                                                    if (sourceFieldName != null)
                                                    {
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString();
                                                            if (sourceLayerName != "")

                                                                sourceLayerName = args[i].ToString();
                                                            if (i == 0)
                                                                i++;
                                                            boolLayerOrFC = true;

                                                            if (sourceLayerName.Contains("("))
                                                            {
                                                                string[] tempSplt = sourceLayerName.Split('(');
                                                                sourceLayerName = tempSplt[0];
                                                                sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                                if (tempSplt[1].ToUpper().Contains("LAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURELAYER)"))
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURECLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("CLASS)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else if (tempSplt[1].ToUpper().Contains("FEATURE)"))
                                                                {
                                                                    boolLayerOrFC = false;
                                                                }
                                                                else
                                                                {
                                                                    boolLayerOrFC = true;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                sourceLayer = (IFeatureLayer)Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref boolLayerOrFC);

                                                            }
                                                            if (sourceLayer == null)
                                                            {
                                                                AAState.WriteLine("                  ERROR/WARNING: " + sourceLayerName + " was not found");
                                                                continue;
                                                            }

                                                            IFeatureClass iFC = inFeature.Class as IFeatureClass;
                                                            if (sourceLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                                                            {
                                                                AAState.WriteLine("                  ERROR: " + sourceLayer + " is a polygon layer");

                                                                break;
                                                            }
                                                            if (sourceLayer != null)
                                                            {
                                                                sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);

                                                                if (sourceField > -1)
                                                                {
                                                                    sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, false);

                                                                    pFS = (IFeatureSelection)sourceLayer;
                                                                    if (boolLayerOrFC)
                                                                    {
                                                                        if (pFS.SelectionSet.Count > 0)
                                                                        {
                                                                            pFS.SelectionSet.Search(sFilter, true, out cCurs);
                                                                            fCursor = cCurs as IFeatureCursor;

                                                                        }
                                                                        else
                                                                        {
                                                                            fCursor = sourceLayer.Search(sFilter, true);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        fCursor = sourceLayer.FeatureClass.Search(sFilter, true);
                                                                    }

                                                                    while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                    {
                                                                        if (sourceFeature.Class != inFeature.Class)
                                                                        {
                                                                            IPoint pIntPnt;
                                                                            if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                                            {
                                                                                pIntPnt = Globals.GetIntersection(inFeature.ShapeCopy, sourceFeature.ShapeCopy as IPolyline) as IPoint;

                                                                            }
                                                                            else
                                                                                pIntPnt = inFeature.ShapeCopy as IPoint;
                                                                            IPoint snapPnt = null;

                                                                            double dAlong = Globals.PointDistanceOnLine(pIntPnt, sourceFeature.Shape as IPolyline, 2, out snapPnt);
                                                                            snapPnt = null;

                                                                            string strUnit = Globals.GetSpatRefUnitName(Globals.GetLayersCoordinateSystem(sourceLayer.FeatureClass), true);
                                                                            if (strUnit == "Foot" && dAlong != 1)
                                                                            {
                                                                                strUnit = "Feet";
                                                                            }
                                                                            else if (strUnit == "Meter" && dAlong != 1)
                                                                            {
                                                                                strUnit = "Meters";
                                                                            }
                                                                            string strDis = dAlong + " " + strUnit + " along " + sourceLayer.Name + " with " + sourceLayer.FeatureClass.Fields.get_Field(sourceField).AliasName + " of " + sourceFeature.get_Value(sourceField);

                                                                            if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                            {

                                                                                strDis = dAlong + " " + strUnit + ": " + sourceFeature.get_Value(sourceField);
                                                                                AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);

                                                                                if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                {

                                                                                    if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                    {
                                                                                        strDis = dAlong.ToString();
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    strDis = dAlong.ToString();
                                                                                    AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);
                                                                                    if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                    {
                                                                                        strDis = dAlong.ToString();
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Value set to: " + strDis);
                                                                                inObject.set_Value(intFldIdxs[0], strDis);
                                                                                break;
                                                                            }
                                                                        }

                                                                        else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                        {
                                                                            IPoint pIntPnt;
                                                                            if (inFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
                                                                            {
                                                                                pIntPnt = Globals.GetIntersection(inFeature.ShapeCopy, sourceFeature.ShapeCopy as IPolyline) as IPoint;

                                                                            }
                                                                            else
                                                                                pIntPnt = inFeature.ShapeCopy as IPoint;
                                                                            IPoint snapPnt = null;

                                                                            double dAlong = Globals.PointDistanceOnLine(pIntPnt, sourceFeature.Shape as IPolyline, 2, out snapPnt);
                                                                            snapPnt = null;

                                                                            string strUnit = Globals.GetSpatRefUnitName(Globals.GetLayersCoordinateSystem(sourceLayer.FeatureClass), true);
                                                                            if (strUnit == "Foot" && dAlong != 1)
                                                                            {
                                                                                strUnit = "Feet";
                                                                            }
                                                                            else if (strUnit == "Meter" && dAlong != 1)
                                                                            {
                                                                                strUnit = "Meters";
                                                                            }
                                                                            string strDis = dAlong + " " + strUnit + " along " + sourceLayer.Name + " with " + sourceLayer.FeatureClass.Fields.get_Field(sourceField).AliasName + " of " + sourceFeature.get_Value(sourceField);

                                                                            if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                            {

                                                                                strDis = dAlong + " " + strUnit + ": " + sourceFeature.get_Value(sourceField);
                                                                                AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);

                                                                                if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                {

                                                                                    if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                    {
                                                                                        strDis = dAlong.ToString();
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    strDis = dAlong.ToString();
                                                                                    AAState.WriteLine("                  Text is to long, defaulting to length along: " + strDis);
                                                                                    if (inObject.Fields.get_Field(intFldIdxs[0]).Length < strDis.Length - 1)
                                                                                    {
                                                                                        strDis = dAlong.ToString();
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        inObject.set_Value(intFldIdxs[0], strDis);
                                                                                        break;
                                                                                    }
                                                                                }

                                                                            }
                                                                            else
                                                                            {
                                                                                AAState.WriteLine("                  Value set to: " + strDis);
                                                                                inObject.set_Value(intFldIdxs[0], strDis);
                                                                                break;
                                                                            }
                                                                        }
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayer + ": field: " + sourceFieldName + " was not found");
                                                                }
                                                            }
                                                            else { }
                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: INTERSECTING_FEATURE_DISTANCE: " + ex.Message);
                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: INTERSECTING_FEATURE_DISTANCE");
                                            }
                                            break;

                                        //Release: 1.2
                                        //New Dynamic Value Method: NEARSET_FEATURE - similiar to INTERSECTING_FEATURE but requires a search distance.

                                        case "NEAREST_FEATURE":
                                            try
                                            {
                                                AAState.WriteLine("                  Trying: NEAREST_FEATURE");
                                                if (inFeature != null & valData != null)
                                                {
                                                    string sourceMatField = "";
                                                    string targetMatField = "";
                                                    sourceLayerName = "";
                                                    sourceFieldName = "";
                                                    searchDistance = 0;
                                                    found = false;
                                                    // Parse arguments
                                                    args = valData.Split('|');
                                                    switch (args.Length)
                                                    {
                                                        case 2:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            sourceFieldName = args[1].ToString();
                                                            break;
                                                        case 3:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            sourceFieldName = args[1].ToString();

                                                            Double.TryParse(args[2], out searchDistance);
                                                            break;
                                                        case 4:
                                                            AAState.WriteLine("                  ERROR: Incorrect value method");
                                                            break;

                                                        case 5:
                                                            sourceLayerNames = args[0].ToString().Split(',');
                                                            sourceFieldName = args[1].ToString();
                                                            Double.TryParse(args[2], out searchDistance);
                                                            sourceMatField = args[3].ToString();
                                                            targetMatField = args[4].ToString();
                                                            break;
                                                        default:
                                                            AAState.WriteLine("                  ERROR: Incorrect value method");
                                                            break;

                                                    }

                                                    if (sourceLayerNames.Length > 0 & sourceFieldName != null)
                                                    {
                                                        for (int i = 0; i < sourceLayerNames.Length; i++)
                                                        {
                                                            sourceLayerName = sourceLayerNames[i].ToString();
                                                            if (sourceLayerName != "")
                                                            {
                                                                bool FCorLayerSource = true;
                                                                sourceLayer = Globals.FindLayer(AAState._editor.Map, sourceLayerName, ref FCorLayerSource) as IFeatureLayer;
                                                                if (sourceLayer != null)
                                                                {
                                                                    sourceField = Globals.GetFieldIndex(sourceLayer.FeatureClass.Fields, sourceFieldName);

                                                                    if (sourceField > -1)
                                                                    {

                                                                        sFilter = Globals.createSpatialFilter(sourceLayer, inFeature, searchDistance, false);
                                                                        pFS = (IFeatureSelection)sourceLayer;
                                                                        if (boolLayerOrFC)
                                                                        {
                                                                            AAState.WriteLine("                  Searching the layer");
                                                                            if (pFS.SelectionSet.Count > 0)
                                                                            {
                                                                                AAState.WriteLine("                  There is a seleciton set, only checking selected features");
                                                                                pFS.SelectionSet.Search(sFilter, false, out cCurs);
                                                                                fCursor = cCurs as IFeatureCursor;

                                                                            }
                                                                            else
                                                                            {

                                                                                fCursor = sourceLayer.Search(sFilter, false);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            AAState.WriteLine("                  Searching the feature class");
                                                                            fCursor = sourceLayer.FeatureClass.Search(sFilter, false);
                                                                        }

                                                                        nearestFeature = null;

                                                                        proxOp = (IProximityOperator)inFeature.ShapeCopy;
                                                                        lastDistance = searchDistance;
                                                                        while ((sourceFeature = fCursor.NextFeature()) != null)
                                                                        {
                                                                            if (sourceFeature.Class != inFeature.Class)
                                                                            {
                                                                                AAState.WriteLine("                  Feature Classes are different");
                                                                                if (targetMatField == "" && sourceMatField == "")
                                                                                {

                                                                                    AAState.WriteLine("                  No matching fields specified");
                                                                                    try
                                                                                    {
                                                                                        IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                        pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                        distance = proxOp.ReturnDistance(pTempGeo);
                                                                                        pTempGeo = null;

                                                                                        if (distance <= lastDistance)
                                                                                        {
                                                                                            nearestFeature = sourceFeature;
                                                                                            lastDistance = distance;
                                                                                        }
                                                                                        pTempGeo = null;
                                                                                    }
                                                                                    catch
                                                                                    {
                                                                                        MessageBox.Show("Error in the Nearest Feature - Proximity Operator.  This may be caused by corrupt data in the layer, Please run Check/Repair Geometry GP tool on your layer");
                                                                                        return false;

                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  matching fields specified");
                                                                                    int idxTargetFld = Globals.GetFieldIndex(sourceLayer, targetMatField);
                                                                                    int idxSourceFld = Globals.GetFieldIndex(inObject.Fields, sourceMatField);
                                                                                    if (idxSourceFld >= 0 && idxTargetFld >= 0)
                                                                                    {
                                                                                        AAState.WriteLine("                  Fields Found");
                                                                                        if (inObject.get_Value(idxSourceFld).ToString() == sourceFeature.get_Value(idxTargetFld).ToString())
                                                                                        {
                                                                                            AAState.WriteLine("                  Values Match");
                                                                                            IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                            pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                            distance = proxOp.ReturnDistance(pTempGeo);
                                                                                            pTempGeo = null;

                                                                                            if (distance <= lastDistance)
                                                                                            {
                                                                                                nearestFeature = sourceFeature;
                                                                                                lastDistance = distance;
                                                                                            }
                                                                                            pTempGeo = null;

                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            AAState.WriteLine("                  Values does not Match: " + inObject.get_Value(idxSourceFld).ToString() + " - " + sourceFeature.get_Value(idxTargetFld).ToString());

                                                                                        }

                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        AAState.WriteLine("                  Fields Not Found");
                                                                                        IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                        pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                        distance = proxOp.ReturnDistance(pTempGeo);
                                                                                        pTempGeo = null;

                                                                                        if (distance <= lastDistance)
                                                                                        {
                                                                                            nearestFeature = sourceFeature;
                                                                                            lastDistance = distance;
                                                                                        }
                                                                                        pTempGeo = null;

                                                                                    }

                                                                                }
                                                                            }
                                                                            else if (sourceFeature.Class == inFeature.Class && sourceFeature.OID != inFeature.OID)
                                                                            {
                                                                                AAState.WriteLine("                  matching fields specified");
                                                                                int idxTargetFld = Globals.GetFieldIndex(sourceLayer, targetMatField);
                                                                                int idxSourceFld = Globals.GetFieldIndex(inObject.Fields, sourceMatField);
                                                                                if (idxSourceFld >= 0 && idxTargetFld >= 0)
                                                                                {
                                                                                    AAState.WriteLine("                  Fields Found");
                                                                                    if (inObject.get_Value(idxSourceFld).ToString() == sourceFeature.get_Value(idxTargetFld).ToString())
                                                                                    {
                                                                                        AAState.WriteLine("                  Values Match");
                                                                                        IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                        pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                        distance = proxOp.ReturnDistance(pTempGeo);
                                                                                        pTempGeo = null;

                                                                                        if (distance <= lastDistance)
                                                                                        {
                                                                                            nearestFeature = sourceFeature;
                                                                                            lastDistance = distance;
                                                                                        }
                                                                                        pTempGeo = null;

                                                                                    }

                                                                                }
                                                                                else
                                                                                {
                                                                                    AAState.WriteLine("                  Fields Not Found");
                                                                                    IGeometry pTempGeo = sourceFeature.ShapeCopy;
                                                                                    pTempGeo.Project(inFeature.Shape.SpatialReference);

                                                                                    distance = proxOp.ReturnDistance(pTempGeo);
                                                                                    pTempGeo = null;

                                                                                    if (distance <= lastDistance)
                                                                                    {
                                                                                        nearestFeature = sourceFeature;
                                                                                        lastDistance = distance;
                                                                                    }
                                                                                    pTempGeo = null;
                                                                                }

                                                                            }

                                                                        }

                                                                        if (nearestFeature != null)
                                                                        {
                                                                            AAState.WriteLine("                  Feature found: " + nearestFeature.Class.AliasName + ":" + nearestFeature.OID);
                                                                            inObject.set_Value(intFldIdxs[0], nearestFeature.get_Value(sourceField));
                                                                            found = true;
                                                                            break;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        AAState.WriteLine("                  ERROR: " + sourceLayer + ": field: " + sourceFieldName + " was not found");
                                                                    }

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                  ERROR: " + sourceLayer + " was not found");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                AAState.WriteLine("                  ERROR: Empty source layer name");
                                                            }

                                                        }
                                                        if (!found)
                                                        {

                                                        }
                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                AAState.WriteLine("                  ERROR: NEAREST_FEATURE: " + ex.Message);

                                            }
                                            finally
                                            {
                                                AAState.WriteLine("                  Finished: NEAREST_FEATURE");
                                            }
                                            break;

                                        default:
                                            AAState.WriteLine("ERROR: " + valMethod + " for layer " + tableName + " is not a valid method, check the dynamic value table");

                                            break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("TableName:" + tableName + "  FieldName:" + strFldNames[0] + System.Environment.NewLine + "ValueMethod:" + valMethod + "  ValueData:" + valData + System.Environment.NewLine + "Message: " + ex.Message, "Attribute Assistant Message");
                                    AAState.WriteLine("ERROR: TableName:" + tableName + "  FieldName:" + strFldNames[0] + System.Environment.NewLine + "ValueMethod:" + valMethod + "  ValueData:" + valData + System.Environment.NewLine + "Message: " + ex.Message);
                                }
                            }
                            else
                            {
                                AAState.WriteLine("      Rule not processed");

                            }

                            try
                            {
                                if (intFldIdxs.Count > 0 && strFldNames.Count > 0)
                                {
                                    for (int p = 0; p < strFldNames.Count; p++)
                                    {

                                        IRowChanges inChanges = inObject as IRowChanges;
                                        bool changed = inChanges.get_ValueChanged(intFldIdxs[p]);
                                        if (changed)
                                            try
                                            {
                                                if (AAState.lastValueProperties.GetProperty(strFldNames[p]) != null)
                                                {
                                                    LastValueEntry lstVal = AAState.lastValueProperties.GetProperty(strFldNames[p]) as LastValueEntry;
                                                    if (lstVal != null)
                                                    {
                                                        if (mode == "ON_CREATE" && lstVal.On_Create == false)
                                                        {
                                                            string test = "";
                                                        }
                                                        else if (mode == "ON_MANUAL" && lstVal.On_Manual == false)
                                                        {
                                                            string test = "";
                                                        }
                                                        else if (mode == "ON_CHANGE" && lstVal.On_ChangeAtt == false)
                                                        {
                                                            string test = "";
                                                        }
                                                        else if (mode == "ON_CHANGEGEO" && lstVal.On_ChangeGeo == false)
                                                        {
                                                            string test = "";
                                                        }
                                                        else
                                                        {
                                                            if (lstVal.Value != null)
                                                            {
                                                                AAState.WriteLine("                      Setting Last Value");
                                                                if (mode == "ON_CREATE" && (inObject.get_Value(intFldIdxs[p]) == null || inObject.get_Value(intFldIdxs[p]).ToString() == ""))
                                                                {
                                                                    AAState.WriteLine("                           Null Value in the create Method, not storing in last value array");

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                           " + strFldNames[p] + ": " + inObject.get_Value(intFldIdxs[p]).ToString());
                                                                    lstVal.Value = inObject.get_Value(intFldIdxs[p]);

                                                                    AAState.lastValueProperties.SetProperty(strFldNames[p], lstVal);
                                                                }
                                                            }

                                                            else
                                                            {
                                                                if (mode == "ON_CREATE" && (inObject.get_Value(intFldIdxs[p]) == null || inObject.get_Value(intFldIdxs[p]).ToString() == ""))
                                                                {
                                                                    AAState.WriteLine("                           Null Value in the create Method, not storing in last value array");

                                                                }
                                                                else
                                                                {
                                                                    AAState.WriteLine("                      Setting Last Value");
                                                                    AAState.WriteLine("                           " + strFldNames[p] + ": " + inObject.get_Value(intFldIdxs[p]).ToString());
                                                                    lstVal.Value = inObject.get_Value(intFldIdxs[p]);

                                                                    AAState.lastValueProperties.SetProperty(strFldNames[p], lstVal);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                            catch
                                            {

                                            }

                                    }
                                }
                            }
                            catch
                            {
                                AAState.WriteLine("        Error Setting Last Value");

                            }

                            AAState.WriteLine("    ------------------------------------------------");

                        }

                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error processing the rules" + System.Environment.NewLine + "Message:" + ex.Message, "Attribute Assistant Message");
                AAState.WriteLine("Error processing the rules");
                return false;

            }
            finally
            {
                if (AAState._tab == inObject.Class || AAState._gentab == inObject.Class)
                {
                    AAState.reInitExt();

                }
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }
                AAState.WriteLine("DONE");
                AAState.WriteLine("---------------------------------------");
                if (fCursor != null)
                {
                    Marshal.ReleaseComObject(fCursor);
                    GC.Collect(300);
                    GC.WaitForFullGCComplete();
                }
                inFeature = null;

                mseg = null;
                netFeat = null;
                iEdgeFeat = null;

                iJuncFeat = null;

                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog = null;
                trackCancel = null;

            }
        }
        public static void SplitLines(IApplication app, string SplitSuspendAA, double SplitAtLocationSnap, double SkipDistance)
        {
            IProgressDialogFactory progressDialogFactory = null;
            ITrackCancel trackCancel = null;
            IStepProgressor stepProgressor = null;

            IProgressDialog2 progressDialog = null;

            ICommandItem pCmd = null;
            IEditLayers eLayers = null;
            IEditor editor = null;
            IMxDocument mxdoc = null;
            IMap map = null;

            IFeatureLayer fLayer = null;
            IFeatureSelection fSel = null;

            UID geoFeatureLayerID = null;

            IEnumLayer enumLayer = null;

            List<IFeatureLayer> pointLayers = null;

            ILayer layer = null;
            List<IFeatureLayer> lineLayers;
            List<MergeSplitGeoNetFeatures> m_Config = null;
            IPoint pSplitPnt = null;
            ISet pSet = null;
            IFeature pSplitResFeat = null;
            try
            {
                m_Config = ConfigUtil.GetMergeSplitConfig();

                if (SplitSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                }
                editor = Globals.getEditor(app);
                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
                    return;
                }

                //Get enumeration of editable layers
                eLayers = (IEditLayers)editor;

                mxdoc = (IMxDocument)app.Document;
                map = editor.Map;

                int i = 0;
                int total = 0;

                //Get enumeration of feature layers
                geoFeatureLayerID = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                // Create list of visible point layers with selected feature(s)
                pointLayers = new List<IFeatureLayer>();
                lineLayers = new List<IFeatureLayer>();
                enumLayer.Reset();
                layer = enumLayer.Next();
                while (layer != null)
                {
                    fLayer = (IFeatureLayer)layer;
                    if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
                       && (fLayer.Visible))
                    {
                        fSel = fLayer as IFeatureSelection;
                        if (fSel.SelectionSet.Count > 0)
                        {
                            total += fSel.SelectionSet.Count;
                            pointLayers.Add(fLayer);
                        }
                    }
                    else if (fLayer.Valid && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
                        && (fLayer.Visible))
                    {
                        if (eLayers.IsEditable(fLayer))
                            lineLayers.Add(fLayer);
                    }
                    layer = enumLayer.Next();
                }

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

                // Create a CancelTracker
                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = app.hWnd;
                stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                stepProgressor.MinRange = 0;
                stepProgressor.MaxRange = total;
                stepProgressor.StepValue = 1;
                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_10");

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

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
                progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9");
                progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;

                //Create an edit operation enabling undo/redo
                editor.StartOperation();
                ICursor pointCursor = null;
                IFeatureSelection pointSel = null;
                IFeature pointFeature = null;
                ISpatialFilter sFilter = null;
                IFeatureSelection lineSel = null;
                IFeatureCursor lineCursor = null;
                IFeature lineFeature = null;
                //IFeatureEdit2 featureEdit = null;

                //Determine if point is at end of this line (if so skip)
                //ITopologicalOperator topoOp = null;
                //IPolygon poly = null;
                //IRelationalOperator relOp = null;
                //ICurve curve = null;

                try
                {
                    // step through all points and split the lines that intersect them

                    foreach (IFeatureLayer pointLayer in pointLayers)
                    {
                        pointSel = pointLayer as IFeatureSelection;
                        pointSel.SelectionSet.Search(null, false, out pointCursor);
                        pointFeature = pointCursor.NextRow() as IFeature;
                        while (!(pointFeature == null))
                        {
                            foreach (IFeatureLayer lineLayer in lineLayers)
                            {
                                sFilter = new SpatialFilterClass();
                                sFilter.Geometry = pointFeature.ShapeCopy;
                                sFilter.GeometryField = lineLayer.FeatureClass.ShapeFieldName;
                                sFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                                lineSel = lineLayer as IFeatureSelection;
                                lineCursor = lineLayer.Search(sFilter, false);
                                lineFeature = lineCursor.NextFeature();

                                IList<MergeSplitFlds> pFldsNames = new List<MergeSplitFlds>();

                                string strFormValu = "{0:0.##}";
                                if (m_Config.Count > 0)
                                {
                                    foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields)
                                    {
                                        int idx = Globals.GetFieldIndex(lineLayer.FeatureClass.Fields, FldNam.Name);
                                        if (idx > -1)
                                            pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule, FldNam.SplitRule));

                                    }
                                    strFormValu = m_Config[0].SplitFormatString;
                                }

                                while (!(lineFeature == null))
                                {
                                    Globals.splitLineWithPoint(lineFeature, pointFeature.Shape as IPoint, SplitAtLocationSnap, pFldsNames, strFormValu,app);

                                    //featureEdit = lineFeature as IFeatureEdit2;

                                    ////Determine if point is at end of this line (if so skip)
                                    //topoOp = pointFeature.Shape as ITopologicalOperator;
                                    //poly = topoOp.Buffer(SkipDistance) as IPolygon;
                                    //relOp = poly as IRelationalOperator;
                                    //curve = lineFeature.Shape as ICurve;
                                    //if (!(relOp.Contains(curve.FromPoint)) &
                                    //    !(relOp.Contains(curve.ToPoint)))
                                    //{
                                    //     pSplitPnt = pointFeature.ShapeCopy as IPoint;
                                    //     double dblHighVal = 0;
                                    //     double dblLowVal = 0;
                                    //     int intHighIdx = -1;
                                    //     int intLowIdx = -1;
                                    //    foreach (MergeSplitFlds FldNam in pFldsNames)
                                    //    {
                                    //        FldNam.Value= lineFeature.get_Value(FldNam.FieldIndex).ToString();
                                    //        if (FldNam.SplitType.ToUpper() == "MAX")
                                    //        {
                                    //            if (FldNam.Value != null)
                                    //            {
                                    //                if (FldNam.Value != "")
                                    //                {

                                    //                    dblHighVal = Convert.ToDouble(FldNam.Value);
                                    //                    intHighIdx = FldNam.FieldIndex;
                                    //                }
                                    //            }
                                    //        }
                                    //        else if (FldNam.SplitType.ToUpper() == "MIN")
                                    //        {
                                    //            if (FldNam.Value != null)
                                    //            {
                                    //                if (FldNam.Value != "")
                                    //                {

                                    //                    dblLowVal = Convert.ToDouble(FldNam.Value);
                                    //                    intLowIdx = FldNam.FieldIndex;
                                    //                }
                                    //            }
                                    //        }

                                    //    }
                                    //    if (intHighIdx > -1 && intLowIdx > -1)
                                    //    {
                                    //        double len = ((ICurve)(lineFeature.Shape as IPolyline)).Length;

                                    //        double splitDist = Globals.PointDistanceOnLine(pSplitPnt, lineFeature.Shape as IPolyline, 2, out pSplitPnt);
                                    //        double percentSplit = splitDist / len;
                                    //        double dblMidVal;
                                    //        if (m_Config[0].SplitFormatString == "")
                                    //        {
                                    //            dblMidVal = dblLowVal + ((dblHighVal - dblLowVal) * percentSplit);
                                    //        }
                                    //        else
                                    //        {
                                    //            dblMidVal = Convert.ToDouble(string.Format(m_Config[0].SplitFormatString, dblLowVal + ((dblHighVal - dblLowVal) * percentSplit)));

                                    //        }

                                    //        //Split feature
                                    //        pSet = featureEdit.SplitWithUpdate(pSplitPnt);

                                    //        if (pSet.Count == 1)
                                    //        {
                                    //            while ((pSplitResFeat = pSet.Next() as IFeature) != null)
                                    //            {
                                    //                if ((pSplitResFeat.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y)
                                    //                {
                                    //                    pSplitResFeat.set_Value(intHighIdx, dblMidVal);
                                    //                }
                                    //                else if ((pSplitResFeat.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (pSplitResFeat.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y)
                                    //                {
                                    //                    pSplitResFeat.set_Value(intLowIdx, dblMidVal);

                                    //                }
                                    //            }

                                    //        }
                                    //        if ((lineFeature.ShapeCopy as IPolyline).FromPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).FromPoint.Y == pSplitPnt.Y)
                                    //        {
                                    //            lineFeature.set_Value(intHighIdx, dblMidVal);
                                    //        }
                                    //        else if ((lineFeature.ShapeCopy as IPolyline).ToPoint.X == pSplitPnt.X && (lineFeature.ShapeCopy as IPolyline).ToPoint.Y == pSplitPnt.Y)
                                    //        {
                                    //            lineFeature.set_Value(intLowIdx, dblMidVal);

                                    //        }
                                    //    }else
                                    //        pSet = featureEdit.SplitWithUpdate(pSplitPnt);

                                    //    pSplitPnt = null;
                                    //}

                                    lineFeature = lineCursor.NextFeature();
                                }
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(lineCursor);

                            }

                            //Update progress bar
                            i += 1;
                            progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_11") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";
                            stepProgressor.Step();
                            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = app.StatusBar;
                            statusBar.set_Message(0, i.ToString());

                            //Check if the cancel button was pressed. If so, stop process
                            if (!trackCancel.Continue())
                            {
                                break;
                            }
                            pointFeature = (IFeature)pointCursor.NextRow();
                        }

                    }
                }
                catch (Exception ex)
                {
                    editor.AbortOperation();
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
                    return;
                }
                finally
                {
                    if (pointCursor != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pointCursor);
                    }
                    pointCursor = null;
                    pointSel = null;
                    pointFeature = null;
                    sFilter = null;
                    lineSel = null;
                    lineCursor = null;
                    lineFeature = null;
                    //featureEdit = null;

                    //topoOp = null;
                    //poly = null;
                    //relOp = null;
                    //curve = null;
                }
                progressDialog.HideDialog();

                //Stop the edit operation
                editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_9"));

            }
            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_5"));
                return;
            }
            finally
            {

                pSet = null;
                pSplitPnt = null;
                if (SplitSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                    pCmd = null;

                }
                if (progressDialog != null)
                    progressDialog.HideDialog();
                progressDialogFactory = null;
                trackCancel = null;
                stepProgressor = null;

                progressDialog = null;

                pCmd = null;
                eLayers = null;
                editor = null;
                mxdoc = null;
                map = null;

                fLayer = null;
                fSel = null;

                geoFeatureLayerID = null;

                enumLayer = null;

                pointLayers = null;

                layer = null;
                lineLayers = null;
                pSplitResFeat = null;
            }
        }
        public static void DisconnectSelected(IApplication app)
        {
            try
            {
                //Get list of editable layers
                IEditor editor = Globals.getEditor(ref app);

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_2"));
                    return;
                }
                IEditLayers eLayers = (IEditLayers)editor;

                IMap map = editor.Map;
                IActiveView activeView = map as IActiveView;

                if (map.SelectionCount > 0)
                {
                    //If above threshold, prompt to cancel
                    if ((map.SelectionCount > 1) &&
                       (MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_9a") + map.SelectionCount + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsAsk_9b"), A4LGSharedFunctions.Localizer.GetString("Confirm"), System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No))
                        return;

                    bool test = false;
                    ESRI.ArcGIS.esriSystem.IStatusBar statusBar = null;
                    ESRI.ArcGIS.esriSystem.IAnimationProgressor animationProgressor = null;
                    ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
                    ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
                    ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
                    ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = null;
                    try
                    {
                        // Create an edit operation enabling undo/redo
                        editor.StartOperation();

                        //Get list of feature layers
                        UID geoFeatureLayerID = new UIDClass();
                        geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                        IEnumLayer enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                        IFeatureLayer fLayer;
                        IFeatureSelection fSel;
                        ILayer layer;
                        ICursor cursor = null; IFeatureCursor fCursor = null;

                        int lyrCnt = 0;
                        while ((layer = enumLayer.Next()) != null)
                        {
                            lyrCnt = lyrCnt + 1;

                        }
                        enumLayer.Reset();

                        statusBar = app.StatusBar;
                        animationProgressor = statusBar.ProgressAnimation;

                        animationProgressor.Show();
                        animationProgressor.Play(0, -1, -1);

                        statusBar.set_Message(0, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_7"));

                        // Create a CancelTracker
                        trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                        progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                        // Set the properties of the Step Progressor
                        System.Int32 int32_hWnd = app.hWnd;
                        stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                        stepProgressor.MinRange = 0;
                        stepProgressor.MaxRange = lyrCnt - 1;
                        stepProgressor.StepValue = 1;
                        stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_10");

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

                        // Set the properties of the ProgressDialog
                        progressDialog2.CancelEnabled = true;
                        progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDesc_10");
                        progressDialog2.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsTitle_10");
                        progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;

                        // Step. Do your big process here.
                        System.Boolean boolean_Continue = false;
                        boolean_Continue = true;

                        // Step through each geofeature layer in the map
                        enumLayer.Reset();
                        while ((layer = enumLayer.Next()) != null)
                        {
                            // Verify that this is a valid, visible layer and that this layer is editable
                            fLayer = (IFeatureLayer)layer;
                            if (fLayer.Valid && fLayer.Visible && eLayers.IsEditable(fLayer))
                            {
                                stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_10a") + fLayer.Name;

                                // Verify selected features and network
                                INetworkClass netClass = fLayer.FeatureClass as INetworkClass;
                                fSel = (IFeatureSelection)fLayer;
                                if ((netClass != null) && (fSel.SelectionSet.Count > 0))
                                {
                                    test = true;

                                    fSel.SelectionSet.Search(null, false, out cursor);
                                    fCursor = cursor as IFeatureCursor;
                                    INetworkFeature netFeature;
                                    while ((netFeature = (INetworkFeature)fCursor.NextFeature()) != null)
                                    {
                                        try
                                        {
                                            netFeature.Disconnect();
                                        }
                                        catch
                                        { }
                                        //IFeature feat = (IFeature)netFeature;
                                        //int fieldPos = feat.Fields.FindField("ENABLED");

                                        //if (fieldPos > -1)
                                        //{
                                        //    feat.set_Value(fieldPos, feat.get_Value(fieldPos));
                                        //    feat.Store();
                                        //}

                                    }

                                    Marshal.ReleaseComObject(cursor);
                                    Marshal.ReleaseComObject(fCursor);

                                }

                            }
                            stepProgressor.Step();

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

                        // Stop the edit operation
                        editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_10"));

                    }
                    catch (Exception ex)
                    {
                        editor.AbortOperation();
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_10") + "\n" + ex.Message, ex.Source);
                        return;
                    }
                    finally
                    {
                        if (animationProgressor != null)
                        {
                            animationProgressor.Stop();
                            animationProgressor.Hide();
                        }
                        // Done
                        trackCancel = null;
                        stepProgressor = null;
                        if (progressDialog2 != null)
                        {
                            progressDialog2.HideDialog();
                        }

                        progressDialog2 = null;

                    }

                    //Alert the user know if no work was performed
                    if (!(test))
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_8a"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_10"));
                    else
                        activeView.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_10") + "\n" + ex.Message, ex.Source);
                return;
            }
        }
        public static void AddRotate(IApplication app, string AddRotateSuspendAA, double addSpinAngle)
        {
            ESRI.ArcGIS.Framework.ICommandItem pCmd = null;
            IEditor editor = null;
            IEditLayers eLayers = null;
            IMap map = null;
            UID geoFeatureLayerID = null;
            IEnumLayer enumLayer = null;
            IFeatureLayer fLayer = null;
            IGeoFeatureLayer geoFLayer = null;
            IRotationRenderer rRenderer = null;
            IFeatureSelection fSel = null;
            ILayer layer = null;
            string rotationFieldName;
            int rotationFieldPos;
            int count;
            double angle;
            IActiveView activeView = null;
            IInvalidArea invalid = null;
            IEnvelope ext = null;
            int i = 0;
            ICursor pointCursor = null;
            IFeature pointFeature = null;
            ISelectionSet2 sel = null;
            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;

            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            try
            {

                if (AddRotateSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                }

                int maxIndividualRefresh = 100;
                editor = Globals.getEditor(app);
                map = editor.Map;

                //Get list of editable layers
                // IEditor editor = _editor;
                eLayers = (IEditLayers)editor;
                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"));
                    return;
                }

                //Get list of feature layers
                geoFeatureLayerID = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                if (map.SelectionCount > 0)
                {
                    int total = map.SelectionCount;
                    progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                    // Create a CancelTracker
                    trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                    // Set the properties of the Step Progressor
                    System.Int32 int32_hWnd = app.hWnd;
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = total;
                    stepProgressor.StepValue = 1;
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeometryToolsMess_1");

                    // Create the ProgressDialog. This automatically displays the dialog

                    progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                    // Set the properties of the ProgressDialog
                    progressDialog.CancelEnabled = true;
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_3") + total.ToString() + ".";
                    progressDialog.Title = A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_2");
                    progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;

                    // Prep rotation calculator
                    // RotationCalculator rc = new RotationCalculator(_app);

                    //Prep screen refresh for selected features
                    activeView = map as IActiveView;
                    invalid = new InvalidAreaClass();
                    invalid.Display = editor.Display;

                    // Step through each geofeature layer in the map
                    enumLayer.Reset();
                    layer = enumLayer.Next();
                    bool test = false;
                    while (!(layer == null))
                    {
                        // Verify that this is a valid, visible point layer and that this layer is editable
                        fLayer = (IFeatureLayer)layer;
                        if (fLayer.Valid && fLayer.Visible && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint) &&
                            eLayers.IsEditable(fLayer))
                        {
                            // Verify that a selection  for this layer
                            fSel = (IFeatureSelection)fLayer;
                            count = fSel.SelectionSet.Count;

                            if (count > 0)
                            {
                                // Verify that symbol rotation has been setup for this layer
                                geoFLayer = (IGeoFeatureLayer)fLayer;
                                if (!(geoFLayer.Renderer is IRotationRenderer))
                                {
                                    layer = enumLayer.Next();
                                    continue;
                                }

                                // Verify that the rotation field has been specified and that the field exists
                                rRenderer = (IRotationRenderer)geoFLayer.Renderer;
                                rotationFieldName = rRenderer.RotationField;
                                rotationFieldPos = fLayer.FeatureClass.FindField(rotationFieldName);
                                if (rotationFieldPos == -1)
                                {
                                    layer = enumLayer.Next();
                                    continue;
                                }
                                test = true;

                                //rc.RotationType = rRenderer.RotationType;
                                //rc.SpinAngle = m_spinAngle;
                                //rc.DiameterFieldName = m_diameterFieldName;
                                //rc.UseDiameter = true;

                                // Create an edit operation enabling undo/redo
                                editor.StartOperation();
                                try
                                {
                                    //Get a cursor for selected features

                                    sel = fSel.SelectionSet as ISelectionSet2;
                                    sel.Update(null, false, out pointCursor);

                                    while ((pointFeature = (IFeature)pointCursor.NextRow()) != null)
                                    {
                                        if (map.SelectionCount <= maxIndividualRefresh)
                                        {
                                            //Prepare to redraw area around feature
                                            ext = pointFeature.Extent;
                                            ext.Expand(2, 2, true);
                                            invalid.Add(ext);
                                        }
                                        //Use Rotation Calculator
                                        // angle = rc.GetRotationUsingConnectedEdges(pointFeature);

                                        //Set rotation value in feature
                                        if (pointFeature.get_Value(rotationFieldPos) == null)
                                        {
                                            angle = 0;
                                        }
                                        else if (pointFeature.get_Value(rotationFieldPos) == DBNull.Value)
                                        {
                                            angle = 0;
                                        }
                                        else
                                        {
                                             Double.TryParse( pointFeature.get_Value(rotationFieldPos).ToString(),out angle);
                                        }
                                        angle = angle + addSpinAngle;
                                        if (angle > 360) angle -= 360;
                                        if (angle < 0) angle += 360;
                                        pointFeature.set_Value(rotationFieldPos, angle);
                                        pointCursor.UpdateRow(pointFeature as IRow);

                                        //Update progress bar
                                        i += 1;
                                        stepProgressor.Step();
                                        progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_4") + i.ToString() + A4LGSharedFunctions.Localizer.GetString("Of") + total.ToString() + ".";

                                        //Check if the cancel button was pressed. If so, stop process
                                        if (!trackCancel.Continue())
                                        {
                                            break;
                                        }

                                    }

                                    if (pointCursor != null)
                                    {
                                        Marshal.ReleaseComObject(pointCursor);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    editor.AbortOperation();
                                    progressDialog.HideDialog();
                                    MessageBox.Show("AddRotate\n" + ex.Message, ex.Source);
                                    return;
                                }

                                // Stop the edit operation
                                editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_5"));

                            }

                        }

                        layer = enumLayer.Next();

                    }

                    progressDialog.HideDialog();

                    //Alert the user know if no work was performed
                    if (!(test))
                        MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsError_6"), A4LGSharedFunctions.Localizer.GetString("GeometryToolsLbl_3"));

                    //Redraw invalid areas or entire map
                    if (i > 0)
                    {
                        if (map.SelectionCount < maxIndividualRefresh)
                            invalid.Invalidate((short)esriScreenCache.esriAllScreenCaches);
                        else
                            activeView.Refresh();
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_5") + "\n" + ex.Message, A4LGSharedFunctions.Localizer.GetString("GeometryToolsProc_5"));
                return;
            }
            finally
            {
                if (AddRotateSuspendAA.ToUpper() == "TRUE")
                {
                    pCmd = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
                    if (pCmd != null)
                    {
                        pCmd.Execute();
                    }
                    pCmd = null;
                }
                if (pointCursor != null)
                {
                    Marshal.ReleaseComObject(pointCursor);
                }
                pCmd = null;
                editor = null;
                eLayers = null;
                map = null;
                geoFeatureLayerID = null;
                if (enumLayer != null)
                {
                    Marshal.ReleaseComObject(enumLayer);
                }
                enumLayer = null;
                fLayer = null;
                geoFLayer = null;
                rRenderer = null;
                fSel = null;
                layer = null;

                activeView = null;
                invalid = null;
                ext = null;

                pointCursor = null;
                pointFeature = null;
                sel = null;
                progressDialogFactory = null;

                trackCancel = null;
                stepProgressor = null;
                progressDialog = null;

            }
        }
        public static void MoveConnectionsToNewLine(IApplication app, double snapTol, List<MoveConnectionsDetails> moveConDetails)
        {
            IEditor editor = null;

            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = null;
            ESRI.ArcGIS.esriSystem.IAnimationProgressor animationProgressor = null;
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = null;
            ICommandItem pCmdItem;

            IMxDocument pMxDoc = ((IMxDocument)app.Document);
            IGeometricNetwork pGN = null;
            IFeature pFeature = null;
            IPoint pTracePoint = null;
            ISimpleLineSymbol pSimpleLineSym = null;
            IRgbColor pRGBColor = null;

            IGraphicsContainer gc = null;

            IElement pMoveElemFirst = null;
            IElementProperties3 pMoveElemPropFirst = null;

            IElement element = null;
            IElementProperties3 elementProp = null;
            ILineElement lineElem = null;
            IJunctionFeature pJuncFeat = null;

            IFeatureLayer pSourceLayer = null;
            IFeature pSourceFeature = null;
            IFeature pMoveFeat = null;
            INetworkFeature pNetworkSourceFeature = null;
            IEdgeFeature iTargetEdgeFeat = null;
            IComplexEdgeFeature iCEdge = null;
            IFeatureClass pOraphFC = null;

            List<int> OIDs = new List<int>();
            List<string> FeatLoc = new List<string>();
            List<IObjectClass> FCs = new List<IObjectClass>();
            IPolyline pL;

            IHitTest pHtTest = null;//= pPolyline as IHitTest;

            IPoint pHitPntOne = new PointClass();
            double pHitDistOne = -1;
            int pHitPrtOne = -1;
            int pHitSegOne = -1;
            bool pHitSideOne = false;

            //IFeatureCursor pFeatCursor = null;
            IFeatureLayer pMainLayer = null;
            //IFeatureLayer pMainLayer = null;
            //IFeatureLayer pTapLayer = null;
            ILayer pLay = null;
            try
            {
                editor = Globals.getEditor(ref app);

                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("MustBEditg"), A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_2"));
                    return;
                }

                pTracePoint = pMxDoc.CurrentLocation;
                pFeature = Globals.GetNetworkAndFeatureAtLocation(pTracePoint, app, esriElementType.esriETEdge, out pGN, snapTol);

                if (pFeature == null)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("NoFtrFndOnClck"));
                    return;
                }

                int idxDet = -1;

                for (int i = 0; i < moveConDetails.Count; i++)
                {
                    //MoveConnectionsDetails conDet = moveConDetails[i];
                    bool FCorLayerTemp = true;
                    pMainLayer = (IFeatureLayer)Globals.FindLayer(app, moveConDetails[i].LineLayer, ref FCorLayerTemp);
                    if (pMainLayer != null)
                    {
                        if (pMainLayer.FeatureClass.ObjectClassID == pFeature.Class.ObjectClassID)
                        {
                            idxDet = i;

                            break;

                        }
                    }
                }

                if (idxDet == -1)
                    return;

                if (Globals.IsEditable(ref pFeature, ref editor) == false)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_13b"));
                    return;
                }
                if (pFeature.FeatureType != esriFeatureType.esriFTComplexEdge)
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsMess_13c"));
                    return;
                }
                pRGBColor = Globals.GetColor(255, 0, 0);

                pSimpleLineSym = Globals.CreateSimpleLineSymbol(pRGBColor, 2, esriSimpleLineStyle.esriSLSSolid);

                gc = pMxDoc.FocusMap as IGraphicsContainer;

                gc.Reset();
                element = gc.Next();

                while (element != null)
                {
                    elementProp = element as IElementProperties3;
                    if (elementProp.Name.Contains("MoveFeatureFlag"))
                    {
                        if (pMoveElemFirst == null)
                        {

                            pMoveElemFirst = element;

                            pMoveElemPropFirst = elementProp;
                            string[] firstVals = pMoveElemPropFirst.Name.ToString().Split(':');
                            if (firstVals[1] != pFeature.Class.ObjectClassID.ToString())
                            {
                                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13a"));
                                return;

                            }

                            break;
                        }

                    }
                    element = gc.Next();
                }

                lineElem = new LineElementClass();
                lineElem.Symbol = pSimpleLineSym;
                element = (IElement)lineElem;
                element.Geometry = pFeature.ShapeCopy;
                elementProp = element as IElementProperties3;
                elementProp.Name = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_13a") + ": " + pFeature.Class.ObjectClassID.ToString() + ":" + pFeature.OID;

                elementProp.ReferenceScale = pMxDoc.FocusMap.ReferenceScale;
                gc.AddElement(element, 0);
                pMxDoc.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pFeature.Shape.Envelope);

                if (pMoveElemFirst == null)
                    return;
                else
                {
                    List<int> LayersToMoveIDs = new List<int>();
                    foreach (string Lay in moveConDetails[idxDet].LayersToMove)
                    {
                        bool FCorLayerTemp = true;
                        pLay = Globals.FindLayer(app, Lay, ref FCorLayerTemp);
                        if (pLay != null)
                        {
                            LayersToMoveIDs.Add(((IFeatureLayer)pLay).FeatureClass.ObjectClassID);

                        }
                    }
                    statusBar = app.StatusBar;
                    animationProgressor = statusBar.ProgressAnimation;

                    animationProgressor.Show();
                    animationProgressor.Play(0, -1, -1);

                    statusBar.set_Message(0, A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13a"));

                    // Create a CancelTracker
                    trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                    progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                    // Set the properties of the Step Progressor
                    System.Int32 int32_hWnd = app.hWnd;
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = 4;
                    stepProgressor.StepValue = 1;
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13a");

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

                    // Set the properties of the ProgressDialog
                    progressDialog2.CancelEnabled = true;
                    progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13a");
                    progressDialog2.Title = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13a");
                    progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;

                    System.Boolean boolean_Continue = true;

                    stepProgressor.Step();

                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    stepProgressor.Step();
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsLbl_13b");
                    //ProfileFindPath();
                    pCmdItem = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOffCommand", app);
                    if (pCmdItem != null)
                    {
                        pCmdItem.Execute();
                    }
                    string[] elemInfo = (elementProp = pMoveElemFirst as IElementProperties3).Name.Split(':');

                    pSourceLayer = Globals.FindLayerByClassID(pMxDoc.FocusMap, elemInfo[1]) as IFeatureLayer;
                    pSourceFeature = pSourceLayer.FeatureClass.GetFeature(Convert.ToInt32(elemInfo[2]));
                    pNetworkSourceFeature = (INetworkFeature)pSourceFeature;
                    iTargetEdgeFeat = (IEdgeFeature)pNetworkSourceFeature;
                    iCEdge = (pNetworkSourceFeature) as IComplexEdgeFeature;
                    pOraphFC = pGN.OrphanJunctionFeatureClass;

                    editor.StartOperation();
                    pL = pSourceFeature.ShapeCopy as IPolyline;
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    stepProgressor.Step();
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13b");

                    for (int i = 0; i < iCEdge.JunctionFeatureCount; i++)
                    {
                        pJuncFeat = iCEdge.get_JunctionFeature(i);

                        if ((pJuncFeat as IFeature).Class.ObjectClassID != pOraphFC.ObjectClassID && LayersToMoveIDs.Contains((pJuncFeat as IFeature).Class.ObjectClassID))
                        {

                            if (pL.FromPoint.X == ((pJuncFeat as IFeature).Shape as IPoint).X && pL.FromPoint.Y == ((pJuncFeat as IFeature).Shape as IPoint).Y)
                            {
                                FeatLoc.Add("From");
                            }
                            else if (pL.ToPoint.X == ((pJuncFeat as IFeature).Shape as IPoint).X && pL.ToPoint.Y == ((pJuncFeat as IFeature).Shape as IPoint).Y)
                            {
                                FeatLoc.Add("To");
                            }
                            else
                            {
                                FeatLoc.Add("Along");
                            }

                            OIDs.Add((pJuncFeat as IFeature).OID);
                            FCs.Add((pJuncFeat as IFeature).Class);
                        }
                    }
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    stepProgressor.Step();
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13c");

                    pNetworkSourceFeature.Disconnect();

                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    stepProgressor.Step();
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("GeoNetToolsProc_13d");
                    string msg = "";
                    List<IFeature> pM = new List<IFeature>();
                    for (int i = 0; i < OIDs.Count; i++)
                    {
                        pMoveFeat = (FCs[i] as IFeatureClass).GetFeature(OIDs[i]);
                        esriGeometryHitPartType pSearchLoc;
                        if (FeatLoc[i] == "From" || FeatLoc[i] == "To")
                        {
                            pSearchLoc = esriGeometryHitPartType.esriGeometryPartEndpoint;
                        }
                        else
                        {
                            pSearchLoc = esriGeometryHitPartType.esriGeometryPartBoundary;
                        }
                        pHtTest = pFeature.ShapeCopy as IHitTest;
                        bool bHitOne = pHtTest.HitTest(pMoveFeat.Shape as IPoint, 50, pSearchLoc,
                                        pHitPntOne, ref pHitDistOne, ref pHitPrtOne, ref pHitSegOne, ref pHitSideOne);

                        if (bHitOne != false)
                        {
                            if ((pMoveFeat.Shape as IPoint).Z != null && Globals.IsNumeric((pMoveFeat.Shape as IPoint).Z.ToString()))
                                pHitPntOne.Z = (pMoveFeat.Shape as IPoint).Z;

                            pMoveFeat.Shape = pHitPntOne;
                            pM.Add(pMoveFeat);

                            try
                            {
                                pMoveFeat.Store();
                                INetworkFeature netFeature = null;
                                netFeature = pMoveFeat as INetworkFeature;
                                netFeature.Connect();

                            }
                            catch
                            {
                                if (msg == "")
                                {
                                    msg = A4LGSharedFunctions.Localizer.GetString("FeatureIn") + (FCs[i] as IFeatureClass).AliasName + A4LGSharedFunctions.Localizer.GetString("WithOID") + pMoveFeat.OID + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13b");

                                }
                                else
                                {
                                    msg = msg + "\n" + A4LGSharedFunctions.Localizer.GetString("FeatureIn") + (FCs[i] as IFeatureClass).AliasName + A4LGSharedFunctions.Localizer.GetString("WithOID") + pMoveFeat.OID + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13b");

                                }
                            }

                        }
                    }

                    ////foreach (IFeature pF in pM)
                    ////{
                    ////    try
                    ////    {
                    ////        pF.Store();
                    ////        INetworkFeature netFeature = null;
                    ////        netFeature = pF as INetworkFeature;
                    ////        netFeature.Connect();

                    ////    }
                    ////    catch
                    ////    {
                    ////        if (msg == "")
                    ////        {
                    ////            msg = A4LGSharedFunctions.Localizer.GetString("FeatureIn") + (pF.Class as IFeatureClass).AliasName + A4LGSharedFunctions.Localizer.GetString("WithOID") + pMoveFeat.OID + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13b");

                    ////        }
                    ////        else
                    ////        {
                    ////            msg = msg + "\n" + A4LGSharedFunctions.Localizer.GetString("FeatureIn") + (pF.Class as IFeatureClass).AliasName + A4LGSharedFunctions.Localizer.GetString("WithOID") + pMoveFeat.OID + A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13b");

                    ////        }
                    ////    }

                    ////    if (msg != "")
                    ////    {
                    ////        MessageBox.Show(msg);

                    ////    }
                    ////}
                    //INetworkFeature pNetworkTargetFeature = (INetworkFeature)pFeature;
                    // IFeatureLayer pTargetLayer = Globals.FindLayerByClassID(pMxDoc.FocusMap,pFeature.Class.CLSID.ToString()) as IFeatureLayer;

                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    stepProgressor.Step();
                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("Complete");

                    try
                    {
                        Globals.RemoveTraceGraphics(pMxDoc.FocusMap, true);
                    }
                    catch
                    { }
                    // unpress the UIToolControl button
                    app.CurrentTool = null;
                    app.RefreshWindow();
                    pMxDoc.ActiveView.Refresh();
                    return;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    editor.AbortOperation();

                }
                catch
                { }

                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsError_13c") + ex.Message);
                return;
            }
            finally
            {
                try
                {
                    editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("GeoNetToolsDone_13a"));
                }
                catch
                { }

                if (progressDialog2 != null)
                    progressDialog2.HideDialog();
                progressDialog2 = null;
                pCmdItem = Globals.GetCommand("ArcGIS4LocalGovernment_AttributeAssistantSuspendOnCommand", app);
                if (pCmdItem != null)
                {
                    pCmdItem.Execute();
                }
                pLay = null;
                statusBar = null;
                animationProgressor = null;
                trackCancel = null;
                progressDialogFactory = null;
                stepProgressor = null;
                progressDialog2 = null;
                pCmdItem = null;

                pMxDoc = null;
                pGN = null;
                pFeature = null;
                pTracePoint = null;
                pSimpleLineSym = null;
                pRGBColor = null;

                gc = null;

                pMoveElemFirst = null;
                pMoveElemPropFirst = null;

                element = null;
                elementProp = null;
                lineElem = null;
                pJuncFeat = null;

                pSourceLayer = null;
                pSourceFeature = null;
                pMoveFeat = null;
                pNetworkSourceFeature = null;
                iTargetEdgeFeat = null;
                iCEdge = null;
                pOraphFC = null;

                OIDs = null;
                FeatLoc = null;
                FCs = null;
                pL = null;

                pHtTest = null;//= pPolyline as IHitTest;

                pHitPntOne = null;
                editor = null;

            }
        }
        public void RunCreateRules()
        {
            ICursor cursor = null; IFeatureCursor fCursor = null;
            bool ran = false;

            try
            {
                //Get list of editable layers
                IEditor editor = _editor;
                IEditLayers eLayers = (IEditLayers)editor;
                long lastOID = -1;
                string lastLay = "";

                if (_editor.EditState != esriEditState.esriStateEditing)
                    return;

                IMap map = editor.Map;
                IActiveView activeView = map as IActiveView;

                IStandaloneTable stTable;

                ITableSelection tableSel;

                IStandaloneTableCollection stTableColl = (IStandaloneTableCollection)map;

                long rowCount = stTableColl.StandaloneTableCount;
                long rowSelCount = 0;
                for (int i = 0; i < stTableColl.StandaloneTableCount; i++)
                {

                    stTable = stTableColl.get_StandaloneTable(i);
                    tableSel = (ITableSelection)stTable;
                    if (tableSel.SelectionSet != null)
                    {
                        rowSelCount = rowSelCount + tableSel.SelectionSet.Count;
                    }

                }
                long featCount = map.SelectionCount;
                int totalCount = (Convert.ToInt32(rowSelCount) + Convert.ToInt32(featCount));

                if (totalCount >= 1)
                {

                    if (MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantAsk_4a") + totalCount + A4LGSharedFunctions.Localizer.GetString("AttributeAssistantAsk_2b"),
                        A4LGSharedFunctions.Localizer.GetString("Confirm"), System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {

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

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

                        // Set the properties of the Step Progressor
                        System.Int32 int32_hWnd = ArcMap.Application.hWnd;
                        ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                        stepProgressor.MinRange = 1;
                        stepProgressor.MaxRange = totalCount;

                        stepProgressor.StepValue = 1;
                        stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("AttributeAssistantMess_2a");

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

                        // Set the properties of the ProgressDialog
                        progressDialog2.CancelEnabled = true;
                        progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("AttributeAssistantDesc_2a") + totalCount.ToString() + ".";
                        progressDialog2.Title = A4LGSharedFunctions.Localizer.GetString("AttributeAssistantTitle_2a");
                        progressDialog2.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;

                        // Step. Do your big process here.
                        System.Boolean boolean_Continue = false;
                        boolean_Continue = true;
                        System.Int32 progressVal = 0;

                        ESRI.ArcGIS.esriSystem.IStatusBar statusBar = ArcMap.Application.StatusBar;

                        ran = true;
                        editor.StartOperation();

                        //bool test = false;

                        //Get list of feature layers
                        UID geoFeatureLayerID = new UIDClass();
                        geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                        IEnumLayer enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);
                        IFeatureLayer fLayer;
                        IFeatureSelection fSel;
                        ILayer layer;
                        // Step through each geofeature layer in the map
                        enumLayer.Reset();
                        // Create an edit operation enabling undo/redo
                        try
                        {
                            //   AAState.StopCreateMonitor();
                            while ((layer = enumLayer.Next()) != null)
                            {
                                // Verify that this is a valid, visible layer and that this layer is editable
                                fLayer = (IFeatureLayer)layer;
                                bool bIsEditableFabricLayer = (fLayer is ICadastralFabricSubLayer2);
                                if (bIsEditableFabricLayer)
                                {
                                    IDataset pDS = (IDataset)fLayer.FeatureClass;
                                    IWorkspace pFabWS = pDS.Workspace;
                                    bIsEditableFabricLayer = (bIsEditableFabricLayer && pFabWS.Equals(editor.EditWorkspace));
                                }
                                if (fLayer.Valid && (eLayers.IsEditable(fLayer) || bIsEditableFabricLayer))//fLayer.Visible &&
                                {
                                    // Verify that this layer has selected features
                                    IFeatureClass fc = fLayer.FeatureClass;
                                    fSel = (IFeatureSelection)fLayer;

                                    if ((fc != null) && (fSel.SelectionSet.Count > 0))
                                    {

                                        fSel.SelectionSet.Search(null, false, out cursor);
                                        fCursor = cursor as IFeatureCursor;
                                        IFeature feat;
                                        feat = (IFeature)fCursor.NextFeature();
                                        while (feat != null)
                                        {

                                            progressVal++;
                                            progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("AttributeAssistantProc_2a") + progressVal + A4LGSharedFunctions.Localizer.GetString("Of") + totalCount.ToString() + ".";

                                            stepProgressor.Step();

                                            statusBar.set_Message(0, progressVal.ToString());

                                            lastOID = feat.OID;
                                            lastLay = fLayer.Name;
                                            IObject pObj = feat as IObject;

                                            AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantMess_5a"));
                                            AAState._editEvents.OnCreateFeature -= AAState.FeatureCreate;
                                            AAState._editEvents.OnChangeFeature -= AAState.FeatureChange;

                                            try
                                            {
                                                //AAState.FeatureCreate(pObj);
                                                Debug.WriteLine("Feature with " + feat.OID);
                                                Debug.WriteLine(progressVal.ToString() + " : Count is " + fSel.SelectionSet.Count);
                                                feat.Store();
                                            }
                                            catch
                                            {
                                            }

                                            AAState._editEvents.OnCreateFeature += AAState.FeatureCreate;
                                            AAState._editEvents.OnChangeFeature += AAState.FeatureChange;
                                            AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantMess_5b"));

                                            //Check if the cancel button was pressed. If so, stop process
                                            boolean_Continue = trackCancel.Continue();
                                            if (!boolean_Continue)
                                            {
                                                break;
                                            }
                                            feat = (IFeature)fCursor.NextFeature();
                                        }
                                        if (feat != null)
                                            Marshal.ReleaseComObject(feat);

                                    }

                                }
                                else
                                {
                                    if (fLayer.Valid)
                                    {
                                        // Verify that this layer has selected features
                                        IFeatureClass fc = fLayer.FeatureClass;
                                        fSel = (IFeatureSelection)fLayer;
                                        if (fSel.SelectionSet.Count > 0)
                                        {
                                            progressVal = progressVal + fSel.SelectionSet.Count;
                                            stepProgressor.OffsetPosition(progressVal);

                                            stepProgressor.Step();

                                        }
                                    }

                                }
                            }

                            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                        }
                        catch (Exception ex)
                        {
                            editor.AbortOperation();
                            ran = false;
                            MessageBox.Show("RunCreateRule\n" + ex.Message + " \n" + lastLay + ": " + lastOID, ex.Source);
                            return;
                        }
                        finally
                        {
                            //  AAState.StartCreateMonitor();
                            try
                            {
                                // Stop the edit operation
                                editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantDone_5a"));
                            }
                            catch (Exception ex)
                            { }

                        }

                        editor.StartOperation();
                        try
                        {
                            AAState.StopChangeMonitor();
                            for (int i = 0; i < stTableColl.StandaloneTableCount; i++)
                            {

                                stTable = stTableColl.get_StandaloneTable(i);
                                tableSel = (ITableSelection)stTable;
                                if (tableSel.SelectionSet != null)
                                {

                                    if (tableSel.SelectionSet.Count > 0)
                                    {
                                        tableSel.SelectionSet.Search(null, false, out  cursor);
                                        IRow pRow;
                                        while ((pRow = (IRow)cursor.NextRow()) != null)
                                        {

                                            progressVal++;
                                            progressDialog2.Description = A4LGSharedFunctions.Localizer.GetString("AttributeAssistantProc_2a") + progressVal + A4LGSharedFunctions.Localizer.GetString("Of") + totalCount.ToString() + ".";
                                            stepProgressor.Step();

                                            statusBar.set_Message(0, progressVal.ToString());

                                            lastOID = pRow.OID;
                                            lastLay = stTable.Name;
                                            IObject pObj = pRow as IObject;

                                            AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantMess_5a"));
                                            AAState._editEvents.OnCreateFeature -= AAState.FeatureCreate;

                                            try
                                            {
                                                AAState.FeatureCreate(pObj);
                                                pRow.Store();
                                            }
                                            catch
                                            {
                                            }

                                            AAState._editEvents.OnCreateFeature += AAState.FeatureCreate;
                                            AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantMess_5b"));

                                            //Check if the cancel button was pressed. If so, stop process
                                            boolean_Continue = trackCancel.Continue();
                                            if (!boolean_Continue)
                                            {
                                                break;
                                            }
                                        }
                                        if (pRow != null)
                                            Marshal.ReleaseComObject(pRow);

                                    }
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            editor.AbortOperation();
                            MessageBox.Show("RunCreateRules\n" + ex.Message + " \n" + lastLay + ": " + lastOID, ex.Source);
                            ran = false;

                            return;
                        }
                        finally
                        {
                            AAState.StartChangeMonitor();
                            try
                            {
                                // Stop the edit operation
                                editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantDone_5a"));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorWarn_14a") + " " + ex.Message);

                            }

                        }

                        // Done
                        trackCancel = null;
                        stepProgressor = null;
                        progressDialog2.HideDialog();
                        progressDialog2 = null;
                    }

                }
                else
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantError_2a"));

                }

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " \n" + "RunCreateRules", ex.Source);
                ran = false;

                return;
            }
            finally
            {
                if (ran)
                    //  MessageBox.Show("Process has completed successfully");

                    if (cursor != null)
                        Marshal.ReleaseComObject(cursor);
                if (fCursor != null)
                    Marshal.ReleaseComObject(fCursor);

            }
        }
        public static void RotateSelected(IApplication app, double spinAngle, string diameterFieldName)
        {
            IEditor editor = null;
            IEditLayers eLayers = null;
            IMap map = null;
            UID geoFeatureLayerID = null;
            IEnumLayer enumLayer = null;
            IFeatureLayer fLayer = null;
            IGeoFeatureLayer geoFLayer = null;
            IRotationRenderer rRenderer = null;
            IFeatureSelection fSel = null;
            ILayer layer = null;
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = null;
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = null;
            RotationCalculator rc = null;
            IActiveView activeView = null;
            IInvalidArea invalid = null;

            IEnvelope ext = null;
            ICursor pointCursor = null;
            IFeature pointFeature = null;
            ISelectionSet2 sel = null;

            try
            {

                int maxIndividualRefresh = 100;

                //Get list of editable layers
                 editor = Globals.getEditor(app);
                eLayers = (IEditLayers)editor;
                if (editor.EditState != esriEditState.esriStateEditing)
                {
                    MessageBox.Show("Must be editing.");
                    return;
                }

                map = editor.Map;

                //Get list of feature layers
                geoFeatureLayerID = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(((ESRI.ArcGIS.esriSystem.UID)geoFeatureLayerID), true);

                if (map.SelectionCount > 0)
                {

                    string rotationFieldName;
                    int rotationFieldPos;
                    int count;
                    Nullable<double> angle;
                    int total = map.SelectionCount;
                    int i = 0;

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

                    // Create a CancelTracker
                    trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                    // Set the properties of the Step Progressor
                    System.Int32 int32_hWnd = app.hWnd;
                    stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = total;
                    stepProgressor.StepValue = 1;
                    stepProgressor.Message = "Setting Rotation Value for Selected Points";

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

                    // Set the properties of the ProgressDialog
                    progressDialog.CancelEnabled = true;
                    progressDialog.Description = "Rotating points " + total.ToString() + ".";
                    progressDialog.Title = "Rotate Points";
                    progressDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;

                    // Prep rotation calculator
                    rc = new RotationCalculator(app);

                    //Prep screen refresh for selected features
                    activeView = map as IActiveView;
                    invalid = new InvalidAreaClass();
                    invalid.Display = editor.Display;

                    // Step through each geofeature layer in the map
                    enumLayer.Reset();
                    layer = enumLayer.Next();
                    bool test = false;
                    while (!(layer == null))
                    {
                        // Verify that this is a valid, visible point layer and that this layer is editable
                        fLayer = (IFeatureLayer)layer;
                        if (fLayer.Valid && fLayer.Visible && (fLayer.FeatureClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint) &&
                            eLayers.IsEditable(fLayer))
                        {
                            // Verify that a selection  for this layer
                            fSel = (IFeatureSelection)fLayer;
                            count = fSel.SelectionSet.Count;

                            if (count > 0)
                            {
                                // Verify that symbol rotation has been setup for this layer
                                geoFLayer = (IGeoFeatureLayer)fLayer;
                                if (!(geoFLayer.Renderer is IRotationRenderer))
                                {
                                    layer = enumLayer.Next();
                                    continue;
                                }

                                // Verify that the rotation field has been specified and that the field exists
                                rRenderer = (IRotationRenderer)geoFLayer.Renderer;
                                rotationFieldName = rRenderer.RotationField;
                                rotationFieldPos = fLayer.FeatureClass.FindField(rotationFieldName);
                                if (rotationFieldPos == -1)
                                {
                                    layer = enumLayer.Next();
                                    continue;
                                }
                                test = true;

                                rc.RotationType = rRenderer.RotationType;
                                rc.SpinAngle = spinAngle;
                                rc.DiameterFieldName = diameterFieldName;
                                rc.UseDiameter = true;

                                // Create an edit operation enabling undo/redo
                                editor.StartOperation();
                                try
                                {
                                    //Get a cursor for selected features
                                    sel = fSel.SelectionSet as ISelectionSet2;
                                    sel.Update(null, false, out pointCursor);

                                    while ((pointFeature = (IFeature)pointCursor.NextRow()) != null)
                                    {
                                        if (map.SelectionCount <= maxIndividualRefresh)
                                        {
                                            //Prepare to redraw area around feature
                                            ext = pointFeature.Extent;
                                            ext.Expand(2, 2, true);
                                            invalid.Add(ext);
                                        }
                                        //Use Rotation Calculator
                                        angle = rc.GetRotationUsingConnectedEdges(pointFeature);

                                        //Set rotation value in feature
                                        pointFeature.set_Value(rotationFieldPos, angle);
                                        pointCursor.UpdateRow(pointFeature as IRow);

                                        //Update progress bar
                                        i += 1;
                                        stepProgressor.Step();
                                        progressDialog.Description = "Rotating point " + i.ToString() + " of " + total.ToString() + ".";

                                        //Check if the cancel button was pressed. If so, stop process
                                        if (!trackCancel.Continue())
                                        {
                                            break;
                                        }

                                    }
                                    if (pointCursor != null)
                                    {
                                        Marshal.ReleaseComObject(pointCursor);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    editor.AbortOperation();
                                    progressDialog.HideDialog();
                                    MessageBox.Show("RotateSelected\n" + ex.Message, ex.Source);
                                    return;
                                }

                                // Stop the edit operation
                                editor.StopOperation("Rotate Selected");

                            }

                        }

                        layer = enumLayer.Next();

                    }

                    progressDialog.HideDialog();

                    //Alert the user know if no work was performed
                    if (!(test))
                        MessageBox.Show("None of the editable layers with selected features have rotation specified. \nIn Layer properties on the Symbology tab, click Advanced to set the rotation field and type.", "RotateSelected");

                    //Redraw invalid areas or entire map
                    if (i > 0)
                    {
                        if (map.SelectionCount < maxIndividualRefresh)
                            invalid.Invalidate((short)esriScreenCache.esriAllScreenCaches);
                        else
                            activeView.Refresh();
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("RotateSelected\n" + ex.Message, "RotateSelected");
                return;
            }
            finally
            {
                editor = null;
                eLayers = null;
                map = null;
                geoFeatureLayerID = null;
                enumLayer = null;
                fLayer = null;
                geoFLayer = null;
                rRenderer = null;
                fSel = null;
                layer = null;
                progressDialogFactory = null;
                trackCancel = null;
                stepProgressor = null;
                progressDialog = null;
                rc = null;
                activeView = null;
                invalid = null;

                ext = null;
                pointCursor = null;
                pointFeature = null;
                sel = null;

            }
        }