static void Main(string[] args)
 {
     // get a geodatabase path from the command line or use this default:
     var gdbPath = @"C:\Data\SDK\GDB\LocalGovernment.gdb";
     if (args.Count() > 0) gdbPath = args[0];
     //Call Host.Initialize before constructing any objects from ArcGIS.Core
     try {
         Host.Initialize();
     }
     catch (Exception e) {
         // Error (missing installation, no license, 64 bit mismatch, etc.)
         Console.WriteLine(string.Format("Initialization failed: {0}", e.Message));
         return;
     }
     try
     {
         //if we are here, ArcGIS.Core is successfully initialized
         using (var gdb = new Geodatabase(gdbPath))
         {
             IReadOnlyList<TableDefinition> definitions = gdb.GetDefinitions<FeatureClassDefinition>();
             foreach (var fdsDef in definitions)
             {
                 Console.WriteLine(TableString(fdsDef as TableDefinition));
             }
         }
         Console.Read();
     }
     catch (Exception e)
     {
         // Error (missing installation, no license, 64 bit mismatch, etc.)
         Console.WriteLine(string.Format("Cannot read file Geodatabase [{0}] error: {1}", gdbPath, e.Message));
         return;
     }
 }
Example #2
0
 private IEnumerable <RelationshipClassDefinition> GetRelationshipClassDefinitionsFromFeatureClass(
     Geodatabase gdb, string featureClassName)
 {
     return(gdb.GetDefinitions <RelationshipClassDefinition>().
            Where(defn => defn.GetOriginClass().Equals(featureClassName) || defn.GetDestinationClass().Equals(featureClassName)));
 }
 /// <summary>
 /// Given that a Layer has been selected, this method will populate the RelationshipClasses (bound to RelationshipClasses Combobox) with the names of the RelationshipClasses
 /// in which the FeatureClass/Table corresponding to the selected layer participates (as Origin or Destination)
 /// </summary>
 public void UpdateRelationshipClasses()
 {
     QueuedTask.Run(() =>
     {
         lock (_lockCollections) _relationshipClasses.Clear();
         using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
         {
             Geodatabase geodatabase = null;
             if (table != null && table.GetDatastore() is Geodatabase)
             {
                 geodatabase = table.GetDatastore() as Geodatabase;
             }
             if (geodatabase == null)
             {
                 return;
             }
             IReadOnlyList <RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions <RelationshipClassDefinition>();
             IEnumerable <RelationshipClassDefinition> relavantRelationshipClassDefns = relationshipClassDefinitions.Where(definition =>
                                                                                                                           definition.GetOriginClass().Contains(table.GetName()) ||
                                                                                                                           definition.GetDestinationClass().Contains(table.GetName()));
             IEnumerable <string> relationshipClassNames = relavantRelationshipClassDefns.Select(definition => definition.GetName());
             lock (_lockCollections) _relationshipClasses.AddRange(new ObservableCollection <string>(relationshipClassNames));
         }
     });
 }
Example #4
0
        private async Task <bool> ExecuteVisibilityRLOS()
        {
            bool success = false;

            try
            {
                // Check surface spatial reference
                var surfaceSR = await GetSpatialReferenceFromLayer(SelectedSurfaceName);

                if (surfaceSR == null || !surfaceSR.IsProjected)
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.RLOSUserPrompt, VisibilityLibrary.Properties.Resources.RLOSUserPromptCaption);
                    return(false);
                }

                var observerPoints = new ObservableCollection <AddInPoint>(RLOS_ObserversInExtent.Select(x => x.AddInPoint).Union(ObserverInExtentPoints));
                // Warn if Image Service layer
                Layer surfaceLayer = GetLayerFromMapByName(SelectedSurfaceName);
                if (surfaceLayer is ImageServiceLayer)
                {
                    MessageBoxResult mbr = MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgLayerIsImageService,
                                                           VisibilityLibrary.Properties.Resources.CaptionLayerIsImageService, MessageBoxButton.YesNo);

                    if (mbr == MessageBoxResult.No)
                    {
                        System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                        return(false);
                    }
                }

                //Validate Dataframe Spatial reference with surface spatial reference
                if (MapView.Active.Map.SpatialReference.Wkid != surfaceSR.Wkid)
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.LOSDataFrameMatch, VisibilityLibrary.Properties.Resources.LOSSpatialReferenceCaption);
                    return(false);
                }

                await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                {
                    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(CoreModule.CurrentProject.DefaultGeodatabasePath))))
                    {
                        executionCounter              = 0;
                        int featureDataSetSuffix      = 0;
                        var enterpriseDefinitionNames = geodatabase.GetDefinitions <FeatureDatasetDefinition>().Where(i => i.GetName().StartsWith(VisibilityLibrary.Properties.Resources.RLOSFeatureDatasetName)).Select(i => i.GetName()).ToList();
                        foreach (var defName in enterpriseDefinitionNames)
                        {
                            int n;
                            bool isNumeric = int.TryParse(Regex.Match(defName, @"\d+$").Value, out n);
                            if (isNumeric)
                            {
                                featureDataSetSuffix = featureDataSetSuffix < n ? n : featureDataSetSuffix;
                            }
                        }
                        featureDataSetSuffix = enterpriseDefinitionNames.Count > 0 ? featureDataSetSuffix + 1 : 0;

                        var observerLyrSuffix         = GetLayerSuffix(VisibilityLibrary.Properties.Resources.LLOSObserversLayerName, geodatabase);
                        var convertedPolygonLyrSuffix = GetLayerSuffix(VisibilityLibrary.Properties.Resources.RLOSConvertedPolygonsLayerName, geodatabase);
                        var outputLyrSuffix           = GetLayerSuffix(VisibilityLibrary.Properties.Resources.RLOSOutputLayerName, geodatabase);
                        var maskLyrSuffix             = GetLayerSuffix(VisibilityLibrary.Properties.Resources.RLOSMaskLayerName, geodatabase);

                        executionCounter = new List <int> {
                            featureDataSetSuffix, observerLyrSuffix, convertedPolygonLyrSuffix, outputLyrSuffix, maskLyrSuffix
                        }.Max();
                    }
                });

                //Create Feature dataset
                success = await FeatureClassHelper.CreateFeatureDataset(FeatureDatasetName);

                if (!success)
                {
                    return(false);
                }

                success = await FeatureClassHelper.CreateLayer(FeatureDatasetName, ObserversLayerName, "POINT", true, true);

                if (!success)
                {
                    return(false);
                }

                // add fields for observer offset

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetWithZFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.IsOutOfExtentFieldName, "SHORT");

                // add observer points to feature layer
                await FeatureClassHelper.CreatingFeatures(ObserversLayerName, observerPoints, GetAsMapZUnits(surfaceSR, ObserverOffset.Value));

                //execute only if points are available in surface extent
                if (ObserverInExtentPoints.Any() || RLOS_ObserversInExtent.Any())
                {
                    // update with surface information
                    success = await FeatureClassHelper.AddSurfaceInformation(ObserversLayerName, SelectedSurfaceName, VisibilityLibrary.Properties.Resources.ZFieldName);

                    if (!success)
                    {
                        return(false);
                    }

                    // Visibility

                    var observerOffsetInMapZUnits     = GetAsMapZUnits(surfaceSR, ObserverOffset.Value);
                    var surfaceOffsetInMapZUnits      = GetAsMapZUnits(surfaceSR, SurfaceOffset);
                    var minDistanceInMapUnits         = GetAsMapUnits(surfaceSR, MinDistance);
                    var maxDistanceInMapUnits         = GetAsMapUnits(surfaceSR, MaxDistance);
                    var horizontalStartAngleInDegrees = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, LeftHorizontalFOV);
                    var horizontalEndAngleInDegrees   = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, RightHorizontalFOV);
                    var verticalUpperAngleInDegrees   = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, TopVerticalFOV);
                    var verticalLowerAngleInDegrees   = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, BottomVerticalFOV);

                    await FeatureClassHelper.UpdateShapeWithZ(ObserversLayerName, VisibilityLibrary.Properties.Resources.ZFieldName, observerOffsetInMapZUnits);

                    await CreateMask(RLOSMaskLayerName, minDistanceInMapUnits, maxDistanceInMapUnits, horizontalStartAngleInDegrees,
                                     horizontalEndAngleInDegrees, surfaceSR, observerPoints);

                    string maxRangeMaskFeatureClassName = CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + RLOSMaskLayerName;
                    var    environments = Geoprocessing.MakeEnvironmentArray(mask: maxRangeMaskFeatureClassName, overwriteoutput: true);

                    var rlosOutputLayer = CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + RLOSOutputLayerName;


                    success = await FeatureClassHelper.CreateVisibility(SelectedSurfaceName, ObserversLayerName,
                                                                        rlosOutputLayer,
                                                                        observerOffsetInMapZUnits, surfaceOffsetInMapZUnits,
                                                                        minDistanceInMapUnits, maxDistanceInMapUnits,
                                                                        horizontalStartAngleInDegrees, horizontalEndAngleInDegrees,
                                                                        verticalUpperAngleInDegrees, verticalLowerAngleInDegrees,
                                                                        ShowNonVisibleData,
                                                                        environments,
                                                                        false);

                    if (!success)
                    {
                        return(false);
                    }

                    var rlosConvertedPolygonsLayer = CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + RLOSConvertedPolygonsLayerName;

                    string rangeFanMaskFeatureClassName = string.Empty;
                    if ((MinDistance > 0) || !((horizontalStartAngleInDegrees == 0.0) && (horizontalEndAngleInDegrees == 360.0)))
                    {
                        string RLOSRangeFanMaskLayerName = "RangeFan_" + RLOSMaskLayerName;
                        rangeFanMaskFeatureClassName = CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + RLOSRangeFanMaskLayerName;

                        await CreateMask(RLOSRangeFanMaskLayerName, minDistanceInMapUnits, maxDistanceInMapUnits, horizontalStartAngleInDegrees,
                                         horizontalEndAngleInDegrees, surfaceSR, observerPoints, true);
                    }

                    success = await FeatureClassHelper.IntersectOutput(rlosOutputLayer, rlosConvertedPolygonsLayer, false, "Value", rangeFanMaskFeatureClassName);

                    if (!success)
                    {
                        return(false);
                    }
                }

                // add observer points present out of extent to feature layer
                var outOfExtent = new ObservableCollection <AddInPoint>(RLOS_ObserversOutOfExtent.Select(x => x.AddInPoint).Union(ObserverOutExtentPoints));
                await FeatureClassHelper.CreatingFeatures(ObserversLayerName, outOfExtent, GetAsMapZUnits(surfaceSR, ObserverOffset.Value), VisibilityLibrary.Properties.Resources.IsOutOfExtentFieldName);

                await FeatureClassHelper.CreateUniqueValueRenderer(GetLayerFromMapByName(RLOSConvertedPolygonsLayerName) as FeatureLayer, ShowNonVisibleData, RLOSConvertedPolygonsLayerName, ShowClassicViewshed);

                var observersLayer = GetLayerFromMapByName(ObserversLayerName) as FeatureLayer;

                if (observersLayer != null)
                {
                    await FeatureClassHelper.CreateRLOSObserversRenderer(observersLayer as FeatureLayer);
                }

                await FeatureClassHelper.Delete(RLOSOutputLayerName);

                //await FeatureClassHelper.Delete(RLOSMaskLayerName);

                // Eventually we will add the new layers to a new group layer for each run
                // Currently not working in current release of Pro.
                // From Roshan Herbert - I just spoke with the Dev who wrote the MoveLayer method. Apparently this a known issue.
                //                       We have bug to fix this and plan to fix it in the next release.
                List <Layer> layerList                  = new List <Layer>();
                var          observersLayerFromMap      = GetLayerFromMapByName(ObserversLayerName);
                var          RLOSConvertedPolygonsLayer = GetLayerFromMapByName(RLOSConvertedPolygonsLayerName);

                if (observersLayerFromMap != null)
                {
                    layerList.Add(observersLayerFromMap);
                }
                if (RLOSConvertedPolygonsLayer != null)
                {
                    layerList.Add(GetLayerFromMapByName(RLOSConvertedPolygonsLayerName));
                }

                await FeatureClassHelper.MoveLayersToGroupLayer(layerList, FeatureDatasetName);

                //string groupName = "RLOS Group";
                //if (executionCounter > 0)
                //    groupName = string.Format("{0}_{1}", groupName, executionCounter.ToString());

                //await FeatureClassHelper.CreateGroupLayer(layerList, groupName);

                // for now we are not resetting after a run of the tool
                //await Reset(true);

                // Get the extent of the output layer and zoom to extent
                var layer = GetLayerFromMapByName(RLOSConvertedPolygonsLayerName);
                if (layer != null)
                {
                    var envelope = await QueuedTask.Run(() => layer.QueryExtent());
                    await ZoomToExtent(envelope);
                }

                var surfaceEnvelope = await GetSurfaceEnvelope();
                await DisplayOutOfExtentMsg();

                success = true;
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                success = false;
            }

            return(success);
        }
Example #5
0
        private async void OpenGDB()
        {
            if (_executeQuery)
            {
                return;
            }
            if (_gdbPath.IsEmpty())
            {
                return;
            }
            _executeQuery = true;
            _timer.Start();
            OnPropertyChanged("IsExecutingQuery");
            _tables.Clear();

            if (_rows.Count > 0)
            {
                _rows.Clear();
                _rows = new ObservableCollection <DynamicDataRow>();
                ExtendListView.Columns = null;
                OnPropertyChanged("Rows");
            }

            TableHasNoRows    = "";
            SelectedTableName = "";

            try {
                await TaskUtils.StartSTATask <int>(() => {
                    using (Geodatabase gdb = new Geodatabase(
                               new FileGeodatabaseConnectionPath(new Uri(_gdbPath, UriKind.Absolute)))) {
                        IReadOnlyList <Definition> fcList = gdb.GetDefinitions <FeatureClassDefinition>();
                        IReadOnlyList <Definition> tables = gdb.GetDefinitions <TableDefinition>();

                        //////Uncomment for just Feature class in Feature Datasets
                        ////IReadOnlyList<Definition> fdsList = gdb.GetDefinitions<FeatureDatasetDefinition>();

                        lock (_theLock) {
                            //Feature class
                            foreach (var fcDef in fcList)
                            {
                                _tables.Add(TableString(fcDef as TableDefinition));
                            }
                            //Tables
                            foreach (var def in tables)
                            {
                                _tables.Add(TableString(def as TableDefinition));
                            }

                            //////Uncomment for just Feature class in Feature Datasets
                            ////foreach (var fdsDef in fdsList) {
                            ////    IReadOnlyList<Definition> tableDefsInDataset = gdb.GetRelatedDefinitions(fdsDef,
                            ////        DefinitionRelationshipType.DatasetInFeatureDataset);

                            ////    foreach (var def in tableDefsInDataset) {
                            ////        if (def.DatasetType == DatasetType.FeatureClass)
                            ////            _tables.Add(TableString(def as TableDefinition));
                            ////    }
                            ////}
                        }
                    }
                    return(0);
                });
            }
            finally {
                _timer.Stop();
                if (_tables.Count > 0)
                {
                    SelectedTableName = _tables[0];
                }
                else
                {
                    MessageBox.Show("No tables or feature datasets read", _gdbPath);
                }
                _executeQuery = false;
                OnPropertyChanged("IsExecutingQuery");
            }
        }
Example #6
0
        private async Task <bool> ExecuteVisibilityLLOS()
        {
            bool success = false;

            try
            {
                // Check surface spatial reference
                var surfaceSR = await GetSpatialReferenceFromLayer(SelectedSurfaceName);

                if (surfaceSR == null || !surfaceSR.IsProjected)
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.RLOSUserPrompt, VisibilityLibrary.Properties.Resources.RLOSUserPromptCaption);

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        TargetAddInPoints.Clear();
                        ObserverAddInPoints.Clear();
                        ObserverInExtentPoints.Clear();
                        TargetInExtentPoints.Clear();
                        ObserverOutExtentPoints.Clear();
                        TargetOutExtentPoints.Clear();
                        ClearTempGraphics();
                    });

                    await Reset(true);

                    return(false);
                }

                if (string.IsNullOrEmpty(SelectedSurfaceName))
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgSurfaceLayerNotFound,
                                    VisibilityLibrary.Properties.Resources.CaptionError, MessageBoxButton.OK);
                    return(true);
                }

                //Validate Dataframe Spatial reference with surface spatial reference
                IsElevationSurfaceValid = ValidateElevationSurface(MapView.Active.Map, SelectedSurfaceName);
                if (!await IsElevationSurfaceValid)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(VisibilityLibrary.Properties.Resources.LOSDataFrameMatch, VisibilityLibrary.Properties.Resources.LOSSpatialReferenceCaption);
                    SetErrorTemplate(false);
                    return(true);
                }
                else
                {
                    SetErrorTemplate(true);
                }

                var observerPoints = new ObservableCollection <AddInPoint>(LLOS_ObserversInExtent.Select(x => x.AddInPoint).Union(ObserverInExtentPoints));
                var targetPoints   = new ObservableCollection <AddInPoint>(LLOS_TargetsInExtent.Select(x => x.AddInPoint).Union(TargetInExtentPoints));
                // Warn if Image Service layer
                Layer surfaceLayer = GetLayerFromMapByName(SelectedSurfaceName);
                if (surfaceLayer is ImageServiceLayer)
                {
                    MessageBoxResult mbr = MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgLayerIsImageService,
                                                           VisibilityLibrary.Properties.Resources.CaptionLayerIsImageService, MessageBoxButton.YesNo);

                    if (mbr == MessageBoxResult.No)
                    {
                        System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                        return(false);
                    }
                }



                await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                {
                    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(CoreModule.CurrentProject.DefaultGeodatabasePath))))
                    {
                        executionCounter              = 0;
                        int featureDataSetSuffix      = 0;
                        var enterpriseDefinitionNames = geodatabase.GetDefinitions <FeatureDatasetDefinition>().Where(i => i.GetName().StartsWith(VisibilityLibrary.Properties.Resources.LLOSFeatureDatasetName)).Select(i => i.GetName()).ToList();
                        foreach (var defName in enterpriseDefinitionNames)
                        {
                            int n;
                            bool isNumeric = int.TryParse(Regex.Match(defName, @"\d+$").Value, out n);
                            if (isNumeric)
                            {
                                featureDataSetSuffix = featureDataSetSuffix < n ? n : featureDataSetSuffix;
                            }
                        }
                        featureDataSetSuffix = enterpriseDefinitionNames.Count > 0 ? featureDataSetSuffix + 1 : 0;

                        var observerLyrSuffix   = GetLayerSuffix(VisibilityLibrary.Properties.Resources.LLOSObserversLayerName, geodatabase);
                        var targetLyrSuffix     = GetLayerSuffix(VisibilityLibrary.Properties.Resources.LLOSTargetsLayerName, geodatabase);
                        var sightLinesLyrSuffix = GetLayerSuffix(VisibilityLibrary.Properties.Resources.LLOSSightLinesLayerName, geodatabase);
                        var outputLyrSuffix     = GetLayerSuffix(VisibilityLibrary.Properties.Resources.LLOSOutputLayerName, geodatabase);

                        executionCounter = new List <int> {
                            featureDataSetSuffix, observerLyrSuffix, targetLyrSuffix, sightLinesLyrSuffix, outputLyrSuffix
                        }.Max();
                    }
                });

                //Create Feature dataset
                success = await FeatureClassHelper.CreateFeatureDataset(FeatureDatasetName);

                if (!success)
                {
                    return(false);
                }

                success = await FeatureClassHelper.CreateLayer(FeatureDatasetName, ObserversLayerName, "POINT", true, true);

                if (!success)
                {
                    return(false);
                }

                // add fields for observer offset

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetWithZFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.TarIsVisFieldName, "SHORT");

                success = await FeatureClassHelper.CreateLayer(FeatureDatasetName, TargetsLayerName, "POINT", true, true);

                if (!success)
                {
                    return(false);
                }

                // add fields for target offset

                await FeatureClassHelper.AddFieldToLayer(TargetsLayerName, VisibilityLibrary.Properties.Resources.OffsetFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(TargetsLayerName, VisibilityLibrary.Properties.Resources.OffsetWithZFieldName, "DOUBLE");

                await FeatureClassHelper.AddFieldToLayer(TargetsLayerName, VisibilityLibrary.Properties.Resources.NumOfObserversFieldName, "SHORT");

                // add observer points to feature layer
                await FeatureClassHelper.CreatingFeatures(ObserversLayerName, observerPoints, GetAsMapZUnits(surfaceSR, ObserverOffset.Value));

                // add target points to feature layer
                await FeatureClassHelper.CreatingFeatures(TargetsLayerName, targetPoints, GetAsMapZUnits(surfaceSR, TargetOffset.Value));

                // update with surface information
                success = await FeatureClassHelper.AddSurfaceInformation(ObserversLayerName, SelectedSurfaceName, VisibilityLibrary.Properties.Resources.ZFieldName);

                if (!success)
                {
                    return(false);
                }

                success = await FeatureClassHelper.AddSurfaceInformation(TargetsLayerName, SelectedSurfaceName, VisibilityLibrary.Properties.Resources.ZFieldName);

                if (!success)
                {
                    return(false);
                }

                await FeatureClassHelper.UpdateShapeWithZ(ObserversLayerName, VisibilityLibrary.Properties.Resources.ZFieldName, GetAsMapZUnits(surfaceSR, ObserverOffset.Value));

                await FeatureClassHelper.UpdateShapeWithZ(TargetsLayerName, VisibilityLibrary.Properties.Resources.ZFieldName, GetAsMapZUnits(surfaceSR, TargetOffset.Value));

                // create sight lines
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                success = await FeatureClassHelper.CreateSightLines(ObserversLayerName,
                                                                    TargetsLayerName,
                                                                    CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + SightLinesLayerName,
                                                                    VisibilityLibrary.Properties.Resources.OffsetWithZFieldName,
                                                                    VisibilityLibrary.Properties.Resources.OffsetWithZFieldName);

                if (!success)
                {
                    return(false);
                }

                // LOS
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                success = await FeatureClassHelper.CreateLOS(SelectedSurfaceName,
                                                             CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + SightLinesLayerName,
                                                             CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + OutputLayerName);

                if (!success)
                {
                    return(false);
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                // join fields with sight lines

                await FeatureClassHelper.JoinField(CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + SightLinesLayerName,
                                                   "OID",
                                                   CoreModule.CurrentProject.DefaultGeodatabasePath + System.IO.Path.DirectorySeparatorChar + FeatureDatasetName + System.IO.Path.DirectorySeparatorChar + OutputLayerName,
                                                   "SourceOID",
                                                   new string[] { "TarIsVis" });

                // gather results for updating observer and target layers
                var sourceOIDs = await FeatureClassHelper.GetSourceOIDs(OutputLayerName);

                //if (sourceOIDs.Count > 0)
                //{
                var visStats = await FeatureClassHelper.GetVisibilityStats(sourceOIDs, SightLinesLayerName);

                await FeatureClassHelper.UpdateLayersWithVisibilityStats(visStats, ObserversLayerName, TargetsLayerName);

                //}

                var observersLayer  = GetLayerFromMapByName(ObserversLayerName) as FeatureLayer;
                var targetsLayer    = GetLayerFromMapByName(TargetsLayerName) as FeatureLayer;
                var sightLinesLayer = GetLayerFromMapByName(SightLinesLayerName) as FeatureLayer;
                var outputLayer     = GetLayerFromMapByName(OutputLayerName) as FeatureLayer;

                var observerOutOfExtent = new ObservableCollection <AddInPoint>(LLOS_ObserversOutOfExtent.Select(x => x.AddInPoint).Union(ObserverOutExtentPoints));
                // add observer points present out of extent to feature layer
                await FeatureClassHelper.CreatingFeatures(ObserversLayerName, observerOutOfExtent, GetAsMapZUnits(surfaceSR, TargetOffset.Value), VisibilityLibrary.Properties.Resources.TarIsVisFieldName);

                var targetOutOfExtent = new ObservableCollection <AddInPoint>(LLOS_TargetsOutOfExtent.Select(x => x.AddInPoint).Union(TargetOutExtentPoints));
                // add target points present out of extent to feature layer
                await FeatureClassHelper.CreatingFeatures(TargetsLayerName, targetOutOfExtent, GetAsMapZUnits(surfaceSR, TargetOffset.Value), VisibilityLibrary.Properties.Resources.NumOfObserversFieldName);

                if (observersLayer != null && targetsLayer != null && sightLinesLayer != null && outputLayer != null)
                {
                    await FeatureClassHelper.CreateObserversRenderer(GetLayerFromMapByName(ObserversLayerName) as FeatureLayer);

                    await FeatureClassHelper.CreateTargetsRenderer(GetLayerFromMapByName(TargetsLayerName) as FeatureLayer);

                    await FeatureClassHelper.CreateTargetLayerLabels(GetLayerFromMapByName(TargetsLayerName) as FeatureLayer);

                    await FeatureClassHelper.CreateVisCodeRenderer(GetLayerFromMapByName(SightLinesLayerName) as FeatureLayer,
                                                                   VisibilityLibrary.Properties.Resources.TarIsVisFieldName,
                                                                   1,
                                                                   0,
                                                                   ColorFactory.Instance.WhiteRGB,
                                                                   ColorFactory.Instance.BlackRGB,
                                                                   6.0,
                                                                   6.0);

                    await FeatureClassHelper.CreateVisCodeRenderer(GetLayerFromMapByName(OutputLayerName) as FeatureLayer,
                                                                   VisibilityLibrary.Properties.Resources.VisCodeFieldName,
                                                                   1,
                                                                   2,
                                                                   ColorFactory.Instance.GreenRGB,
                                                                   ColorFactory.Instance.RedRGB,
                                                                   5.0,
                                                                   3.0);

                    //await Reset(true);

                    //string groupName = "LLOS Group";
                    //if (executionCounter > 0)
                    //    groupName = string.Format("{0}_{1}", groupName, executionCounter.ToString());

                    //await FeatureClassHelper.CreateGroupLayer(layerList, groupName);

                    // for now we are not resetting after a run of the tool
                    //await Reset(true);


                    List <Layer> lyrList = new List <Layer>();
                    lyrList.Add(observersLayer);
                    lyrList.Add(targetsLayer);
                    lyrList.Add(outputLayer);
                    lyrList.Add(sightLinesLayer);

                    await FeatureClassHelper.MoveLayersToGroupLayer(lyrList, FeatureDatasetName);

                    var envelope = await QueuedTask.Run(() => outputLayer.QueryExtent());
                    await ZoomToExtent(envelope);

                    var surfaceEnvelope = await GetSurfaceEnvelope();
                    await DisplayOutOfExtentMsg(surfaceEnvelope);

                    success = true;
                }
                else
                {
                    success = false;
                }
            }
            catch (Exception ex)
            {
                success = false;
                Debug.Print(ex.Message);
            }

            return(success);
        }
Example #7
0
 public async Task GetFeatureClassesInRelationshipClassAsync()
 {
     await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
     {
         using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
         {
             IReadOnlyList <RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions <RelationshipClassDefinition>();
             foreach (var relationshipClassDefintion in relationshipClassDefinitions)
             {
                 IReadOnlyList <Definition> definitions = geodatabase.GetRelatedDefinitions(relationshipClassDefintion,
                                                                                            DefinitionRelationshipType.DatasetsRelatedThrough);
                 foreach (var definition in definitions)
                 {
                     MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}");
                 }
             }
         }
     });
 }
        private void LookupItems()
        {
            QueuedTask.Run(() =>
            {
                using (Geodatabase fileGeodatabase = new Geodatabase(GdbPath))
                {
                    IReadOnlyList<FeatureClassDefinition> fcdefinitions = fileGeodatabase.GetDefinitions<FeatureClassDefinition>();
                    lock (_lockGdbDefinitions)
                    {
                        _gdbDefinitions.Clear();
                        foreach (var definition in fcdefinitions)
                        {
                            _gdbDefinitions.Add(new GdbItem() {Name = definition.GetName(), Type = definition.DatasetType.ToString()});
                        }
                    }
                    IReadOnlyList<TableDefinition> tbdefinitions = fileGeodatabase.GetDefinitions<TableDefinition>();
                    lock (_lockGdbDefinitions)
                    {
                        foreach (var definition in tbdefinitions)
                        {
                            _gdbDefinitions.Add(new GdbItem() { Name = definition.GetName(), Type = definition.DatasetType.ToString() });
                        }
                    }

                }
            }).ContinueWith(t =>
            {
                if (t.Exception == null) return;
                var aggException = t.Exception.Flatten();
                foreach (var exception in aggException.InnerExceptions)
                    System.Diagnostics.Debug.WriteLine(exception.Message);
            });
        }
        protected override async void OnClick()
        {
            try
            {
                // this connection file has no user/password entered
                var sdeConProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
                {
                    AuthenticationMode = AuthenticationMode.DBMS,
                    Instance           = @"localhost"
                };
                // prompt for username / password using a ProWindow
                var userPwDlg = new ProWindowDialog();
                // ProWindowDialog uses Module1.ConnectionString to display
                // initial values
                Module1.ConnectionString = $@"{sdeConProperties.AuthenticationMode} {sdeConProperties.DBMS} {sdeConProperties.Instance}";
                userPwDlg.Owner          = FrameworkApplication.Current.MainWindow;
                userPwDlg.Closed        += (o, e) => {
                    // in case special processing after dialog closed has be done
                    System.Diagnostics.Debug.WriteLine("Pro Window Dialog closed");
                };
                var dlgResult = userPwDlg.ShowDialog();
                MessageBox.Show($@"ProWindow Dialog was closed with ShowDialog return value: {dlgResult.Value}");
                if (Module1.HasCredentials == false)
                {
                    return;
                }
                sdeConProperties.User     = Module1.UserName;
                sdeConProperties.Password = Module1.Password;

                var hasConnected = await QueuedTask.Run(() =>
                {
                    bool bConnected = false;
                    try
                    {
                        using (Geodatabase sqlServerGeodatabase = new Geodatabase(sdeConProperties))
                        {
                            IReadOnlyList <Definition> fcList = sqlServerGeodatabase.GetDefinitions <FeatureClassDefinition>();
                            foreach (var fc in fcList)
                            {
                                System.Diagnostics.Debug.WriteLine(fc.GetName());
                            }
                            // Use the geodatabase.
                            bConnected = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($@"Unable to connect: {Module1.ConnectionString} reason: {ex.Message}");
                    }
                    return(bConnected);
                });

                if (hasConnected)
                {
                    MessageBox.Show("Connected");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Error: {ex.Message}");
            }
        }
        public async Task <bool> ShouldAddInBeEnabledAsync(ProSymbolUtilities.SupportedStandardsType standard)
        {
            _schemaExists = false;

            //If we can get the database, then enable the add-in
            if (Project.Current == null)
            {
                //No open project
                return(false);
            }

            //Get database with correct schema
            try
            {
                IEnumerable <GDBProjectItem> gdbProjectItems = Project.Current.GetItems <GDBProjectItem>();
                await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                {
                    foreach (GDBProjectItem gdbProjectItem in gdbProjectItems)
                    {
                        if (gdbProjectItem.Name == "map.gdb") // ignore the project Map GDB
                        {
                            continue;
                        }

                        using (Datastore datastore = gdbProjectItem.GetDatastore())
                        {
                            //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
                            if (datastore is UnknownDatastore)
                            {
                                continue;
                            }

                            Geodatabase geodatabase = datastore as Geodatabase;
                            if (geodatabase == null)
                            {
                                continue;
                            }

                            //Set up Fields to check
                            List <string> fieldsToCheck = new List <string>();

                            if (standard == ProSymbolUtilities.SupportedStandardsType.mil2525c_b2)
                            {
                                fieldsToCheck.Add("extendedfunctioncode");
                            }
                            else
                            {   // 2525d
                                fieldsToCheck.Add("symbolset");
                                fieldsToCheck.Add("symbolentity");
                            }

                            // Reset schema data model exists to false for each feature class
                            Dictionary <string, bool> featureClassExists = GetFeatureClassExistsMap(standard, geodatabase);

                            IReadOnlyList <FeatureClassDefinition> featureClassDefinitions = geodatabase.GetDefinitions <FeatureClassDefinition>();

                            bool stopLooking = false;
                            foreach (FeatureClassDefinition featureClassDefinition in featureClassDefinitions)
                            {
                                // stop looking after the first feature class not found
                                if (stopLooking)
                                {
                                    break;
                                }

                                string featureClassName = featureClassDefinition.GetName();

                                if (featureClassExists.ContainsKey(featureClassName))
                                {
                                    //Feature Class Exists!  Check for fields
                                    bool fieldsExist = true;
                                    foreach (string fieldName in fieldsToCheck)
                                    {
                                        IEnumerable <Field> foundFields = featureClassDefinition.GetFields().Where(x => x.Name == fieldName);

                                        if (foundFields.Count() < 1)
                                        {
                                            fieldsExist = false;
                                            stopLooking = true;
                                            break;
                                        }
                                    }

                                    featureClassExists[featureClassName] = fieldsExist;
                                }
                                else
                                {
                                    //Key doesn't exist, so ignore
                                }
                            }

                            bool isSchemaComplete = true;

                            foreach (KeyValuePair <string, bool> pair in featureClassExists)
                            {
                                if (pair.Value == false)
                                {
                                    isSchemaComplete = false;
                                    break;
                                }
                            }

                            //Check if schema is all there
                            if (isSchemaComplete)
                            {
                                //Save geodatabase path to use as the selected database
                                _databaseName = gdbProjectItem.Path;
                                _schemaExists = true;

                                break;
                            }
                        }
                    }
                });
            }
            catch (Exception exception)
            {
                System.Diagnostics.Trace.WriteLine(exception.Message);
            }

            return(SchemaExists);
        }
        private async void OpenGDB() {
            if (_executeQuery)
                return;
            if (_gdbPath.IsEmpty())
                return;
            _executeQuery = true;
            _timer.Start();
            OnPropertyChanged("IsExecutingQuery");
            _tables.Clear();

            if (_rows.Count > 0) {
                _rows.Clear();
                _rows = new ObservableCollection<DynamicDataRow>();
                ExtendListView.Columns = null;
                OnPropertyChanged("Rows");
            }

            TableHasNoRows = "";
            SelectedTableName = "";

            try {
                await TaskUtils.StartSTATask<int>(() => {
                    using (Geodatabase gdb = new Geodatabase(_gdbPath)) {

                        IReadOnlyList<Definition> fcList = gdb.GetDefinitions<FeatureClassDefinition>();
                        IReadOnlyList<Definition> tables = gdb.GetDefinitions<TableDefinition>();

                        //////Uncomment for just Feature class in Feature Datasets
                        ////IReadOnlyList<Definition> fdsList = gdb.GetDefinitions<FeatureDatasetDefinition>();
                        
                        lock (_theLock) {
                            //Feature class
                            foreach (var fcDef in fcList) {
                                _tables.Add(TableString(fcDef as TableDefinition));
                            }
                            //Tables
                            foreach (var def in tables) {
                                _tables.Add(TableString(def as TableDefinition));
                            }

                            //////Uncomment for just Feature class in Feature Datasets
                            ////foreach (var fdsDef in fdsList) {
                            ////    IReadOnlyList<Definition> tableDefsInDataset = gdb.GetRelatedDefinitions(fdsDef,
                            ////        DefinitionRelationshipType.DatasetInFeatureDataset);

                            ////    foreach (var def in tableDefsInDataset) {
                            ////        if (def.DatasetType == DatasetType.FeatureClass)
                            ////            _tables.Add(TableString(def as TableDefinition));
                            ////    }
                            ////}
    

                            
                        }
                    }
                    return 0;
                });
            }
            finally {
                _timer.Stop();
                if (_tables.Count > 0)
                    SelectedTableName = _tables[0];
                else {
                    MessageBox.Show("No tables or feature datasets read", _gdbPath);
                }
                _executeQuery = false;
                OnPropertyChanged("IsExecutingQuery");
            }
            
        }
Example #12
0
        // TODO: we may be able to deprecate this method (GDBContainsSchema) and use the method above (GDBContainsMilitaryOverlay)
        public async Task <bool> GDBContainsSchema(GDBProjectItem gdbProjectItem,
                                                   ProSymbolUtilities.SupportedStandardsType standard)
        {
            bool isSchemaComplete = await
                                    ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run <bool>(() =>
            {
                if (gdbProjectItem == null)
                {
                    return(false);
                }

                using (Datastore datastore = gdbProjectItem.GetDatastore())
                {
                    // Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
                    if (datastore is UnknownDatastore)
                    {
                        return(false);
                    }

                    Geodatabase geodatabase = datastore as Geodatabase;
                    if (geodatabase == null)
                    {
                        return(false);
                    }

                    // Set up Fields to check
                    List <string> fieldsToCheck = new List <string>();

                    if (ProSymbolUtilities.IsLegacyStandard(standard))
                    {
                        fieldsToCheck.Add("extendedfunctioncode");
                    }
                    else
                    {   // 2525d / app6d
                        fieldsToCheck.Add("symbolset");
                        fieldsToCheck.Add("symbolentity");
                    }

                    // Reset schema data model exists to false for each feature class
                    Dictionary <string, bool> featureClassExists = GetFeatureClassExistsMap(standard, geodatabase);

                    IReadOnlyList <FeatureClassDefinition> featureClassDefinitions = geodatabase.GetDefinitions <FeatureClassDefinition>();

                    bool stopLooking = false;
                    foreach (FeatureClassDefinition featureClassDefinition in featureClassDefinitions)
                    {
                        // Stop looking after the first feature class not found
                        if (stopLooking)
                        {
                            return(false);
                        }

                        string featureClassName = featureClassDefinition.GetName();

                        if (featureClassExists.ContainsKey(featureClassName))
                        {
                            // Feature Class Exists. Check for fields
                            bool fieldsExist = true;

                            // Don't do this for remote databases (too slow)
                            if (geodatabase.GetGeodatabaseType() != GeodatabaseType.RemoteDatabase)
                            {
                                foreach (string fieldName in fieldsToCheck)
                                {
                                    IEnumerable <Field> foundFields = featureClassDefinition.GetFields().Where(x => x.Name == fieldName);

                                    if (foundFields.Count() < 1)
                                    {
                                        fieldsExist = false;
                                        return(false);
                                    }
                                }
                            }

                            featureClassExists[featureClassName] = fieldsExist;
                        }
                        else
                        {
                            // Key doesn't exist, so ignore
                        }
                    }

                    foreach (KeyValuePair <string, bool> pair in featureClassExists)
                    {
                        if (pair.Value == false)
                        {
                            return(false);
                        }
                    }

                    // If here, schema is complete
                    // Save geodatabase path to use as the selected database
                    _databaseName = gdbProjectItem.Path;
                    _schemaExists = true;
                    _standard     = standard;

                    return(true);
                }
            });

            return(isSchemaComplete);
        }