Exemplo n.º 1
0
        /// <summary>
        /// Creates the report
        /// </summary>
        /// <returns></returns>
        private async Task CreateReport()
        {
            ReportDataSource reportDataSource = null;
            Report           report           = null;
            //_isCreateReport = false;
            var reportTemplate = await GetReportTemplate(SelectedReportTemplate);

            await QueuedTask.Run(() =>
            {
                //Adding all fields to the report
                List <CIMReportField> reportFields = new List <CIMReportField>();
                var selectedReportFields           = ReportFields.Where((fld) => fld.IsSelected);
                foreach (var rfld in selectedReportFields)
                {
                    var cimReportField = new CIMReportField()
                    {
                        Name = rfld.Name
                    };
                    reportFields.Add(cimReportField);
                    //Defining grouping field
                    if (rfld.Name == SelectedGroupField?.Name)
                    {
                        cimReportField.Group = true;
                    }
                    //To DO: Do sort info here.
                }

                //Report field statistics
                List <ReportFieldStatistic> reportFieldStats = new List <ReportFieldStatistic>();

                if (SelectedStatsField != null)
                {
                    ReportFieldStatistic reportStat = new ReportFieldStatistic();
                    reportStat.Field     = SelectedStatsField.Name;
                    reportStat.Statistic = (FieldStatisticsFlag)Enum.Parse(typeof(FieldStatisticsFlag), SelectedStatsOption);
                    reportFieldStats.Add(reportStat);
                }

                //Set Datasource
                reportDataSource = new ReportDataSource(SelectedLayer, "", IsUseSelection, reportFields);

                try
                {
                    report = ReportFactory.Instance.CreateReport(ReportName, reportDataSource, null, reportFieldStats, reportTemplate, SelectedReportStyle);
                    //_isCreateReport = true;
                }
                catch (System.InvalidOperationException e)
                {
                    if (e.Message.Contains("Group field defined for a non-grouping template"))
                    {
                        MessageBox.Show("A group field cannot be defined for a non-grouping template.");
                    }
                    else if (e.Message.Contains("Grouping template specified but no group field defined"))
                    {
                        MessageBox.Show("A group field should be defined for a grouping template.");
                    }
                }
            });

            //Open the report
            IReportPane iNewReportPane = await ProApp.Panes.CreateReportPaneAsync(report);             //GUI thread
        }
        /// <summary>
        /// Create keyframes centered around a point.
        /// </summary>
        /// <param name="point">The center point around which the keyframes are created.</param>
        internal Task CreateKeyframesAroundPoint(MapPoint point)
        {
            return(QueuedTask.Run(() =>
            {
                var mapView = MapView.Active;
                var degrees = Animation.Settings.Degrees;
                if (mapView == null || degrees == 0)
                {
                    return;
                }

                //Get the camera track from the active map's animation.
                //There will always be only one camera track in the animation.
                var cameraTrack = mapView.Map.Animation.Tracks.OfType <CameraTrack>().First();
                var camera = mapView.Camera;

                //Calculate the number of keys to create.
                var keyEvery = (degrees < 0) ? -10 : 10; //10 degrees
                var numOfKeys = Math.Floor(degrees / keyEvery);
                var remainder = degrees % keyEvery;

                //To maintain a constant speed we need to divide the total time we want the animation to take by the number of degrees of rotation.
                var duration = Animation.Settings.Duration;
                double timeInterval = duration / Math.Abs(degrees);
                double currentTimeSeconds = GetInsertTime(mapView.Map.Animation);

                //Get the distance from the current location to the point we want to rotate around to get the radius.
                var cameraPoint = MapPointBuilder.CreateMapPoint(camera.X, camera.Y, camera.SpatialReference);
                var radius = GeometryEngine.Instance.GeodesicDistance(cameraPoint, point);
                var radian = ((camera.Heading - 90) / 180.0) * Math.PI;

                //If the spatial reference of the point is projected and the unit is not in meters we need to convert the Z values to meters.
                if (!point.SpatialReference.IsGeographic && point.SpatialReference.Unit.ConversionFactor != 1.0)
                {
                    point = MapPointBuilder.CreateMapPoint(point.X, point.Y,
                                                           point.Z * point.SpatialReference.Unit.ConversionFactor, point.SpatialReference);
                }

                //For all geodesic calculations we will use WGS84 so we will project the point if it is not already.
                if (point.SpatialReference.Wkid != SpatialReferences.WGS84.Wkid)
                {
                    var transformation = ProjectionTransformation.Create(point.SpatialReference, SpatialReferences.WGS84);
                    point = GeometryEngine.Instance.ProjectEx(point, transformation) as MapPoint;
                }

                //Create an ellipse around the center point.
                var parameter = new GeodesicEllipseParameter()
                {
                    Center = point.Coordinate2D,
                    SemiAxis1Length = radius,
                    SemiAxis2Length = radius,
                    AxisDirection = radian,
                    LinearUnit = LinearUnit.Meters,
                    OutGeometryType = GeometryType.Polyline,
                    VertexCount = 36
                };
                var ellipse = GeometryEngine.Instance.GeodesicEllipse(parameter, point.SpatialReference) as Polyline;

                //For each key we will progressively rotate around the ellipse and calculate the camera position at each.
                for (int i = 0; i <= numOfKeys; i++)
                {
                    var percentAlong = ((Math.Abs(keyEvery) * i) % 360) / 360.0;
                    if (keyEvery > 0)
                    {
                        percentAlong = 1 - percentAlong;
                    }

                    //Get the camera at the position around the ellipse.
                    camera = OffsetCamera(camera, ellipse, point, percentAlong);

                    //Increment the time by the amount of time per key.
                    if (i != 0)
                    {
                        currentTimeSeconds += (timeInterval * Math.Abs(keyEvery));
                    }

                    //Create a new keyframe for the camera.
                    cameraTrack.CreateKeyframe(camera, TimeSpan.FromSeconds(currentTimeSeconds), AnimationTransition.FixedArc);
                }

                //For any degree rotation left over create a keyframe. For example 155, would have a keyframe every 10 degrees and then one for the final 5 degrees.
                if (remainder != 0.0)
                {
                    var percentAlong = ((Math.Abs(keyEvery) * numOfKeys + Math.Abs(remainder)) % 360) / 360.0;
                    if (remainder > 0)
                    {
                        percentAlong = 1 - percentAlong;
                    }

                    OffsetCamera(camera, ellipse, point, percentAlong);

                    //Increment the time and create the keyframe.
                    currentTimeSeconds += (timeInterval * Math.Abs(remainder));
                    cameraTrack.CreateKeyframe(camera, TimeSpan.FromSeconds(currentTimeSeconds), AnimationTransition.FixedArc);
                }
            }));
        }
Exemplo n.º 3
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);
                }

                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);
                    }
                }

                //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.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);
        }
Exemplo n.º 4
0
        // Set range for feature layer
        // Map Exploration Team Routine
        private Task SetRangeProperties(FeatureLayer ftrLyr, string fieldName, bool hasCustomRange = false, double customMin = 0, double customMax = 1, bool inSingleValueMode = false, int rangeStepCount = 0)
        {
            return(QueuedTask.Run(() =>
            {
                //Get min/max values for the field
                double minValue = 0;
                double maxValue = 0;

                //Calculate min/max if custom range is not defined
                if (!hasCustomRange)
                {
                    int ftrCount = 0;
                    RowCursor rows = ftrLyr.Search(null);
                    while (rows.MoveNext())
                    {
                        ftrCount++;
                    }
                    double[] fieldVals = new double[ftrCount];
                    rows = ftrLyr.Search(null);
                    //Looping through to count
                    int i = 0;
                    while (rows.MoveNext())
                    {
                        object origVal = rows.Current.GetOriginalValue(rows.FindField(fieldName));
                        if (!(origVal is DBNull))
                        {
                            fieldVals[i] = System.Convert.ToDouble(origVal);
                        }
                        i++;
                    }
                    if (fieldVals.Count() > 0)
                    {
                        minValue = fieldVals.Min();
                        maxValue = fieldVals.Max();
                    }
                }
                else
                {
                    minValue = customMin;
                    maxValue = customMax;
                }

                CIMBasicFeatureLayer baseLyr = (CIMBasicFeatureLayer)ftrLyr.GetDefinition();
                CIMFeatureTable ftrTable = baseLyr.FeatureTable;

                //CIMRange theRange = new CIMRange();
                CIMRangeDefinition[] rangeDefn = new CIMRangeDefinition[1];
                rangeDefn[0] = new CIMRangeDefinition();
                rangeDefn[0].FieldName = fieldName;
                rangeDefn[0].Name = fieldName;
                rangeDefn[0].CustomFullExtent = new CIMRange();
                rangeDefn[0].CustomFullExtent.Min = minValue;
                rangeDefn[0].CustomFullExtent.Max = maxValue;

                //Set current range with either step count == 1 OR for some cases with step count == 0
                rangeDefn[0].CurrentRange = new CIMRange();
                rangeDefn[0].CurrentRange.Min = minValue;
                //rangeDefn[0].CurrentRange.Max = (rangeStepCount == 1) ? minValue + 1 : minValue;

                //set range step to 0 if in single value mode and to rangeStepCount otherwise
                rangeDefn[0].CurrentRange.Max = (inSingleValueMode) ? minValue : minValue + rangeStepCount;
                //rangeDefn[0].CurrentRange.Max = maxValue;

                ftrTable.RangeDefinitions = rangeDefn;
                ftrTable.ActiveRangeName = fieldName;
                baseLyr.FeatureTable = ftrTable;
                ftrLyr.SetDefinition(baseLyr);
            }));
        }
Exemplo n.º 5
0
        async public static void MethodSnippets()
        {
            LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
            Layout            layout     = await QueuedTask.Run(() => layoutItem.GetLayout());

            Element element = layout.FindElement("Group Element");


            #region Element_ConvertToGraphics
            //Convert a legend to a graphic and move the Title to the bottom of the legend and also move
            //the label in the contents pane to the bottom of the list.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                Legend leg          = layout.FindElement("Legend") as Legend;
                GroupElement result = leg.ConvertToGraphics().First() as GroupElement;
                Element firstElm    = result.Elements.First(); //Note: Bottom element is first in drawing order.
                foreach (Element elm in result.Elements)
                {
                    if (elm.Name == "Title")
                    {
                        elm.SetY(firstElm.GetY() - 0.25);          //Move title below other legend elements
                        elm.SetTOCPositionAbsolute(result, false); // Move Title item in TOC to bottom as well
                    }
                }
            });

            #endregion Element_ConvertToGraphics

            #region Element_GetSetAnchor
            //Change the element's anchor position

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                Anchor elmAnchor = element.GetAnchor();
                elmAnchor        = Anchor.CenterPoint;

                element.SetAnchor(elmAnchor); //You don't have to get to set; a shortcut would be: element.SetAnchor(Anchor.CenterPoint);
            });

            #endregion Element_GetSetAnchor

            #region Element_GetCustomProperty
            //Get a custom property that has been previously set.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                String custProp = element.GetCustomProperty("MyKeyString");
            });

            #endregion Element_GetCustomProperty

            #region Element_GetSetDefinition
            //Modify an element's CIM properties.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                CIMElement CIMElm = element.GetDefinition();

                //Modify a CIM value

                element.SetDefinition(CIMElm);
            });

            #endregion Element_GetSetDefinition

            #region Element_GetSetHeight
            //Modify an element's hieght.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                double elmHeight = element.GetHeight();
                elmHeight        = 11;

                element.SetHeight(elmHeight); //You don't have to get to set; a shortcut would be: element.SetHieght(11);
            });

            #endregion Element_GetSetHeight

            #region Element_SetLocked
            //Modify an element's locked state if it isn't already

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                if (!element.IsLocked)
                {
                    element.SetLocked(true);
                }
            });

            #endregion Element_GetSetLocked

            #region Element_GetSetLockedAspectRatio
            //Modify an element's aspect ratio.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                bool elmLocked = element.GetLockedAspectRatio();
                elmLocked      = false;                  //Turn off the locked state.

                element.SetLockedAspectRatio(elmLocked); //You don't have to get to set; a shortcut would be: element.SetLockedAspectRatio(false);
            });

            #endregion Element_GetSetLockedAspectRatio

            #region Element_GetSetRotation
            //Modify and element's rotation value.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                double elmRot = element.GetRotation();
                elmRot        = 22.5;

                element.SetRotation(elmRot); //You don't have to get to set; a shortcut would be: element.SetRotation(22.5);
            });

            #endregion Element_GetSetRotation

            #region Element_GetSetWidth
            //Modify an element's width.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                double elmWidth = element.GetWidth();
                elmWidth        = 8.5;

                element.SetWidth(elmWidth); //You don't have to get to set; a shortcut would be: element.SetWidth(8.5);
            });

            #endregion Element_GetSetWidth

            #region Element_GetSetX
            //Modify an element's X position.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                double elmX = element.GetX();
                elmX        = 4.25;

                element.SetX(elmX); //You don't have to get to set; a shortcut would be: element.SetX(4.25);
            });

            #endregion Element_GetSetX

            #region Element_GetSetY
            //Modify an element's Y position.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                double elmY = element.GetY();
                elmY        = 5.5;

                element.SetY(elmY); //You don't have to get to set; a shortcut would be: element.SetY(5.5);
            });

            #endregion Element_GetSetY

            #region Element_SetCustomProperty
            //Set a custom property on an element.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                element.SetCustomProperty("MyKeyString", "MyValueString");
            });

            #endregion Element_SetCustomProperty

            #region Element_SetName
            //Modify an element's name.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                element.SetName("New Name");
            });

            #endregion Element_SetName

            #region Element_SetTOCPositionAbsolute
            //Move an element to the top of the TOC

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                element.SetTOCPositionAbsolute(layout, true);
            });

            #endregion Element_SetTOCPositionAbsolute

            #region Element_SetTOCPositionRelative
            //Move a layout element above an existing layout element.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                element.SetTOCPositionRelative(element, true);
            });

            #endregion Element_SetTOCPositionRelative

            #region Element_SetVisible
            //Modify an element's visibility.

            //Perform on the worker thread
            await QueuedTask.Run(() =>
            {
                element.SetVisible(true); //Turn it on / make visible.
            });

            #endregion Element_SetVisible
        }
Exemplo n.º 6
0
        private void QueueTask(QueuedTask task)
        {
            // Add task to priority queue
            lock (taskPriorityQueue)
            {
                taskPriorityQueue.Enqueue(task);
            }
            if (task.Scheduler != null && task.Scheduler.Priority < 0)
            {
                notifyHighPriorityQueuedTaskEvent.Set();
            }
            else
            {
                notifyQueuedTaskEvent.Set();
            }

            // If necessary, create threads
            if (threads == null)
            {
                lock (lockObject)
                {
                    if (threads == null)
                    {
                        var waitHandles = new WaitHandle[] { notifyThreadExitEvent, notifyHighPriorityQueuedTaskEvent, notifyQueuedTaskEvent };
                        var waitHandlesHighPriorityOnly = new WaitHandle[] { notifyThreadExitEvent, notifyHighPriorityQueuedTaskEvent };
                        threads = new Thread[maximumConcurrencyLevel];
                        for (int i = 0; i < maximumConcurrencyLevel; i++)
                        {
                            int threadIndex = i;
                            threads[i] = new Thread(() =>
                            {
                                while (!threadShouldExit)
                                {
                                    // TODO: ResetEvent, and exit signal
                                    var t = default(QueuedTask);
                                    lock (taskPriorityQueue)
                                    {
                                        if (!taskPriorityQueue.Empty)
                                        {
                                            t = taskPriorityQueue.Dequeue();
                                        }
                                    }

                                    if (t.Task != null)
                                    {
                                        // High priority task (<0) gets an above normal thread priority
                                        if (t.Scheduler.Priority < 0)
                                        {
                                            Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
                                        }

                                        if (t.Scheduler != null)
                                        {
                                            t.Scheduler.TryExecuteTaskInternal(t.Task);
                                        }
                                        else
                                        {
                                            TryExecuteTask(t.Task);
                                        }

                                        if (t.Scheduler.Priority < 0)
                                        {
                                            Thread.CurrentThread.Priority = ThreadPriority.Normal;
                                        }
                                    }
                                    else
                                    {
                                        // If more than one thread, one will be dedicated to high-priority tasks
                                        if (threadIndex == 0 && maximumConcurrencyLevel > 1)
                                        {
                                            WaitHandle.WaitAny(waitHandlesHighPriorityOnly);
                                        }
                                        else
                                        {
                                            WaitHandle.WaitAny(waitHandles);
                                        }
                                    }
                                }
                            })
                            {
                                Name         = string.Format("PriorityScheduler: {0}", i),
                                Priority     = threadPriority,
                                IsBackground = true,
                            };
                            threads[i].Start();
                        }
                    }
                }
            }
        }
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            // execute on the MCT
            return(QueuedTask.Run(() =>
            {
                // find features under the sketch
                var features = MapView.Active.GetFeatures(geometry);
                if (features.Count == 0)
                {
                    return false;
                }

                EditOperation op = null;
                foreach (var layerKey in features.Keys)
                {
                    // is it an anno layer?
                    if (!(layerKey is AnnotationLayer))
                    {
                        continue;
                    }

                    // are there features?
                    var featOids = features[layerKey];
                    if (featOids.Count == 0)
                    {
                        continue;
                    }

                    // use the inspector methodology - load multiple features at once
                    var insp = new Inspector();
                    insp.Load(layerKey, featOids);

                    // make sure tha attribute exists - remember TextString is not guaranteed in the schema
                    Attribute att = insp.FirstOrDefault(a => a.FieldName.ToUpper() == "TEXTSTRING");
                    if (att == null)
                    {
                        continue;
                    }
                    insp["TEXTSTRING"] = "Hello World";

                    // create the edit operation
                    if (op == null)
                    {
                        op = new EditOperation();
                        op.Name = "Update annotation text";
                        op.SelectModifiedFeatures = true;
                        op.SelectNewFeatures = false;
                    }

                    op.Modify(insp);

                    // OR
                    // rather than using the inspector you can use the Dictionary methodology - again TextString has to exist in the schema for the attributes to be applied.

                    //Dictionary<string, object> newAtts = new Dictionary<string, object>();
                    //newAtts.Add("TEXTSTRING", "Hello World");
                    //foreach (var oid in featOids)
                    //  op.Modify(layerKey, oid, newAtts);
                }

                // execute the operation
                if ((op != null) && !op.IsEmpty)
                {
                    return op.Execute();
                }
                return
                false;
            }));
        }
Exemplo n.º 8
0
        private async Task SetupDefinitionDetailsAsync()
        {
            DefinitionDetails.Clear();
            try
            {
                var lstDefs = await QueuedTask.Run <List <string> >(() =>
                {
                    Definition datasetDefinition = Dataset.DatasetDefinition;
                    List <string> lstDefDetails  = new List <string>();
                    if (datasetDefinition is TableDefinition)
                    {
                        TableDefinition tableDefinition = datasetDefinition as TableDefinition;
                        lstDefDetails.Add($"Object ID Field: {tableDefinition.GetObjectIDField()}");
                        StringBuilder stringBuilder = new StringBuilder();

                        if (!(_datastore is FileSystemDatastore))
                        {
                            lstDefDetails.Add($"Alias Name: {tableDefinition.GetAliasName()}");
                            lstDefDetails.Add($"CreatedAt Field: {tableDefinition.GetCreatedAtField()}");
                            lstDefDetails.Add($"Creator Field: {tableDefinition.GetCreatorField()}");
                            lstDefDetails.Add($"Subtype Field: {tableDefinition.GetSubtypeField()}");
                            lstDefDetails.Add($"Default Subtype Code: {tableDefinition.GetDefaultSubtypeCode()}");
                            lstDefDetails.Add($"EditedAt Field: {tableDefinition.GetEditedAtField()}");
                            lstDefDetails.Add($"Editor Field: {tableDefinition.GetEditorField()}");
                            lstDefDetails.Add($"Global ID Field: {tableDefinition.GetGlobalIDField()}");
                            lstDefDetails.Add($"Model Name: {tableDefinition.GetModelName()}");
                            foreach (var subtype in tableDefinition.GetSubtypes())
                            {
                                stringBuilder.Append(subtype.GetCode()).Append(": ").Append(subtype.GetName()).Append(Environment.NewLine);
                            }
                            lstDefDetails.Add($"Subtypes: {stringBuilder}");
                        }
                        stringBuilder = new StringBuilder();
                        foreach (Index index in tableDefinition.GetIndexes())
                        {
                            stringBuilder.Append(index.GetName()).Append(",");
                            string order = index.IsAscending() ? "Ascending" : "Descending";
                            stringBuilder.Append(order).Append(", ");
                            string unique = index.IsUnique() ? "Unique" : "Not Unique";
                            stringBuilder.Append(unique);
                        }
                        lstDefDetails.Add($"Indexes: {stringBuilder}");
                    }

                    if (datasetDefinition is FeatureClassDefinition)
                    {
                        FeatureClassDefinition featureClassDefinition = datasetDefinition as FeatureClassDefinition;
                        if (!(_datastore is FileSystemDatastore))
                        {
                            lstDefDetails.Add($"Area Field: {featureClassDefinition.GetAreaField()}");
                            lstDefDetails.Add($"Length Field: {featureClassDefinition.GetLengthField()}");
                        }
                        lstDefDetails.Add($"Shape Field: {featureClassDefinition.GetShapeField()}");
                        lstDefDetails.Add($"Shape Type: {featureClassDefinition.GetShapeType()}");
                        lstDefDetails.Add($"Spatial Reference Name: {featureClassDefinition.GetSpatialReference().Name}");
                        Envelope extent = featureClassDefinition.GetExtent();
                        lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
                    }

                    if (datasetDefinition is FeatureDatasetDefinition)
                    {
                        FeatureDatasetDefinition featureDatasetDefinition = datasetDefinition as FeatureDatasetDefinition;
                        lstDefDetails.Add($"Spatial Reference Name: {featureDatasetDefinition.GetSpatialReference().Name}");
                        try
                        {
                            Envelope extent = featureDatasetDefinition.GetExtent();
                            lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
                        }
                        catch (Exception)
                        {
                            lstDefDetails.Add("Could not get extent");
                        }
                    }

                    if (datasetDefinition is RelationshipClassDefinition)
                    {
                        RelationshipClassDefinition relationshipClassDefinition = datasetDefinition as RelationshipClassDefinition;
                        lstDefDetails.Add($"Alias Name: {relationshipClassDefinition.GetAliasName()}");
                        lstDefDetails.Add($"Cardinality: {relationshipClassDefinition.GetCardinality()}");
                        lstDefDetails.Add($"Origin Class: {relationshipClassDefinition.GetOriginClass()}");
                        lstDefDetails.Add($"Destination Class: {relationshipClassDefinition.GetDestinationClass()}");
                        lstDefDetails.Add($"Origin Primary Key: {relationshipClassDefinition.GetOriginKeyField()}");
                        lstDefDetails.Add($"Origin Foreign Key: {relationshipClassDefinition.GetOriginForeignKeyField()}");
                        lstDefDetails.Add($"Is Attachement?: {relationshipClassDefinition.IsAttachmentRelationship()}");
                        lstDefDetails.Add($"Is Composite Relationship?: {relationshipClassDefinition.IsComposite()}");
                    }

                    if (datasetDefinition is AttributedRelationshipClassDefinition)
                    {
                        AttributedRelationshipClassDefinition relationshipClassDefinition = datasetDefinition as AttributedRelationshipClassDefinition;
                        lstDefDetails.Add($"Destination Key: {relationshipClassDefinition.GetDestinationKeyField()}");
                        lstDefDetails.Add($"Destination Foreign Key: {relationshipClassDefinition.GetDestinationForeignKeyField()}");
                        lstDefDetails.Add($"Object ID Field: {relationshipClassDefinition.GetObjectIDField()}");
                    }
                    return(lstDefDetails);
                });

                DefinitionDetails.AddRange(lstDefs);
            }
            catch (Exception exObj)
            {
                MessageBox.Show(exObj.Message, "Error");
            }
        }
Exemplo n.º 9
0
        protected override async void OnClick()
        {
            #region Initialization
            // set up a set of TextureCoordinates - these determine how the texture is draped over a face
            //  In this scenario we will use the same textureCoordinates for each face
            var textureCoords = new List <Coordinate2D>()
            {
                new Coordinate2D(4.67909908294678, -2.89953231811523),
                new Coordinate2D(-3.7085223197937, -2.89953231811523),
                new Coordinate2D(-3.6790623664856, 1.89953279495239),
                new Coordinate2D(4.67909908294678, -2.89953231811523),
                new Coordinate2D(-3.6790623664856, 1.89953279495239),
                new Coordinate2D(4.7085223197937, 1.89953327178955)
            };

            TextureCompressionType compressionType = TextureCompressionType.CompressionJPEG;
            byte[] glassImageBuffer     = GetBufferImage("pack://application:,,,/MultipatchBuilder;component/Textures/Glass.jpg", compressionType);
            var    glassTextureResource = new TextureResource(new JPEGTexture(glassImageBuffer));
            byte[] roofImageBuffer      = GetBufferImage("pack://application:,,,/MultipatchBuilder;component/Textures/Roof.jpg", compressionType);
            var    roofTextureResource  = new TextureResource(new JPEGTexture(roofImageBuffer));

            var materialGray = new BasicMaterial
            {
                Color = System.Windows.Media.Colors.Gray
            };
            #endregion

            if (MapView.Active?.Map == null)
            {
                return;
            }

            // find footprint layer
            var footPrintLyr = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "BuildingFootprints") as FeatureLayer;
            if (footPrintLyr == null)
            {
                MessageBox.Show("Can't find layer: BuildingFootprint");
                return;
            }

            var buildingLyr = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "BuildingStructure") as FeatureLayer;
            if (buildingLyr == null)
            {
                MessageBox.Show("Can't find layer: BuildingStructure");
                return;
            }

            // create the multipatch
            var mpb = await QueuedTask.Run <MultipatchBuilderEx>(() =>
            {
                // get all selected lines and use them as the building footprint
                var footPrintSelection = footPrintLyr.GetSelection();
                Polygon footPrint      = null;
                int floorLevels        = 1;
                #region Get Footprint and Floor levels
                foreach (var footprintOid in footPrintSelection.GetObjectIDs())
                {
                    // get the multipatch shape using the Inspector
                    var insp = new Inspector();
                    insp.Load(footPrintLyr, footprintOid);
                    footPrint   = GeometryEngine.Instance.ReverseOrientation(insp.Shape as Multipart) as Polygon;
                    floorLevels = (int)insp["Floors"];
                }
                if (footPrint == null)
                {
                    MessageBox.Show("No selected building footprint found");
                    return(null);
                }
                #endregion
                // Create the MultipatchBuilder using the building footprints and the floorlevels as height
                return(MyMultipatchBuilder.CreateTriangleMultipatchBuilder(footPrint, floorLevels));
            });

            // apply texture or material
            // create a builder to work on the multipatch geometry
            switch (Module1.SelectedTexture)
            {
            case "Glass":
                // create the textures for walls and roof
                BasicMaterial glassMaterialTexture = new BasicMaterial
                {
                    TextureResource = glassTextureResource
                };
                BasicMaterial roofMaterialTexture = new BasicMaterial
                {
                    TextureResource = roofTextureResource
                };

                // apply the texture materials to the patches
                var patches = mpb.Patches;
                for (var iPatch = 0; iPatch < patches.Count; iPatch++)
                {
                    if (iPatch == patches.Count - 1)
                    {
                        // roof
                        patches[iPatch].Material        = roofMaterialTexture;
                        patches[iPatch].TextureCoords2D = textureCoords;
                    }
                    else
                    {
                        // walls
                        patches[iPatch].Material        = glassMaterialTexture;
                        patches[iPatch].TextureCoords2D = textureCoords;
                    }
                }
                break;

            case "Red-solid":
                // create some materials
                var materialRed = new BasicMaterial
                {
                    Color = System.Windows.Media.Colors.Brown
                };
                // apply the materials to the patches
                for (var iPatch = 0; iPatch < mpb.Patches.Count; iPatch++)
                {
                    if (iPatch == mpb.Patches.Count - 1)
                    {
                        // roof
                        mpb.Patches[iPatch].Material = materialGray;
                    }
                    else
                    {
                        // walls
                        mpb.Patches[iPatch].Material = materialRed;
                    }
                }
                break;

            case "Gray-solid":
                // create some materials
                var materialSilver = new BasicMaterial
                {
                    Color = System.Windows.Media.Colors.Silver
                };
                // apply the materials to the patches
                for (var iPatch = 0; iPatch < mpb.Patches.Count; iPatch++)
                {
                    if (iPatch == mpb.Patches.Count - 1)
                    {
                        // roof
                        mpb.Patches[iPatch].Material = materialGray;
                    }
                    else
                    {
                        // walls
                        mpb.Patches[iPatch].Material = materialSilver;
                    }
                }
                break;
            }

            // create a new feature using the multipatch
            bool result = await QueuedTask.Run(() =>
            {
                var op = new EditOperation
                {
                    Name = "Create multipatch feature",
                    SelectNewFeatures = false
                };
                Module1.NewMultipatch = mpb.ToGeometry() as Multipatch;
                var rowToken          = op.Create(buildingLyr, Module1.NewMultipatch);
                if (op.Execute())
                {
                    // track the newly created objectID
                    // save the oid in the module for other commands to use
                    Module1.NewMultipatchOID = rowToken.ObjectID.Value;
                    return(true);
                }
                var msg = op.ErrorMessage;
                return(false);
            });
        }
Exemplo n.º 10
0
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            return(QueuedTask.Run(() =>
            {
                try
                {
                    ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New);


                    var map = MapView.Active.Map;
                    var mhLayer = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault((m => m.Name == "Manholes"));

                    // Get the currently selected features in the map
                    var selectedFeatures = map.GetSelection();
                    var selectCount = mhLayer.SelectionCount;

                    if (selectCount == 0)
                    {
                        MessageBox.Show("No manhole was selected.\n\nTry selecting a manhole again.", "WARNING!");
                    }
                    else if (selectCount > 1)
                    {
                        MessageBox.Show("More than one manhole selected.\n\nTry selecting manholes again.", "WARNING!");
                    }
                    else
                    {
                        progDial.Show();


                        // get the first layer and its corresponding selected feature OIDs
                        var firstSelectionSet = selectedFeatures.First();

                        // create an instance of the inspector class
                        var inspector = new Inspector();

                        // load the selected features into the inspector using a list of object IDs
                        inspector.Load(firstSelectionSet.Key, firstSelectionSet.Value);

                        //get the value of
                        string mhNum = inspector["MH_NO"].ToString();

                        // Create the workArcList to store the Arcs(VALUES as int) from the nodeArcListDict
                        // for the selected mhNum(KEY as string)
                        List <int> workArcList = new List <int>();

                        // Output the Arc ObjectID (VALUES) as List<int> for the selected mhNum (KEY)
                        nodeArcListDict.TryGetValue(mhNum, out List <int> arcValues);

                        // Loop through Output List<int> and add VALUE to workArcList
                        foreach (var arcValue in arcValues)
                        {
                            workArcList.Add(arcValue);
                        }

                        // Create the removeArcsList to store the Arcs(VALUES as int)
                        List <int> removeArcsList = new List <int>();

                        // loop through workArcList check if it contains downstream node = mhNum selected by user
                        foreach (var workArc in workArcList)
                        {
                            // Get the list of Values from the arcNodeListDict for the current arc KEY (workArc) in workArcList.
                            arcNodeListDict.TryGetValue(workArc, out List <string> nodeWorkVals);

                            //Get the downstream manhole [0] from list.
                            string downMH = nodeWorkVals[1];

                            // Check if downstream manhole and selected manhole are the same.
                            if (downMH == mhNum)
                            {
                                // Add to removeArcList
                                removeArcsList.Add(workArc);
                            }
                        }

                        // Loop through removeArcsList remove each removeArc in list from workArcList (this is getting confusing)
                        foreach (var removeArc in removeArcsList)
                        {
                            // Remove from workArcList
                            workArcList.Remove(removeArc);
                        }

                        if (workArcList.Count() == 0)
                        {
                            MessageBox.Show("No downstream sewer lines found.", "WARNING!");
                        }

                        // Create dictionary to store downstream arcs that will be used to create query string.
                        // Only reason dictionary is used is because it's a quick way to prevent duplicate KEYS.
                        Dictionary <string, string> downStreamArcDict = new Dictionary <string, string>();

                        //string downStreamNode = "";
                        List <string> workManholeList = new List <string>();

                        int loopCount = 0;

                        // At start of loop, workArcList has >0 arcs from initial selection.
                        do
                        {
                            loopCount++;

                            workManholeList.Clear();
                            removeArcsList.Clear();

                            foreach (var arc in workArcList)
                            {
                                if (!downStreamArcDict.ContainsKey(arc.ToString()))
                                {
                                    // Add arc to downstream arc dictionary
                                    downStreamArcDict.Add(arc.ToString(), "TRUE");
                                }
                            }

                            foreach (var dwnArc in workArcList)
                            {
                                arcNodeListDict.TryGetValue(dwnArc, out List <string> nodeWorkVals);

                                //Get the downstream manhole [1] from list.
                                string downMH = nodeWorkVals[1];

                                // Add downstream manhole for selected downstream arc to workManholeList.
                                // This will be used to get more more downstream arcs later.
                                workManholeList.Add(downMH);
                            }

                            // Clear workArcList to add new arcs later.
                            workArcList.Clear();

                            // Get all the arcs connected to all the manholes in the workManholeList using nodeArcListDict dictionary.
                            // Add these arcs to workArcList.
                            foreach (var mh in workManholeList)
                            {
                                // Get all the arcs attached to manhole/node.
                                nodeArcListDict.TryGetValue(mh, out List <int> arcVals);
                                // Add list of arcs to workArcList list.
                                workArcList.AddRange(arcVals);
                            }

                            // Loop through all the arcs in workArcList and for arcs that have downstream manholes in the workManholeList,
                            // add that arc to removeArcsList.
                            foreach (var arc2 in workArcList)
                            {
                                // get list of nodes for arcs in workArcList.
                                arcNodeListDict.TryGetValue(arc2, out List <string> nodeWorkVals2);

                                // Get the downstream manhole [0] from list.
                                string downMH = nodeWorkVals2[1];

                                // Check workManholeList for downMH and remove from removeArcList if TRUE.
                                if (workManholeList.Contains(downMH))
                                {
                                    removeArcsList.Add(arc2);
                                }
                            }

                            // Remove arcs in removeArcsList from workArcsList
                            foreach (var arc3 in removeArcsList)
                            {
                                workArcList.Remove(arc3);
                            }



                            // Loop through again if condition is met.
                        } while (workArcList.Count > 0);



                        // Build the query string from the downStreamArcDict KEYS to select the downstream sewer lines.
                        int count = 0;

                        var stringBuilder = new StringBuilder();

                        foreach (var key in downStreamArcDict.Keys)
                        {
                            if (count == 0)
                            {
                                stringBuilder.Append($"OBJECTID IN ({key}");
                            }
                            else if (count < downStreamArcDict.Keys.Count)
                            {
                                stringBuilder.Append($",{key}");
                            }

                            count++;
                        }
                        stringBuilder.Append($")");

                        // Select sewers using StringBuilder object above for the WhereClause.
                        QueryFilter queryFilter = new QueryFilter {
                            WhereClause = stringBuilder.ToString()
                        };
                        var sewerLines = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines");
                        var manholes = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Manholes");

                        sewerLines.Select(queryFilter, SelectionCombinationMethod.New);

                        progDial.Hide();
                    }
                }

                catch (Exception)
                {
                    string caption = "WARNING!";
                    string message = "Downstream trace failed! \n\nSave and restart ArcGIS Pro and try process again.\n\n" +
                                     "If problem persist, contact your local GIS nerd.";

                    progDial.Hide();

                    //Using the ArcGIS Pro SDK MessageBox class
                    MessageBox.Show(message, caption);
                }
                return true;
            }));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Divide the first selected feature into equal parts or by map unit distance.
        /// </summary>
        /// <param name="numberOfParts">Number of parts to create.</param>
        /// <param name="value">Value for number or parts or distance.</param>
        /// <returns></returns>
        private static Task DivideLinesAsync(bool numberOfParts, double value)
        {
            //Run on MCT
            return(QueuedTask.Run(() =>
            {
                //get selected feature
                var selectedFeatures = MapView.Active.Map.GetSelection();

                //get the layer of the selected feature
                var featLayer = selectedFeatures.Keys.First() as FeatureLayer;
                var oid = selectedFeatures.Values.First().First();

                var feature = featLayer.Inspect(oid);

                //get geometry and length
                var origPolyLine = feature.Shape as Polyline;
                var origLength = GeometryEngine.Instance.Length(origPolyLine);

                string xml = origPolyLine.ToXML();

                //List of mappoint geometries for the split
                var splitPoints = new List <MapPoint>();

                var enteredValue = (numberOfParts) ? origLength / value : value;
                var splitAtDistance = 0 + enteredValue;

                while (splitAtDistance < origLength)
                {
                    //create a mapPoint at splitDistance and add to splitpoint list
                    MapPoint pt = null;
                    try
                    {
                        pt = GeometryEngine.Instance.MovePointAlongLine(origPolyLine, splitAtDistance, false, 0, SegmentExtension.NoExtension);
                    }
                    catch (GeometryObjectException)
                    {
                        // line is an arc?
                    }

                    if (pt != null)
                    {
                        splitPoints.Add(pt);
                    }
                    splitAtDistance += enteredValue;
                }

                if (splitPoints.Count == 0)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Divide lines was unable to process your selected line. Please select another.", "Divide Lines");
                    return;
                }
                //create and execute the edit operation
                var op = new EditOperation()
                {
                    Name = "Divide Lines",
                    SelectModifiedFeatures = false,
                    SelectNewFeatures = false
                };
                op.Split(featLayer, oid, splitPoints);
                op.Execute();

                //clear selection
                featLayer.ClearSelection();
            }));
        }
Exemplo n.º 12
0
        public static async void AddLayer(string targets, string name)
        {
            try
            {
                using (HttpClientHandler handler = new HttpClientHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    using (HttpClient client = new HttpClient(handler))
                    {
                        client.BaseAddress = new Uri("https://api.planet.com");
                        //HttpClientHandler handler = new HttpClientHandler()
                        //{
                        //    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        //};
                        //HttpClient client = new HttpClient(handler)
                        //{

                        //    BaseAddress = new Uri("https://api.planet.com")
                        //};
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "data/v1/layers");
                        //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                        request.Headers.Host = "tiles2.planet.com";
                        request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                        var nvc = new List <KeyValuePair <string, string> >();
                        //nvc.Add(new KeyValuePair<string, string>("ids", "PSScene4Band:20190603_205042_1042,PSScene4Band:20190528_205949_43_1061,PSScene4Band:20190818_205116_1009"));
                        nvc.Add(new KeyValuePair <string, string>("ids", targets));
                        //var content = new StringContent(json, Encoding.UTF8, "application/json");
                        var content = new FormUrlEncodedContent(nvc);
                        request.Content = content;
                        var byteArray = Encoding.ASCII.GetBytes(Module1.Current.API_KEY.API_KEY_Value + ":hgvhgv");
                        client.DefaultRequestHeaders.Host = "api.planet.com";
                        //_client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                        content.Headers.Remove("Content-Type");
                        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                        client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                        client.DefaultRequestHeaders.Add("User-Agent", "ArcGISProC#");
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                        using (HttpResponseMessage httpResponse = client.SendAsync(request).Result)
                        {
                            using (HttpContent content2 = httpResponse.Content)
                            {
                                var        json2      = content2.ReadAsStringAsync().Result;
                                customwmts customwmts = JsonConvert.DeserializeObject <customwmts>(json2);
                                customwmts.wmtsURL = new Uri("https://tiles.planet.com/data/v1/layers/wmts/" + customwmts.name + "?api_key=" + Module1.Current.API_KEY.API_KEY_Value);
                                //Geometry geometry2 = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, JsonConvert.SerializeObject( quickSearchResult.features[5].geometry));
                                var serverConnection = new CIMProjectServerConnection {
                                    URL = customwmts.wmtsURL.ToString()
                                };
                                var connection = new CIMWMTSServiceConnection {
                                    ServerConnection = serverConnection
                                };
                                await QueuedTask.Run(() =>
                                {
                                    Layer group           = MapView.Active.Map.FindLayer(Asset.RootGroup);
                                    GroupLayer groupLayer = null;
                                    if (group != null)
                                    {
                                        groupLayer = group as GroupLayer;
                                    }
                                    else
                                    {
                                        int index  = Asset.FindRootIndex();
                                        groupLayer = LayerFactory.Instance.CreateGroupLayer(MapView.Active.Map, index, Asset.RootGroup);
                                    }
                                    BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, groupLayer, 0, name);
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error adding to Map", "Add to Map");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Renders a polygon feature layer with Dot Density symbols to represent quantities.
        /// ![Dot Density renderer](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/dotDensity-renderer.png)
        /// </summary>
        /// <remarks></remarks>
        /// <returns></returns>
        internal static Task DotDensityRendererAsync()
        {
            //Check feature layer name
            //Code works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.Name == "USDemographics");

            if (featureLayer == null)
            {
                MessageBox.Show("This renderer works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data", "Data missing");
                return(Task.FromResult(0));
            }
            return(QueuedTask.Run(() =>
            {
                //Define size of the dot to use for the renderer
                int dotSize = 3;
                //Check if the TOTPOP10 field exists
                int idxField = -1;
                using (var table = featureLayer.GetTable())
                {
                    var def = table.GetDefinition();
                    idxField = def.FindField("TOTPOP10");
                }
                // "TOTPOP10" field was not found
                if (idxField == -1)
                {
                    return;
                }

                //array of fields to be represented in the renderer
                var valueFields = new List <string> {
                    "TOTPOP10"
                };
                //Create the DotDensityRendererDefinition object
                var dotDensityDef = new DotDensityRendererDefinition(valueFields, SDKHelpers.GetColorRamp(),
                                                                     dotSize, 30000, "Dot", "people");
                //Create the renderer using the DotDensityRendererDefinition
                CIMDotDensityRenderer dotDensityRndr = (CIMDotDensityRenderer)featureLayer.CreateRenderer(dotDensityDef);

                //if you want to customize the dot symbol for the renderer, create a "DotDensitySymbol" which is an
                //Amalgamation of 3 symbol layers: CIMVectorMarker, CIMSolidFill and CIMSolidStroke
                //Define CIMVectorMarker layer
                var cimMarker = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, dotSize);
                var dotDensityMarker = cimMarker as CIMVectorMarker;
                //Definte the placement
                CIMMarkerPlacementInsidePolygon markerPlacement = new CIMMarkerPlacementInsidePolygon {
                    Randomness = 100, GridType = PlacementGridType.RandomFixedQuantity, Clipping = PlacementClip.RemoveIfCenterOutsideBoundary
                };
                dotDensityMarker.MarkerPlacement = markerPlacement;

                //Define CIMSolidFill layer
                CIMSolidFill solidFill = new CIMSolidFill {
                    Color = new CIMRGBColor {
                        R = 249, G = 232, B = 189, Alpha = 50
                    }
                };

                //Define CIMSolidStroke
                CIMSolidStroke solidStroke = new CIMSolidStroke {
                    Color = ColorFactory.Instance.GreyRGB, Width = .5
                };

                //Create the amalgamated CIMPolygonSymbol that includes the 3 layers
                var dotDensitySymbol = new CIMPolygonSymbol
                {
                    SymbolLayers = new CIMSymbolLayer[] { dotDensityMarker, solidFill, solidStroke }
                };

                //Apply the dotDensitySymbol to the CIMDotDenstityRenderer's DotDensitySymbol property.
                dotDensityRndr.DotDensitySymbol = dotDensitySymbol.MakeSymbolReference();

                //Apply the renderer to the polygon Feature Layer.
                featureLayer.SetRenderer(dotDensityRndr);
            }));
        }
        //
        // Posts the @contents to the @url.   The post is done in a queue
        // system that is flushed regularly, so it is safe to call Post to
        // fire and forget
        //
        public void Post(string url, string content)
        {
            var qtask = new QueuedTask () {
                AccountId = LocalAccountId,
                Url = url,
                PostData = content,
            };
            lock (Database.Main)
                Database.Main.Insert (qtask);

            FlushTasks ();
        }
Exemplo n.º 15
0
        /// <summary>
        /// This method makes sure
        /// 1. The Mapview is Active
        /// 2. There is at least one Layer selected
        /// 3. The selected Layer is a FeatureLayer
        /// 4. The selected Layer is backed by an Enterprise Sql Server Geodatabase FeatureClass
        ///
        /// If all of these hold good, the DatabaseClient is used to execute a query which creates
        /// a Database Table containing the gdb_items records corresponding to all domains. The Table is
        /// then opened using the API and the domains combobox populated. Finally, the Table is deleted
        /// </summary>
        /// <param name="mapViewEventArgs"></param>
        private async void UpdateDomainList(MapViewEventArgs mapViewEventArgs)
        {
            if (MapView.Active == null ||
                mapViewEventArgs.MapView.GetSelectedLayers().Count < 1 ||
                !(mapViewEventArgs.MapView.GetSelectedLayers()[0] is FeatureLayer))
            {
                Enabled = false;
                return;
            }
            EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown;
            await QueuedTask.Run(() =>
            {
                using (Table table = (mapViewEventArgs.MapView.GetSelectedLayers()[0] as FeatureLayer).GetTable())
                {
                    if (!(table.GetDatastore() is Geodatabase))
                    {
                        return;
                    }
                    try
                    {
                        var gdb                = table.GetDatastore() as Geodatabase;
                        var gdbConnector       = gdb.GetConnector() as DatabaseConnectionProperties;
                        enterpriseDatabaseType = gdbConnector != null ? gdbConnector.DBMS : EnterpriseDatabaseType.Unknown;
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine("Exception was thrown!");
                    }
                }
            });

            if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer)
            {
                Enabled = false;
                return;
            }

            Enabled = true;
            Clear();
            await QueuedTask.Run(() =>
            {
                using (Table table = (mapViewEventArgs.MapView.GetSelectedLayers()[0] as FeatureLayer).GetTable())
                {
                    var geodatabase        = table.GetDatastore() as Geodatabase;
                    Version defaultVersion = geodatabase.GetVersionManager().GetVersions().FirstOrDefault(version =>
                    {
                        string name = version.GetName();
                        return(name.ToLowerInvariant().Equals("dbo.default") || name.ToLowerInvariant().Equals("sde.default"));
                    });
                    if (defaultVersion == null)
                    {
                        return;
                    }


                    string tableName = String.Format("NewTable{0}{1}{2}{3}", DateTime.Now.Hour, DateTime.Now.Minute,
                                                     DateTime.Now.Second, DateTime.Now.Millisecond);
                    gdbItemsOwner    = defaultVersion.GetName().Split('.')[0];
                    string statement =
                        String.Format(
                            @"select {1}.GDB_ITEMTYPES.Name as Type, {1}.GDB_ITEMS.Name into {0} from {1}.GDB_ITEMS JOIN {1}.GDB_ITEMTYPES ON {1}.GDB_ITEMS.Type = {1}.GDB_ITEMTYPES.UUID where {1}.GDB_ITEMTYPES.Name = 'Domain' OR {1}.GDB_ITEMTYPES.Name = 'Coded Value Domain' OR {1}.GDB_ITEMTYPES.Name = 'Range Domain'",
                            tableName, gdbItemsOwner);
                    try
                    {
                        DatabaseClient.ExecuteStatement(geodatabase, statement);
                    }
                    catch (GeodatabaseTableException exception)
                    {
                        MessageBox.Show(exception.Message);
                        return;
                    }

                    var newTable = geodatabase.OpenDataset <Table>(tableName);

                    using (RowCursor rowCursor = newTable.Search(null, false))
                    {
                        while (rowCursor.MoveNext())
                        {
                            using (Row row = rowCursor.Current)
                            {
                                Add(new ComboBoxItem(row["Name"].ToString()));
                            }
                        }
                    }
                    statement = String.Format(@"DROP TABLE {0}", tableName);
                    DatabaseClient.ExecuteStatement(geodatabase, statement);
                }
            });
        }
Exemplo n.º 16
0
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (geometry == null)
            {
                return(false);
            }

            // Create an edit operation
            var createOperation = new EditOperation()
            {
                Name = "Create Transformer Bank",
                SelectNewFeatures = true
            };

            bool   success      = false;
            string errorMessage = "";

            await QueuedTask.Run(() =>
            {
                Map map = GetMap();

                using (UtilityNetwork utilityNetwork = GetUtilityNetwork())
                {
                    if (utilityNetwork == null)
                    {
                        errorMessage = "Please select a layer that participates in a utility network.";
                    }
                    else
                    {
                        if (!ValidateDataModel(utilityNetwork))
                        {
                            errorMessage = "This sample is designed for a different utility network data model";
                        }
                        else
                        {
                            using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
                                // Get the NetworkSource, FeatureClass, AssetGroup, and AssetTypes for all of the features we want to create
                                // The existence of these values has already been confirmed in the ValidateDataModel() routine

                                // TransformerBank
                                using (NetworkSource transformerBankNetworkSource = GetNetworkSource(utilityNetworkDefinition, AssemblyNetworkSourceName))
                                    using (FeatureClass transformerBankFeatureClass = utilityNetwork.GetTable(transformerBankNetworkSource) as FeatureClass)
                                        using (AssetGroup transformerBankAssetGroup = transformerBankNetworkSource.GetAssetGroup(TransformerBankAssetGroupName))
                                            using (AssetType transformerBankAssetType = transformerBankAssetGroup.GetAssetType(TransformerBankAssetTypeName))

                                                // Transformer
                                                using (NetworkSource deviceNetworkSource = GetNetworkSource(utilityNetworkDefinition, DeviceNetworkSourceName))
                                                    using (FeatureClass deviceFeatureClass = utilityNetwork.GetTable(deviceNetworkSource) as FeatureClass)
                                                        using (AssetGroup transformerAssetGroup = deviceNetworkSource.GetAssetGroup(TransformerAssetGroupName))
                                                            using (AssetType transformerAssetType = transformerAssetGroup.GetAssetType(TransformerAssetTypeName))

                                                                // Arrester
                                                                using (AssetGroup arresterAssetGroup = deviceNetworkSource.GetAssetGroup(ArresterAssetGroupName))
                                                                    using (AssetType arresterAssetType = arresterAssetGroup.GetAssetType(ArresterAssetTypeName))

                                                                        // Fuse
                                                                        using (AssetGroup fuseAssetGroup = deviceNetworkSource.GetAssetGroup(FuseAssetGroupName))
                                                                            using (AssetType fuseAssetType = fuseAssetGroup.GetAssetType(FuseAssetTypeName))
                                                                            {
                                                                                MapPoint clickPoint = geometry as MapPoint;

                                                                                // Create a transformer bank

                                                                                RowToken token = createOperation.Create(transformerBankFeatureClass, CreateAttributes(transformerBankAssetGroup, transformerBankAssetType, clickPoint));
                                                                                RowHandle transformerBankHandle = new RowHandle(token);

                                                                                // Create three transformers, one for each phase

                                                                                MapPoint transformerPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointA, APhase));
                                                                                RowHandle transformerHandleA = new RowHandle(token);

                                                                                MapPoint transformerPointB = CreateOffsetMapPoint(clickPoint, 0, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointB, BPhase));
                                                                                RowHandle transformerHandleB = new RowHandle(token);

                                                                                MapPoint transformerPointC = CreateOffsetMapPoint(clickPoint, XOffset, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointC, CPhase));
                                                                                RowHandle transformerHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the transformers
                                                                                AssociationDescription containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Find the high-side terminal for transformers
                                                                                TerminalConfiguration transformerTerminalConfiguration = transformerAssetType.GetTerminalConfiguration();
                                                                                IReadOnlyList <Terminal> terminals = transformerTerminalConfiguration.Terminals;
                                                                                Terminal highSideTerminal          = terminals.First(x => x.IsUpstreamTerminal == true);
                                                                                long highSideTerminalID            = highSideTerminal.ID;

                                                                                // Create three fuses, one for each phase

                                                                                MapPoint fusePointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointA, APhase));
                                                                                RowHandle fuseHandleA = new RowHandle(token);

                                                                                MapPoint fusePointB = CreateOffsetMapPoint(clickPoint, 0, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointB, BPhase));
                                                                                RowHandle fuseHandleB = new RowHandle(token);

                                                                                MapPoint fusePointC = CreateOffsetMapPoint(clickPoint, XOffset, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointC, CPhase));
                                                                                RowHandle fuseHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the fuses
                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Connect the high-side transformer terminals to the fuses (connect the A-phase transformer to the A-phase fuse, and so on)
                                                                                AssociationDescription connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleA, highSideTerminalID, fuseHandleA);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleB, highSideTerminalID, fuseHandleB);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleC, highSideTerminalID, fuseHandleC);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                // Create three arresters, one for each phase

                                                                                MapPoint arresterPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointA, APhase));
                                                                                RowHandle arresterHandleA = new RowHandle(token);

                                                                                MapPoint arresterPointB = CreateOffsetMapPoint(clickPoint, 0, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointB, BPhase));
                                                                                RowHandle arresterHandleB = new RowHandle(token);

                                                                                MapPoint arresterPointC = CreateOffsetMapPoint(clickPoint, XOffset, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointC, CPhase));
                                                                                RowHandle arresterHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the arresters
                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Create connectivity associations between the fuses and the arresters (connect the A-phase fuse the A-phase arrester, and so on)
                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleA, arresterHandleA);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleB, arresterHandleB);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleC, arresterHandleC);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                // Execute the edit operation, which creates all of the rows and associations
                                                                                success = createOperation.Execute();

                                                                                if (!success)
                                                                                {
                                                                                    errorMessage = createOperation.ErrorMessage;
                                                                                }
                                                                            }
                        }
                    }
                }
            });

            if (!success)
            {
                MessageBox.Show(errorMessage, "Create Transformer Bank Tool");
            }
            return(success);
        }
Exemplo n.º 17
0
 /// <summary>
 /// In order to illustrate that Geodatabase calls have to be made on the MCT
 /// </summary>
 /// <returns></returns>
 public async Task FeatureClassValidateAsync()
 {
     await QueuedTask.Run(() => MainMethodCode());
 }
Exemplo n.º 18
0
        async public static void CreateElementSnippets()
        {
            //There are already many Create element snippets in the PRO snippets section.  This section will only contain examples that are NOT in the Pro snippets section
            //Pro snippets region names includes:
            //    Create point graphic with symbology
            //    Create line graphic with symbology
            //    Create rectangle graphic with simple symbology
            //    Create text element with basic font properties
            //    Create rectangle text with more advanced symbol settings
            //    Create a new picture element with advanced symbol settings
            //    Create a map frame and zoom to a bookmark
            //    Create a legend for a specific map frame
            //    Creating group elements

            LayoutView lytView = LayoutView.Active;
            Layout     layout  = lytView.Layout;

            #region Create_BezierCurve
            //Create a beizier curve element with a simple line style.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D pt1          = new Coordinate2D(1, 7.5);
                Coordinate2D pt2          = new Coordinate2D(1.66, 8);
                Coordinate2D pt3          = new Coordinate2D(2.33, 7.1);
                Coordinate2D pt4          = new Coordinate2D(3, 7.5);
                CubicBezierBuilder bez    = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
                CubicBezierSegment bezSeg = bez.ToSegment();
                Polyline bezPl            = PolylineBuilder.CreatePolyline(bezSeg);

                //Set symbology, create and add element to layout
                CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 4.0, SimpleLineStyle.DashDot);
                GraphicElement bezElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, bezPl, lineSym);
                bezElm.SetName("New Bezier Curve");
            });

            #endregion Create_BezierCurve

            #region Create_freehand
            //Create a graphic freehand element with a simple line style.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plCoords = new List <Coordinate2D>();
                plCoords.Add(new Coordinate2D(1.5, 10.5));
                plCoords.Add(new Coordinate2D(1.25, 9.5));
                plCoords.Add(new Coordinate2D(1, 10.5));
                plCoords.Add(new Coordinate2D(0.75, 9.5));
                plCoords.Add(new Coordinate2D(0.5, 10.5));
                plCoords.Add(new Coordinate2D(0.5, 1));
                plCoords.Add(new Coordinate2D(0.75, 2));
                plCoords.Add(new Coordinate2D(1, 1));
                Polyline linePl = PolylineBuilder.CreatePolyline(plCoords);

                //Set symbolology, create and add element to layout
                CIMLineSymbol lineSym  = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
                GraphicElement lineElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, linePl, lineSym);
                lineElm.SetName("New Freehand");
            });

            #endregion Create_freehand

            #region Create_polygon_poly
            //Create a polygon graphic with simple line and fill styles.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(1, 7));
                plyCoords.Add(new Coordinate2D(2, 7));
                plyCoords.Add(new Coordinate2D(2, 6.7));
                plyCoords.Add(new Coordinate2D(3, 6.7));
                plyCoords.Add(new Coordinate2D(3, 6.1));
                plyCoords.Add(new Coordinate2D(1, 6.1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.DashDotDot);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
                GraphicElement polyElm   = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
                polyElm.SetName("New Polygon");
            });

            #endregion Create_polygon_poly

            #region Create_polygon_env
            //Create a polygon graphic using an envelope with simple line and fill styles.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build 2D envelope
                Coordinate2D env_ll = new Coordinate2D(1.0, 4.75);
                Coordinate2D env_ur = new Coordinate2D(3.0, 5.75);
                Envelope env        = EnvelopeBuilder.CreateEnvelope(env_ll, env_ur);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.DashDotDot);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
                GraphicElement polyElm   = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, env, polySym);
                polyElm.SetName("New Polygon");
            });

            #endregion Create_polygon_env

            #region Create_circle
            //Create a circle graphic element using a simple line and fill styles.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center       = new Coordinate2D(2, 4);
                EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment cir    = eabCir.ToSegment();

                //Set symbolology, create and add element to layout
                CIMStroke outline          = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Dash);
                CIMPolygonSymbol circleSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);
                GraphicElement cirElm      = LayoutElementFactory.Instance.CreateCircleGraphicElement(layout, cir, circleSym);
                cirElm.SetName("New Circle");
            });

            #endregion

            #region Create_ellipse
            //Create an ellipse graphic with simple line and fill styles.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center        = new Coordinate2D(2, 2.75);
                EllipticArcBuilder eabElp  = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment ellipse = eabElp.ToSegment();

                //Set symbolology, create and add element to layout
                CIMStroke outline           = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB, 2.0, SimpleLineStyle.Dot);
                CIMPolygonSymbol ellipseSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreyRGB, SimpleFillStyle.Vertical, outline);
                GraphicElement elpElm       = LayoutElementFactory.Instance.CreateEllipseGraphicElement(layout, ellipse, ellipseSym);
                elpElm.SetName("New Ellipse");
            });

            #endregion

            #region Create_lasso
            //Create a graphic lasso element with simple line and fill styles.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(1, 1));
                plyCoords.Add(new Coordinate2D(1.25, 2));
                plyCoords.Add(new Coordinate2D(1.5, 1.1));
                plyCoords.Add(new Coordinate2D(1.75, 2));
                plyCoords.Add(new Coordinate2D(2, 1.1));
                plyCoords.Add(new Coordinate2D(2.25, 2));
                plyCoords.Add(new Coordinate2D(2.5, 1.1));
                plyCoords.Add(new Coordinate2D(2.75, 2));
                plyCoords.Add(new Coordinate2D(3, 1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
                GraphicElement polyElm   = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
                polyElm.SetName("New Lasso");
            });

            #endregion Create_lasso

            #region Create_CurveText
            //Create curve text with basic text properties.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D pt1          = new Coordinate2D(3.6, 7.5);
                Coordinate2D pt2          = new Coordinate2D(4.26, 8);
                Coordinate2D pt3          = new Coordinate2D(4.93, 7.1);
                Coordinate2D pt4          = new Coordinate2D(5.6, 7.5);
                CubicBezierBuilder bez    = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
                CubicBezierSegment bezSeg = bez.ToSegment();
                Polyline bezPl            = PolylineBuilder.CreatePolyline(bezSeg);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 24, "Comic Sans MS", "Regular");
                GraphicElement bezTxtElm = LayoutElementFactory.Instance.CreateCurvedTextGraphicElement(layout, bezPl, "Curved Text", sym);
                bezTxtElm.SetName("New Splinned Text");
            });

            #endregion Create_CurveText

            #region Create_PolygonText
            //Create polygon paragraph text with basic text properties.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(3.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.1));
                plyCoords.Add(new Coordinate2D(3.5, 6.1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym         = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 10, "Arial", "Regular");
                string text               = "Some Text String that is really long and is <BOL>forced to wrap to other lines</BOL> so that we can see the effects." as String;
                GraphicElement polyTxtElm = LayoutElementFactory.Instance.CreatePolygonParagraphGraphicElement(layout, poly, text, sym);
                polyTxtElm.SetName("New Polygon Text");

                //(Optionally) Modify paragraph border
                CIMGraphic polyTxtGra = polyTxtElm.GetGraphic();
                CIMParagraphTextGraphic cimPolyTxtGra   = polyTxtGra as CIMParagraphTextGraphic;
                cimPolyTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimPolyTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                polyTxtElm.SetGraphic(polyTxtGra);
            });

            #endregion Create_PolygonText

            #region Create_CircleText
            //Create circle paragraph text with basic text settings and optionally a modified border.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center       = new Coordinate2D(4.5, 4);
                EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment cir    = eabCir.ToSegment();

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreenRGB, 10, "Arial", "Regular");
                string text              = "Circle, circle, circle, circle, circle, circle, circle, circle, circle, circle, circle";
                GraphicElement cirTxtElm = LayoutElementFactory.Instance.CreateCircleParagraphGraphicElement(layout, cir, text, sym);
                cirTxtElm.SetName("New Circle Text");

                //(Optionally) Modify paragraph border
                CIMGraphic cirTxtGra = cirTxtElm.GetGraphic();
                CIMParagraphTextGraphic cimCirTxtGra   = cirTxtGra as CIMParagraphTextGraphic;
                cimCirTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimCirTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                cirTxtElm.SetGraphic(cirTxtGra);
            });

            #endregion

            #region Create_EllipseText
            //Create ellipse paragraph text with basic text settings and optionally a modified border.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center        = new Coordinate2D(4.5, 2.75);
                EllipticArcBuilder eabElp  = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment ellipse = eabElp.ToSegment();

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB, 10, "Arial", "Regular");
                string text              = "Ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse";
                GraphicElement elpTxtElm = LayoutElementFactory.Instance.CreateEllipseParagraphGraphicElement(layout, ellipse, text, sym);
                elpTxtElm.SetName("New Ellipse Text");

                //(Optionally) Modify paragraph border
                CIMGraphic elpTxtGra = elpTxtElm.GetGraphic();
                CIMParagraphTextGraphic cimElpTxtGra   = elpTxtGra as CIMParagraphTextGraphic;
                cimElpTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimElpTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                elpTxtElm.SetGraphic(elpTxtGra);
            });

            #endregion Create_EllipseText

            MapFrame mfElm = null;

            #region Create_MapFrame
            //Creates a new map frame and changes the camera's scale.

            //Constuct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D ll = new Coordinate2D(6.0, 8.5);
                Coordinate2D ur = new Coordinate2D(8.0, 10.5);
                Envelope env    = EnvelopeBuilder.CreateEnvelope(ll, ur);

                //Reference map, create MF and add to layout
                MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map"));
                Map mfMap = mapPrjItem.GetMap();
                mfElm     = LayoutElementFactory.Instance.CreateMapFrame(layout, env, mfMap);
                mfElm.SetName("New Map Frame");

                //Set the camera
                Camera camera = mfElm.Camera;
                camera.Scale  = 24000;
                mfElm.SetCamera(camera);
            });

            #endregion Create_MapFrame

            #region Create_ScaleBar
            //Create a scale bar for a specific map frame and assign a scale bar style item.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Reference a North Arrow in a style
                StyleProjectItem stylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars("Double Alternating Scale Bar 1")[0];

                //Build geometry
                Coordinate2D center = new Coordinate2D(7, 8);

                //Reference MF, create north arrow and add to layout
                MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
                if (mf == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                ScaleBar sbElm = LayoutElementFactory.Instance.CreateScaleBar(layout, center, mf, sbStyleItm);
                sbElm.SetName("New Scale Bar");
                sbElm.SetWidth(2);
                sbElm.SetX(6);
                sbElm.SetY(7.5);
            });

            #endregion Create_ScaleBar

            #region Create_NorthArrow
            //Create a north arrow for a specific map frame and assign a north arrow style item.

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Reference a North Arrow in a style
                StyleProjectItem stylePrjItm   = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                NorthArrowStyleItem naStyleItm = stylePrjItm.SearchNorthArrows("ArcGIS North 10")[0];

                //Build geometry
                Coordinate2D center = new Coordinate2D(7, 5.5);

                //Reference MF, create north arrow and add to layout
                MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
                if (mf == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                NorthArrow arrowElm = LayoutElementFactory.Instance.CreateNorthArrow(layout, center, mf, naStyleItm);
                arrowElm.SetName("New North Arrow");
                arrowElm.SetHeight(1.75);
                arrowElm.SetX(7);
                arrowElm.SetY(6);
            });

            #endregion Create_NorthArrow

            #region Create_Empty_Group_Root
            //Create an empty group element at the root level of the contents pane.


            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                GroupElement emptyGroupAtRoot = LayoutElementFactory.Instance.CreateGroupElement(layout);
                emptyGroupAtRoot.SetName("Empty group at root");
            });

            #endregion

            #region Create_Empty_Group_Group
            //Create an empty group element at the root level of another group element.

            //Find an existing group element
            GroupElement existingGroupAtRoot = layout.FindElement("Empty group at root") as GroupElement;

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                GroupElement emptyGroupInGroupAtRoot = LayoutElementFactory.Instance.CreateGroupElement(existingGroupAtRoot);
                emptyGroupInGroupAtRoot.SetName("Empty group in group at root");
            });

            #endregion

            #region Create_Group_With_Single_Element_Root
            //Create a group with a single element at the root level of the contents pane.

            //Find an existing element
            Element titleElm = layout.FindElement("Title") as Element;

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                GroupElement groupWithSingleElementAtRoot = LayoutElementFactory.Instance.CreateGroupElement(layout, titleElm);
                groupWithSingleElementAtRoot.SetName("Group with single element at root");
            });

            #endregion

            #region Create_Group_With_List_Elements_Root
            //Create a group with a list of elements at the root level of the contents pane.

            //Find an existing elements
            Element scaleBar   = layout.FindElement("Scale Bar") as Element;
            Element northArrow = layout.FindElement("North Arrow") as Element;
            Element legend     = layout.FindElement("Legend") as Element;

            //Build a list and add the elements
            List <Element> elmList = new List <Element>
            {
                scaleBar,
                northArrow,
                legend
            };

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                GroupElement groupWithListOfElementsAtRoot = LayoutElementFactory.Instance.CreateGroupElement(layout, elmList);
                groupWithListOfElementsAtRoot.SetName("Group with list of elements at root");
            });

            #endregion

            #region Create_Group_With_List_Element_Names_Root
            //Create a group using a list of element names at the root level of the contents pane.

            //Build list of element names
            var elmNameList = new[] { "Table Frame", "Chart Frame" };

            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                GroupElement groupWithListOfElementNamesAtRoot = LayoutElementFactory.Instance.CreateGroupElement(layout, elmNameList);
                groupWithListOfElementNamesAtRoot.SetName("Group with list of element names at root");
            });

            #endregion
        }
        public static async Task CreateKeyframes()
        {
            FeatureLayer ftrLayer = null;

            MapView mapView = MapView.Active;

            if (mapView == null)
            {
                return;
            }

            var mapSelection = await QueuedTask.Run(() => MapView.Active.Map.GetSelection());

            if (mapSelection.Count == 1)
            {
                var layer = mapSelection.First().Key;
                if (layer is FeatureLayer)
                {
                    ftrLayer = (FeatureLayer)layer;
                    if (ftrLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
                        return;
                    }

                    int numFtrsSelected = await QueuedTask.Run(() => ftrLayer.GetSelection().GetCount());

                    if (numFtrsSelected != 1)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select only one polyline feature.");
                        return;
                    }
                }
                else
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
                    return;
                }
            }
            else
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
                return;
            }

            if (SelectedCameraView == "Face target" && TargetPoint == null)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Selected view type is - Face target - but a target point is not set.");
                return;
            }

            string oid_fieldName = await QueuedTask.Run(() => ftrLayer.GetTable().GetDefinition().GetObjectIDField());

            //get selected polyline
            Polyline lineGeom = await QueuedTask.Run <Polyline>(() =>
            {
                var selectedFtrOID = MapView.Active.Map.GetSelection()[ftrLayer][0];
                QueryFilter qf     = new QueryFilter();
                qf.WhereClause     = oid_fieldName + " = " + selectedFtrOID.ToString();
                RowCursor result   = ftrLayer.GetFeatureClass().Search(qf);
                if (result != null)
                {
                    result.MoveNext();
                    Feature selectedFtr = result.Current as Feature;
                    return(selectedFtr.GetShape() as Polyline);
                }
                return(null);
            });

            //couldn't get the selected feature
            if (lineGeom == null)
            {
                return;
            }

            ProjectionTransformation transformation = await QueuedTask.Run(() => ProjectionTransformation.Create(ftrLayer.GetSpatialReference(), mapView.Map.SpatialReference));

            SpatialReference layerSpatRef = await QueuedTask.Run(() => ftrLayer.GetSpatialReference());

            if (layerSpatRef.Unit.Name != "Degree")
            {
                Z_CONVERSION_FACTOR = layerSpatRef.Unit.ConversionFactor;
            }

            //Project target point if method is Face target
            if (SelectedCameraView == "Face target")
            {
                if (TargetPoint != null && TargetPoint.SpatialReference != layerSpatRef)
                {
                    ProjectionTransformation transf_forTarget = await QueuedTask.Run(() => ProjectionTransformation.Create(TargetPoint.SpatialReference, layerSpatRef));

                    MapPoint projected_targetPoint = (MapPoint)GeometryEngine.Instance.ProjectEx(TargetPoint, transf_forTarget);
                    TargetPoint = null;
                    TargetPoint = projected_targetPoint;
                }
            }

            var animation   = mapView.Map.Animation;
            var cameraTrack = animation.Tracks.OfType <CameraTrack>().First();
            var keyframes   = cameraTrack.Keyframes;

            //Get segment list for line
            ReadOnlyPartCollection polylineParts = lineGeom.Parts;

            //get total segment count and determine path length
            double pathLength   = 0;
            int    segmentCount = 0;
            IEnumerator <ReadOnlySegmentCollection> segments = polylineParts.GetEnumerator();

            while (segments.MoveNext())
            {
                ReadOnlySegmentCollection seg = segments.Current;
                foreach (Segment s in seg)
                {
                    //pathLength += s.Length;//s.Length returns 2D length

                    double length3D = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
                                                (s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
                                                (s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));

                    pathLength   += length3D;
                    segmentCount += 1;
                }
            }

            //reset heading and pitch
            _keyframeHeading = 0;
            _keyframePitch   = 0;

            // Create keyframes based on chosen method
            if (SelectedMethod == "Keyframes along path")
            {
                await CreateKeyframes_AlongPath(mapView, layerSpatRef, transformation, cameraTrack, segments, segmentCount, pathLength);
            }
            else if (SelectedMethod == "Keyframes every N seconds")
            {
                await CreateKeyframes_EveryNSeconds(mapView, layerSpatRef, transformation, cameraTrack, segments, segmentCount, pathLength, KeyEveryNSecond);
            }
            else if (SelectedMethod == "Keyframes only at vertices")
            {
                await CreateKeyframes_AtVertices(mapView, layerSpatRef, transformation, cameraTrack, lineGeom, segments, segmentCount, pathLength);
            }
        }
Exemplo n.º 20
0
        public async Task <string> LoadData(string[] splitter, string[] fieldTypes, string csvFilePath)
        {
            await QueuedTask.Run(() =>
            {
                string lineOfTxtFile = "";
                FileStream fs        = new FileStream(csvFilePath, FileMode.Open);
                StreamReader sr      = new StreamReader(fs);

                lineOfTxtFile = sr.ReadLine();  // skip the title line
                lineOfTxtFile = sr.ReadLine();

                using (Geodatabase projectWorkspace = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath))))
                    using (Table table = projectWorkspace.OpenDataset <Table>("TestTable"))
                        using (RowBuffer rowBuffer = table.CreateRowBuffer())
                        {
                            while (lineOfTxtFile != null)
                            {
                                string[] dataItems = lineOfTxtFile.Split(splitter, StringSplitOptions.None);

                                for (int i = 0; i < dataItems.Length; i++)
                                {
                                    switch (fieldTypes[i])
                                    {
                                    case "Text":
                                        rowBuffer[i + 1] = dataItems[i].Trim();
                                        break;

                                    case "Short":
                                        if (dataItems[i].Length > 0)
                                        {
                                            if (dataItems[i].Contains("."))
                                            {
                                                rowBuffer[i + 1] = Int16.Parse(dataItems[i].Substring(0, dataItems[i].IndexOf('.')));
                                            }
                                            else
                                            {
                                                rowBuffer[i + 1] = Int16.Parse(dataItems[i]);
                                            }
                                        }
                                        else
                                        {
                                            rowBuffer[i + 1] = null;
                                        }
                                        break;

                                    case "Long":
                                        if (dataItems[i].Length > 0)
                                        {
                                            if (dataItems[i].Contains("."))
                                            {
                                                rowBuffer[i + 1] = int.Parse(dataItems[i].Substring(0, dataItems[i].IndexOf('.')));
                                            }
                                            else
                                            {
                                                rowBuffer[i + 1] = int.Parse(dataItems[i]);
                                            }
                                        }
                                        else
                                        {
                                            rowBuffer[i + 1] = null;
                                        }
                                        break;

                                    case "Date":
                                        if (dataItems[i].Length > 0)
                                        {
                                            rowBuffer[i + 1] = DateTime.Parse(dataItems[i]);
                                        }
                                        else
                                        {
                                            rowBuffer[i + 1] = null;
                                        }
                                        break;

                                    case "Double":
                                        if (dataItems[i].Length > 0)
                                        {
                                            rowBuffer[i + 1] = double.Parse(dataItems[i]);
                                        }
                                        else
                                        {
                                            rowBuffer[i + 1] = null;
                                        }
                                        break;

                                    default:
                                        break;
                                    }
                                }
                                table.CreateRow(rowBuffer);
                                lineOfTxtFile = sr.ReadLine();
                            }
                            rowBuffer.Dispose();
                        }
            });

            return("ok");
        }
        //Use this method for smoother turns at corners. Additionally this method processes straight line segments and arc segments separately
        //For arc segments a keyframe is created at every second. However a minimum of 5 keyframes are created for arcs.
        //So if arc segment length is less than 5 then we default to at least 5 keyframes. This is an attempt to stick to the path as much as possible.
        //For straight line segments, rotation is ignored at end point of each segment except for the end point of the path itself. Two keyframes with rotation
        //are created at certain distance (determined by LINE_CONSTRAINT_FACTOR) before and after the end point of each segment. This is an attempt to avoid
        //sharp turns at corners along the path.
        public static async Task CreateKeyframes_AlongPath(MapView mapView, SpatialReference layerSpatRef, ProjectionTransformation transformation,
                                                           CameraTrack cameraTrack, IEnumerator <ReadOnlySegmentCollection> segments,
                                                           int segmentCount, double pathLength)
        {
            double segmentLength  = 0;
            int    num_iterations = 0;

            segments.Reset();

            //process each segment depending upon its type - straight line or arc
            while (segments.MoveNext())
            {
                ReadOnlySegmentCollection seg = segments.Current;
                double accumulatedDuration    = mapView.Map.Animation.Duration.TotalSeconds + ((mapView.Map.Animation.Duration.TotalSeconds > 0) ? ANIMATION_APPEND_TIME : 0); // 0;

                foreach (Segment s in seg)
                {
                    double length3D = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
                                                (s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
                                                (s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));


                    double segmentDuration = (TotalDuration / pathLength) * length3D;
                    segmentLength = length3D;

                    //straight line segments
                    if (s.SegmentType == SegmentType.Line)
                    {
                        MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z *Z_CONVERSION_FACTOR, layerSpatRef));

                        MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z *Z_CONVERSION_FACTOR, layerSpatRef));

                        //we will be creating three intermediate keyframes for staright segments only if segment length is more than a set threshold
                        //the threshold is just a guess and might have to be altered depending upon the path geometry. Should work for most cases though
                        MapPoint firstIntPoint = null;
                        MapPoint midIntPoint   = null;
                        MapPoint lastIntPoint  = null;

                        if (segmentLength >= STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
                        {
                            //first intermediate point
                            firstIntPoint = await CreatePointAlongSegment(startPt, endPt, LINE_CONSTRAINT_FACTOR *segmentLength, layerSpatRef);

                            //mid point
                            midIntPoint = await CreatePointAlongSegment(startPt, endPt, 0.5 *segmentLength, layerSpatRef);

                            //last intermediate point
                            lastIntPoint = await CreatePointAlongSegment(startPt, endPt, (1 - LINE_CONSTRAINT_FACTOR) *segmentLength, layerSpatRef);
                        }

                        //create keyframe at start vertex of path in map space
                        double   timeSpanValue    = accumulatedDuration;
                        TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                        if (segmentLength >= STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
                        {
                            SetPitchAndHeadingForLine(startPt, firstIntPoint);
                        }
                        else
                        {
                            SetPitchAndHeadingForLine(startPt, endPt);
                        }

                        //ignore rotation for all start vertices (which would also be end vertices of previous segments) EXCEPT for the first vertex of path
                        if (num_iterations == 0 || segmentLength < STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                        else
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
                        }

                        if (segmentLength > STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
                        {
                            //Create a keyframe at PATH_CONSTRAINT_FACTOR distance along the segment from start point
                            double distanceAlong = LINE_CONSTRAINT_FACTOR * segmentLength;
                            timeSpanValue    = accumulatedDuration + LINE_CONSTRAINT_FACTOR * segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                            SetPitchAndHeadingForLine(firstIntPoint, midIntPoint);
                            await CreateCameraKeyframe(mapView, firstIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                            //Create a keyframe at middle of segment
                            distanceAlong    = 0.5 * segmentLength;
                            timeSpanValue    = accumulatedDuration + 0.5 * segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                            SetPitchAndHeadingForLine(midIntPoint, lastIntPoint);
                            //await CreateCameraKeyframe(mapView, midIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                            //Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR) distance along the segment from start point
                            distanceAlong    = (1 - LINE_CONSTRAINT_FACTOR) * segmentLength;
                            timeSpanValue    = accumulatedDuration + (1 - LINE_CONSTRAINT_FACTOR) * segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                            SetPitchAndHeadingForLine(lastIntPoint, endPt);
                            await CreateCameraKeyframe(mapView, lastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }

                        //Create a keyframe at end point of segment only for the end point of last segment
                        //Otherwise we will get duplicate keyframes at end of one segment and start of the next one
                        if (num_iterations == segmentCount - 1)
                        {
                            timeSpanValue    = accumulatedDuration + segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                            if (SelectedCameraView == "Face target")
                            {
                                SetPitchAndHeadingForLine(endPt, TargetPoint);
                            }

                            await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                    }
                    //processing for arcs - create a keyframe every second for arcs
                    //we will create a minimum of 5 keyframes along the arc
                    else if (s.SegmentType == SegmentType.EllipticArc && segmentDuration > 5)
                    {
                        EllipticArcSegment ellipArc = s as EllipticArcSegment;
                        MapPoint           startPt  = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));

                        MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));

                        double   radius   = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
                        double   angle    = ellipArc.CentralAngle;
                        MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));

                        int num_keys = (int)segmentDuration;

                        MapPoint firstIntPoint = null;

                        //first intermediate keyframe for arc - needed for setting heading for start vertex
                        // >2 to account for start and end
                        if (num_keys > 2)
                        {
                            firstIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle / (num_keys - 1), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
                        }

                        //Create keyframe at start vertex of path in map space
                        double   timeSpanValue    = accumulatedDuration;
                        TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                        if (firstIntPoint != null)
                        {
                            SetPitchAndHeadingForLine(startPt, firstIntPoint);
                        }
                        else
                        {
                            SetPitchAndHeadingForLine(startPt, endPt);
                        }

                        //Ignore rotation for all start vertices EXCEPT for the first vertex of path
                        if (num_iterations == 0)
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                        else
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
                        }

                        //Loop to create intermediate keyframes at each second
                        for (int i = 0; i < num_keys - 2; i++)
                        {
                            MapPoint currentIntPoint = null;
                            MapPoint nextIntPoint    = null;

                            currentIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, (angle / (num_keys - 1)) *(i + 1), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                            if (i < num_keys - 3)
                            {
                                nextIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, (angle / (num_keys - 1)) *(i + 2), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
                            }
                            else //for the last intermediate keyframe, heading/pitch has to be determined relative to the end point fo segment
                            {
                                nextIntPoint = endPt;
                            }
                            //timeSpanValue = accumulatedDuration + (i + 1) * 1; //at each second
                            timeSpanValue = accumulatedDuration + (i + 1) * (segmentDuration / (num_keys - 1));

                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                            SetPitchAndHeadingForLine(currentIntPoint, nextIntPoint);
                            await CreateCameraKeyframe(mapView, currentIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }

                        //Create a keyframe at end point of segment only for the end point of last segment
                        if (num_iterations == segmentCount - 1)
                        {
                            timeSpanValue    = accumulatedDuration + segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                            if (SelectedCameraView == "Face target")
                            {
                                SetPitchAndHeadingForLine(endPt, TargetPoint);
                            }

                            await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                    }
                    //create a minimum of 5 keyframes along the arc
                    else if (s.SegmentType == SegmentType.EllipticArc)
                    {
                        EllipticArcSegment ellipArc = s as EllipticArcSegment;
                        MapPoint           startPt  = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));

                        MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));

                        double   radius   = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
                        double   angle    = ellipArc.CentralAngle;
                        MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));

                        //we are creating five intermediate keyframes for arcs
                        MapPoint firstIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle *ARC_CONSTRAINT_FACTOR, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                        MapPoint secondIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle *ARC_CONSTRAINT_FACTOR * 2, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                        MapPoint midIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * 0.5, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                        MapPoint secondLastIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle *(1 - ARC_CONSTRAINT_FACTOR * 2), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                        MapPoint lastIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle *(1 - ARC_CONSTRAINT_FACTOR), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                        //Create keyframe at start vertex of path in map space
                        double   timeSpanValue    = accumulatedDuration;
                        TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(startPt, firstIntPoint);

                        //Ignore rotation for all start vertices EXCEPT for the first vertex of path
                        if (num_iterations == 0)
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                        else
                        {
                            await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
                        }

                        //await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at PATH_CONSTRAINT_FACTOR distance along the segment from start point
                        timeSpanValue    = accumulatedDuration + ARC_CONSTRAINT_FACTOR * segmentDuration;
                        keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(firstIntPoint, secondIntPoint);
                        await CreateCameraKeyframe(mapView, firstIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at 2* PATH_CONSTRAINT_FACTOR distance along the segment from start point
                        timeSpanValue    = accumulatedDuration + ARC_CONSTRAINT_FACTOR * 2 * segmentDuration;
                        keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(secondIntPoint, midIntPoint);
                        await CreateCameraKeyframe(mapView, secondIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at middle of segment
                        timeSpanValue    = accumulatedDuration + 0.5 * segmentDuration;
                        keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(midIntPoint, secondLastIntPoint);
                        await CreateCameraKeyframe(mapView, midIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR * 2) distance along the segment from start point
                        timeSpanValue    = accumulatedDuration + (1 - ARC_CONSTRAINT_FACTOR * 2) * segmentDuration;
                        keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(secondLastIntPoint, lastIntPoint);
                        await CreateCameraKeyframe(mapView, secondLastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR) distance along the segment from start point
                        timeSpanValue    = accumulatedDuration + (1 - ARC_CONSTRAINT_FACTOR) * segmentDuration;
                        keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
                        SetPitchAndHeadingForLine(lastIntPoint, endPt);
                        await CreateCameraKeyframe(mapView, lastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                        //Create a keyframe at end point of segment only for the end point of last segment
                        if (num_iterations == segmentCount - 1)
                        {
                            timeSpanValue    = accumulatedDuration + segmentDuration;
                            keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                            if (SelectedCameraView == "Face target")
                            {
                                SetPitchAndHeadingForLine(endPt, TargetPoint);
                            }

                            await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                        }
                    }

                    accumulatedDuration += segmentDuration;
                    num_iterations++;
                }
            }
        }
Exemplo n.º 22
0
        public async void Examples()
        {
            #region Get symbol from SymbolStyleItem
            SymbolStyleItem symbolItem = null;
            CIMSymbol       symbol     = await QueuedTask.Run <CIMSymbol>(() =>
            {
                return(symbolItem.Symbol);
            });

            #endregion

            #region Get color from ColorStyleItem
            ColorStyleItem colorItem = null;
            CIMColor       color     = await QueuedTask.Run <CIMColor>(() =>
            {
                return(colorItem.Color);
            });

            #endregion

            #region Get color ramp from ColorRampStyleItem
            ColorRampStyleItem colorRampItem = null;
            CIMColorRamp       colorRamp     = await QueuedTask.Run <CIMColorRamp>(() =>
            {
                return(colorRampItem.ColorRamp);
            });

            #endregion

            #region Get north arrow from NorthArrowStyleItem
            NorthArrowStyleItem northArrowItem = null;
            CIMNorthArrow       northArrow     = await QueuedTask.Run <CIMNorthArrow>(() =>
            {
                return(northArrowItem.NorthArrow);
            });

            #endregion

            #region Get scale bar from ScaleBarStyleItem
            ScaleBarStyleItem scaleBarItem = null;
            CIMScaleBar       scaleBar     = await QueuedTask.Run <CIMScaleBar>(() =>
            {
                return(scaleBarItem.ScaleBar);
            });

            #endregion

            #region Get label placement from LabelPlacementStyleItem
            LabelPlacementStyleItem     labelPlacementItem = null;
            CIMLabelPlacementProperties labelPlacement     = await QueuedTask.Run <CIMLabelPlacementProperties>(() =>
            {
                return(labelPlacementItem.LabelPlacement);
            });

            #endregion

            #region Get grid from GridStyleItem
            GridStyleItem gridItem = null;
            CIMMapGrid    grid     = await QueuedTask.Run <CIMMapGrid>(() =>
            {
                return(gridItem.Grid);
            });

            #endregion

            #region Get legend from LegendStyleItem
            LegendStyleItem legendItem = null;
            CIMLegend       legend     = await QueuedTask.Run <CIMLegend>(() =>
            {
                return(legendItem.Legend);
            });

            #endregion

            #region Get table frame from TableFrameStyleItem
            TableFrameStyleItem tableFrameItem = null;
            CIMTableFrame       tableFrame     = await QueuedTask.Run <CIMTableFrame>(() =>
            {
                return(tableFrameItem.TableFrame);
            });

            #endregion

            #region Get map surround from MapSurroundStyleItem
            MapSurroundStyleItem mapSurroundItem = null;
            CIMMapSurround       mapSurround     = await QueuedTask.Run <CIMMapSurround>(() =>
            {
                return(mapSurroundItem.MapSurround);
            });

            #endregion

            #region Get dimension style from DimensionStyleStyleItem
            DimensionStyleStyleItem dimensionStyleStyleItem = null;
            CIMDimensionStyle       dimensionStyle          = await QueuedTask.Run <CIMDimensionStyle>(() =>
            {
                return(dimensionStyleStyleItem.DimensionStyle);
            });

            #endregion
        }
        //Use this method to create a keyframe at every n-second of the specified animation duration
        public static async Task CreateKeyframes_EveryNSeconds(MapView mapView, SpatialReference layerSpatRef, ProjectionTransformation transformation,
                                                               CameraTrack cameraTrack, IEnumerator <ReadOnlySegmentCollection> segments,
                                                               int segmentCount, double pathLength, double keyEveryNSecond = 1)
        {
            double segmentLength   = 0;
            int    numKeysToCreate = (int)(TotalDuration / keyEveryNSecond); //approximately
            double createKeyAtDist = pathLength / numKeysToCreate;

            double skippedDistance     = 0;
            double accumulatedDuration = mapView.Map.Animation.Duration.TotalSeconds + ((mapView.Map.Animation.Duration.TotalSeconds > 0) ? ANIMATION_APPEND_TIME : 0); // 0;

            int num_iterations = 0;

            segments.Reset();

            List <MapPoint> pointsForKeyframes = new List <MapPoint>();

            MapPoint pathEndPt = null;

            //process each segment depending upon its type - straight line or arc
            while (segments.MoveNext())
            {
                ReadOnlySegmentCollection seg = segments.Current;

                foreach (Segment s in seg)
                {
                    segmentLength = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
                                              (s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
                                              (s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));

                    double segmentDuration = (TotalDuration / pathLength) * segmentLength;

                    //straight line segments
                    if (s.SegmentType == SegmentType.Line)
                    {
                        MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));

                        MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));

                        //add start of path to points collection
                        if (num_iterations == 0)
                        {
                            pointsForKeyframes.Add(startPt);
                        }

                        if (num_iterations == segmentCount - 1 || segmentCount == 1)
                        {
                            pathEndPt = endPt; //store path end pt. This will be the last keyframe.
                        }

                        double distCoveredAlongSeg = Math.Abs(createKeyAtDist - skippedDistance); //we are accouunting for skipped distances from previous segments

                        if (distCoveredAlongSeg < segmentLength)
                        {
                            MapPoint keyPt = await CreatePointAlongSegment(startPt, endPt, distCoveredAlongSeg, layerSpatRef);

                            //add point to collection
                            pointsForKeyframes.Add(keyPt);

                            //skipped distance is used now, reset to zero
                            skippedDistance = 0;

                            //are more keyframes possible for this segment
                            bool moreKeysPossible = ((segmentLength - distCoveredAlongSeg) >= createKeyAtDist);

                            while (moreKeysPossible)
                            {
                                double keyAtDistAlongSeg = distCoveredAlongSeg + createKeyAtDist;

                                keyPt = await CreatePointAlongSegment(startPt, endPt, keyAtDistAlongSeg, layerSpatRef);

                                //add point to collection
                                pointsForKeyframes.Add(keyPt);

                                distCoveredAlongSeg += createKeyAtDist;

                                moreKeysPossible = ((segmentLength - distCoveredAlongSeg) > createKeyAtDist);
                            }

                            //if any segment length left then add to skipped distance
                            skippedDistance += (segmentLength - distCoveredAlongSeg);
                        }
                        else
                        {
                            //add this segment's length to skipped distance as no keyframe could be created along it
                            skippedDistance += segmentLength;
                        }
                    }
                    else if (s.SegmentType == SegmentType.EllipticArc)
                    {
                        EllipticArcSegment ellipArc = s as EllipticArcSegment;
                        MapPoint           startPt  = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));

                        MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));

                        double   radius   = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
                        double   angle    = ellipArc.CentralAngle;
                        MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));

                        //add start of path to points collection
                        if (num_iterations == 0)
                        {
                            pointsForKeyframes.Add(startPt);
                        }

                        if (num_iterations == segmentCount - 1 || segmentCount == 1)
                        {
                            pathEndPt = endPt; //store path end pt. This will be the last keyframe.
                        }

                        double distCoveredAlongSeg = Math.Abs(createKeyAtDist - skippedDistance); //we are accouunting for skipped distances from previous segments

                        if (distCoveredAlongSeg < segmentLength)
                        {
                            MapPoint keyPt = await CreatePointAlongArc(startPt, endPt, centerPt, angle *distCoveredAlongSeg / segmentLength, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                            //add point to collection
                            pointsForKeyframes.Add(keyPt);

                            //skipped distance is used now, reset to zero
                            skippedDistance = 0;

                            //are more keyframes possible for this segment
                            bool moreKeysPossible = ((segmentLength - distCoveredAlongSeg) >= createKeyAtDist);

                            while (moreKeysPossible)
                            {
                                double keyAtDistAlongSeg = distCoveredAlongSeg + createKeyAtDist;

                                keyPt = await CreatePointAlongArc(startPt, endPt, centerPt, angle *keyAtDistAlongSeg / segmentLength, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);

                                //add point to collection
                                pointsForKeyframes.Add(keyPt);

                                distCoveredAlongSeg += createKeyAtDist;

                                moreKeysPossible = ((segmentLength - distCoveredAlongSeg) > createKeyAtDist);
                            }

                            //if any segment length left then add to skipped distance
                            skippedDistance += (segmentLength - distCoveredAlongSeg);
                        }
                        else
                        {
                            //add this segment's length to skipped distance as no keyframe could be created along it
                            skippedDistance += segmentLength;
                        }
                    }

                    num_iterations++;
                }
            }

            //now iterate over the points list and create keyframes

            double   timeSpanValue    = accumulatedDuration;
            TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

            for (int i = 0; i < pointsForKeyframes.Count; i++)
            {
                MapPoint currentPt = pointsForKeyframes[i];
                MapPoint nextPt    = null;

                if (i + 1 < pointsForKeyframes.Count)
                {
                    nextPt = pointsForKeyframes[i + 1];
                }
                else
                {
                    nextPt = pathEndPt;
                }

                timeSpanValue    = i * keyEveryNSecond + accumulatedDuration;
                keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);

                SetPitchAndHeadingForLine(currentPt, nextPt);
                await CreateCameraKeyframe(mapView, currentPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);

                if (i == pointsForKeyframes.Count - 1 && skippedDistance > 0)
                {
                    keyframeTimespan = TimeSpan.FromSeconds(TotalDuration + accumulatedDuration);
                    await CreateCameraKeyframe(mapView, pathEndPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
                }
            }
        }
Exemplo n.º 24
0
        public void GenerateKeyframes(string animationType)
        {
            try
            {
                QueuedTask.Run(async() =>
                {
                    if (VehicleListComboBoxValue.Text == "" || VehicleListComboBoxValue.Text == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No Vehicle Route selected. Exiting...", "Value Needed");
                        return;
                    }

                    string VehiclePointsLayer = VehicleListComboBoxValue.Text + "_Route";

                    // Iterate and list the layers within the group layer
                    // string pointLayerName = System.IO.Path.GetFileName(outfc);
                    var pointLayer = MapView.Active.Map.FindLayers("VehiclePoints_" + VehiclePointsLayer).FirstOrDefault() as BasicFeatureLayer;
                    if (pointLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Can't find the layer: " + "VehiclePoints_" + VehiclePointsLayer + ". Exiting...", "Info");
                        return;
                    }

                    // Ensure there's a value in the speed edit box
                    if (SpeedValueEditBox.Text == "" && animationType == "use speed")
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The Speed in MPH value Editbox is empty. Exiting...", "Value Needed");
                        SpeedValueEditBox.Text = "";
                        return;
                    }

                    double speedValueMPH;
                    bool isNumeric = Double.TryParse(SpeedValueEditBox.Text, out speedValueMPH);
                    // Ensure there's a value in the speed edit box
                    if (isNumeric != true && animationType == "use speed")
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The Speed in MPH value Editbox is not invalid. Type in a new value. Exiting...", "Value Needed");
                        SpeedValueEditBox.Text = "";
                        return;
                    }

                    // Prompt for confirmation, and if answer is no, return.
                    if (animationType == "use speed")
                    {
                        var result = MessageBox.Show("Confirm building of " + VehicleListComboBoxValue.Text.ToUpper() + " animation simulating vehicle speed of " + SpeedValueEditBox.Text + " MPH?", "Build Animation", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Asterisk);
                        // Return if cancel value is chosen
                        if (Convert.ToString(result) == "Cancel")
                        {
                            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Operation cancelled.", "Info");
                            return;
                        }
                    }
                    else if (animationType == "ten-second")
                    {
                        var result = MessageBox.Show("Confirm building of " + VehicleListComboBoxValue.Text.ToUpper() + " 10-SECOND duration animation?", "Build Animation", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Asterisk);
                        // Return if cancel value is chosen
                        if (Convert.ToString(result) == "Cancel")
                        {
                            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Operation cancelled.", "Info");
                            return;
                        }
                    }


                    int viewDistance = 0;
                    if (VehiclePointsLayer == "Car_Route")
                    {
                        viewDistance = 100;
                    }
                    else if (VehiclePointsLayer == "Boat_Route")
                    {
                        viewDistance = 200;
                    }
                    else if (VehiclePointsLayer == "Helicopter_Route")
                    {
                        viewDistance = 300;
                    }



                    // SET UP 3D MODEL SYMBOL AND SETTINGS

                    // Use the speed value to set keyframe timespan - Calculate distance covered in seconds and milliseconds based on speed and distance between points
                    // NOTE:  Assumes map units are in feet.  This is key.
                    // Calculate the Timespan using speed:

                    int rowNumber;
                    RowCursor pointsRowcursor;
                    int numPoints;
                    // Tempororily set to empty timespans
                    TimeSpan temp_span        = new TimeSpan(0, 0, 0, 0, 0);
                    TimeSpan temp_newTimeSpan = new TimeSpan(0, 0, 0, 0, 0);

                    if (animationType == "use speed")
                    {
                        // Get the value of the distance between features.
                        rowNumber          = 0;
                        MapPoint mapPoint1 = null;
                        MapPoint mapPoint2 = null;
                        pointsRowcursor    = pointLayer.Search(null);
                        numPoints          = pointLayer.GetTable().GetCount();
                        while (rowNumber < 3)
                        {
                            rowNumber = rowNumber + 1;
                            using (Row currentRow = pointsRowcursor.Current)
                            {
                                pointsRowcursor.MoveNext();
                                var pointFeature = pointsRowcursor.Current as Feature;
                                if (rowNumber == 1)
                                {
                                    mapPoint1 = pointFeature.GetShape() as MapPoint;
                                }
                                else if (rowNumber == 2)
                                {
                                    mapPoint2 = pointFeature.GetShape() as MapPoint;
                                }
                            }
                        }

                        pointsRowcursor.Dispose();

                        double dblDistBetween     = GeometryEngine.Instance.Distance(mapPoint1, mapPoint2);
                        double dblFeetPerSecond   = (speedValueMPH * 5280) / 3600;
                        double dblSecondsPerPoint = dblDistBetween / dblFeetPerSecond;

                        Double dblSec      = Math.Truncate(dblSecondsPerPoint);
                        Double dblMilliSec = dblSecondsPerPoint - dblSec;
                        // round it
                        dblMilliSec           = Math.Round(dblMilliSec, 3);
                        string strFixMilliSec = Convert.ToString(dblMilliSec);
                        strFixMilliSec        = strFixMilliSec.Remove(0, 2);
                        Int32 intMilliSec     = Convert.ToInt32(strFixMilliSec);
                        Int32 intSec          = Convert.ToInt32(dblSec);

                        temp_span        = new TimeSpan(0, 0, 0, intSec, intMilliSec);
                        temp_newTimeSpan = new TimeSpan(0, 0, 0, 0, 0);
                    }

                    else if (animationType == "ten-second")
                    {
                        temp_span        = new TimeSpan(0, 0, 0, 0, 40);
                        temp_newTimeSpan = new TimeSpan(0, 0, 0, 0, 0);
                    }

                    TimeSpan span        = temp_span;
                    TimeSpan newTimeSpan = temp_newTimeSpan;

                    var currentmapview = MapView.Active;
                    var mapAnimation   = currentmapview.Map.Animation;
                    var currentcamera  = currentmapview.Camera;
                    var newCamera      = currentcamera;

                    // Use GetDisconnectedTracks
                    List <Track> tracks = mapAnimation.GetDisconnectedTracks();
                    var cameraTrack     = tracks.OfType <CameraTrack>().First();
                    var rangeTrack      = tracks.OfType <RangeTrack>().First();

                    int cameraJumpVal    = 0;
                    rowNumber            = 0;
                    string cameraSetting = "perspective";
                    Feature prevFeature  = null;
                    MapPoint prevPoint   = null;
                    pointsRowcursor      = pointLayer.Search(null);
                    numPoints            = pointLayer.GetTable().GetCount();
                    while (pointsRowcursor.MoveNext())
                    {
                        rowNumber = rowNumber + 1;
                        using (Row currentRow = pointsRowcursor.Current)
                        {
                            var pointFeature = pointsRowcursor.Current as Feature;
                            var mapPoint     = pointFeature.GetShape() as MapPoint;


                            // if prevPoint == null, skip creation of keyframe
                            if (prevFeature != null)
                            {
                                double bearingRadians        = 0;
                                string bearingValForKeyframe = Convert.ToString(currentRow["BEARING"]);

                                if (rowNumber == 2)  // View from behind vehicle to begin animation

                                {
                                    double bearingVal = Convert.ToDouble(currentRow["BEARING"]) + 180;
                                    bearingRadians    = (Math.PI / 180) * bearingVal;
                                    cameraJumpVal     = 12;
                                }
                                else if (rowNumber == numPoints)  // Last point, build keyframe with camera facing the front of the vehicle:
                                {
                                    double bearingVal = Convert.ToDouble(currentRow["BEARING"]) + 0;
                                    bearingRadians    = (Math.PI / 180) * bearingVal;
                                    cameraJumpVal     = 12;
                                }
                                else  // View from the side
                                {
                                    double bearingVal = Convert.ToDouble(currentRow["BEARING"]) + 270;
                                    bearingRadians    = (Math.PI / 270) * bearingVal;
                                }

                                double xNew = mapPoint.X + viewDistance * Math.Cos(Math.PI / 2 - bearingRadians);
                                double yNew = mapPoint.Y + viewDistance * Math.Sin(Math.PI / 2 - bearingRadians);

                                MapPoint newprevPoint = MapPointBuilder.CreateMapPoint(xNew, yNew);
                                double headingCalc    = CalculateHeading(newprevPoint, mapPoint);
                                newCamera.Heading     = headingCalc;

                                newCamera.X = xNew;
                                newCamera.Y = yNew;

                                if (VehiclePointsLayer == "Helicopter_Route")
                                {
                                    newCamera.Z = mapPoint.Z + 60;
                                }
                                else
                                {
                                    newCamera.Z = 60;
                                }

                                newCamera.Pitch     = -5;
                                newCamera.Viewpoint = CameraViewpoint.LookAt;

                                double sequenceVal = Convert.ToDouble(currentRow["Sequence"]);
                                Range newRange     = new Range();
                                newRange.Min       = sequenceVal;
                                newRange.Max       = sequenceVal;

                                // Create and edit the keyframes
                                rangeTrack.CreateKeyframe(newRange, newTimeSpan, AnimationTransition.Linear);
                                //newTimeSpan = newTimeSpan.Add(span);


                                if (cameraSetting == "perspective" && cameraJumpVal == 12)
                                {
                                    // rangeTrack.CreateKeyframe(newRange, newTimeSpan, AnimationTransition.Linear);
                                    // Set up side / angle perspective for the camera and create keyframe
                                    cameraTrack.CreateKeyframe(newCamera, newTimeSpan, AnimationTransition.Linear);
                                    cameraJumpVal = 0;
                                }

                                newTimeSpan = newTimeSpan.Add(span);
                            }

                            prevFeature = pointFeature;
                            prevPoint   = prevFeature.GetShape() as MapPoint;
                        }


                        cameraJumpVal = cameraJumpVal + 1;
                    }


                    // Wrap up the animation
                    mapAnimation.Tracks = tracks;

                    // Final calculation for the recommendation on keyframes for video export:
                    // Get decimal seconds of newTimeSpan and use numPoints for number of keyframes
                    double keyframesTotal = Convert.ToDouble(numPoints);
                    double seconds        = newTimeSpan.TotalSeconds;
                    double kpsValue       = keyframesTotal / seconds;
                    double reccomendedKPS;
                    if (kpsValue > 50)
                    {
                        var kpsDivision = kpsValue / 25;
                        int kpsDivider  = Convert.ToInt16(Math.Truncate(kpsDivision));
                        reccomendedKPS  = kpsValue / kpsDivider;
                    }
                    else
                    {
                        reccomendedKPS = kpsValue;
                    }

                    string strReccKPS = Convert.ToString(Math.Round(reccomendedKPS, 0));

                    MessageBox.Show("Animation built.  View timeline and/or export movie. \r\n" +
                                    "NOTE:  Recommended Frames Per Second setting for Export: \r\n" +
                                    strReccKPS + " Frames Per Second", "Info");
                });
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error in GenerateKeyframes:  " + ex.ToString(), "Error");
            }
        }   // End of GenerateKeyframes()
Exemplo n.º 25
0
        protected override Task OnToolActivateAsync(bool active)
        {
            //return addFeatureLayer();

            /*
             * ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL)
             * {
             *      AuthenticationMode = AuthenticationMode.DBMS,
             *      Instance = @"127.0.0.1",
             *      Database = "geomapmaker2",
             *      User = "******",
             *      Password = "******",
             *      //Version = "dbo.DEFAULT"
             * };
             *
             * using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
             * {
             *      IReadOnlyList<string> createParams = Geoprocessing.MakeValueArray(new object[] { geodatabase, "fc01", null, null });
             *      return Geoprocessing.ExecuteToolAsync("management.CreateFeatureClass", createParams);
             * }
             */

            return(QueuedTask.Run(async() =>
            {
                //This works, but creates an xml representation of the connect string. Not sure that's what the next call wants
                var cStr = "";
                IReadOnlyList <string> cParams = Geoprocessing.MakeValueArray(new object[] {
                    "POSTGRESQL",
                    @"127.0.0.1",
                    "DATABASE_AUTH ",
                    "geomapmaker2",
                    "password",
                    "geomapmaker2"
                });
                IGPResult res = await Geoprocessing.ExecuteToolAsync("management.CreateDatabaseConnectionString", cParams);
                if (!res.IsFailed)
                {
                    Debug.WriteLine("conn string = " + res.ReturnValue);
                    cStr = res.ReturnValue;
                }
                else
                {
                    Debug.WriteLine("failed ErrorCode " + res.ErrorCode);
                    Debug.WriteLine("failed ReturnValue " + res.ReturnValue);
                    foreach (IGPMessage msg in res.Messages)
                    {
                        Debug.WriteLine("failed msg text " + msg.Text);
                    }
                }

                /*
                 * // this works
                 * IReadOnlyList<string> cParams = Geoprocessing.MakeValueArray(new object[] {
                 *      "C:/toolTest",
                 *      "test01"
                 * });
                 * IGPResult res = await Geoprocessing.ExecuteToolAsync("management.CreateFolder", cParams);
                 * if (!res.IsFailed)
                 * {
                 *      Debug.WriteLine("folder = " + res.ReturnValue);
                 * }
                 * else
                 * {
                 *      Debug.WriteLine("failed!!!! " + res.ErrorCode);
                 *      Debug.WriteLine("failed!!!! " + res.ReturnValue);
                 *      foreach (IGPMessage msg in res.Messages)
                 *      {
                 *              Debug.WriteLine("failed!!!! " + msg.Text);
                 *
                 *      }
                 * }
                 */


                ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL)
                {
                    AuthenticationMode = AuthenticationMode.DBMS,
                    Instance = @"127.0.0.1",
                    Database = "geomapmaker2",
                    User = "******",
                    Password = "******",
                    //Version = "dbo.DEFAULT"
                };

                using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                {
                    //Call fails no matter what I pass as connection string. No error is generated.
                    cStr = geodatabase.GetConnectionString();
                    //cStr = "ENCRYPTED_PASSWORD=00022e6877513471743162776f4c684e454a3363556157765177616373677361465977513463364c2b314c386165733d2a00;SERVER=127.0.0.1;INSTANCE=sde:postgresql:127.0.0.1;DBCLIENT=postgresql;DB_CONNECTION_PROPERTIES=127.0.0.1;DATABASE=geomapmaker2;USER=geomapmaker2;VERSION=sde.DEFAULT;AUTHENTICATION_MODE=DBMS";
                    //TODO: build this connection string using GeoProcessing "management.CreateDatabaseConnectionString"?
                    Debug.WriteLine("cStr = " + cStr);
                    IReadOnlyList <string> createParams = Geoprocessing.MakeValueArray(new object[] { cStr, "fc01", "POLYGON" });
                    //file gdb works:
                    //IReadOnlyList<string> createParams = Geoprocessing.MakeValueArray(new object[] { "C:/toolTest", "fc01", "POLYGON" });
                    res = await Geoprocessing.ExecuteToolAsync("management.CreateFeatureclass", createParams);
                    if (res.IsFailed)
                    {
                        Debug.WriteLine("feature class fail!!! = " + res.ErrorCode);
                        Debug.WriteLine("fc failed ReturnValue " + res.ReturnValue);
                        foreach (IGPMessage msg in res.Messages)
                        {
                            Debug.WriteLine("fc failed msg text " + msg.Text);
                        }
                    }
                }
            }));
        }
Exemplo n.º 26
0
        public Task <int> CountFeaturesAsyc()
        {
            Func <int> methodToCall = CountFeatures;

            return(QueuedTask.Run(methodToCall));
        }
        /// <summary>
        /// Method used to convert a string to a known coordinate
        /// Assumes WGS84 for now
        /// </summary>
        /// <param name="coordinate">the coordinate as a string</param>
        /// <returns>MapPoint if successful, null if not</returns>
        internal MapPoint GetMapPointFromString(string coordinate)
        {
            MapPoint point = null;

            // future use if order of GetValues is not acceptable
            //var listOfTypes = new List<GeoCoordinateType>(new GeoCoordinateType[] {
            //    GeoCoordinateType.DD,
            //    GeoCoordinateType.DDM,
            //    GeoCoordinateType.DMS,
            //    GeoCoordinateType.GARS,
            //    GeoCoordinateType.GeoRef,
            //    GeoCoordinateType.MGRS,
            //    GeoCoordinateType.USNG,
            //    GeoCoordinateType.UTM
            //});

            var listOfTypes = Enum.GetValues(typeof(GeoCoordinateType)).Cast <GeoCoordinateType>();

            foreach (var type in listOfTypes)
            {
                try
                {
                    point = QueuedTask.Run(() =>
                    {
                        return(MapPointBuilder.FromGeoCoordinateString(coordinate, MapView.Active.Map.SpatialReference, type, FromGeoCoordinateMode.Default));
                    }).Result;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }

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

            try
            {
                point = QueuedTask.Run(() =>
                {
                    return(MapPointBuilder.FromGeoCoordinateString(coordinate, MapView.Active.Map.SpatialReference, GeoCoordinateType.UTM, FromGeoCoordinateMode.UtmNorthSouth));
                }).Result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            if (point == null)
            {
                coordinate = coordinate.Trim();

                Regex regexMercator = new Regex(@"^(?<latitude>\-?\d+\.?\d*)[+,;:\s]*(?<longitude>\-?\d+\.?\d*)");

                var matchMercator = regexMercator.Match(coordinate);

                if (matchMercator.Success && matchMercator.Length == coordinate.Length)
                {
                    try
                    {
                        var Lat = Double.Parse(matchMercator.Groups["latitude"].Value);
                        var Lon = Double.Parse(matchMercator.Groups["longitude"].Value);
                        point = QueuedTask.Run(() =>
                        {
                            return(MapPointBuilder.CreateMapPoint(Lon, Lat, MapView.Active.Map.SpatialReference));
                        }).Result;
                        return(point);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        return(null);
                    }
                }
            }

            return(point);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Updates the report with the new field and the title of the field.
        /// </summary>
        /// <remarks>
        /// New Field: The new field gets added to the ReportDetails section.
        /// Field title: If the report is grouped, the title goes in the "GroupHeader". If not, the title goes in the PageHeader section.
        /// </remarks>
        /// <returns></returns>
        private async Task UpdateReport()
        {
            await QueuedTask.Run(() =>
            {
                //report to update
                var reportToUpdate = _reportsInProject.FirstOrDefault(r => r.Name == ReportName);

                //Create field
                foreach (var field in _fieldsAddToReport)
                {
                    //Get the "ReportSectionElement"
                    var mainReportSection = reportToUpdate.Elements.OfType <ReportSectionElement>().FirstOrDefault();
                    if (mainReportSection == null)
                    {
                        return;
                    }

                    #region Field content
                    //Get the "ReportDetails" within the ReportSectionElement. ReportDetails is where "fields" are.
                    var reportDetailsSection = mainReportSection?.Elements.OfType <ReportDetails>().FirstOrDefault();
                    if (reportDetailsSection == null)
                    {
                        return;
                    }

                    //Within ReportDetails find the envelope that encloses a field.
                    //We get the first CIMParagraphTextGraphic in the collection so that we can add the new field next to it.
                    var lastFieldGraphic = reportDetailsSection.Elements.FirstOrDefault((r) =>
                    {
                        var gr = r as GraphicElement;
                        if (gr == null)
                        {
                            return(false);
                        }
                        return(gr.GetGraphic() is CIMParagraphTextGraphic ? true : false);
                    });
                    //Get the Envelope of the last field
                    var graphicBounds = lastFieldGraphic.GetBounds();

                    //Min and Max values of the envelope
                    var xMinOfFieldEnvelope = graphicBounds.XMin;
                    var yMinOfFieldEnvelope = graphicBounds.YMin;

                    var xMaxOfFieldEnvelope = graphicBounds.XMax;
                    var YMaxOfFieldEnvelope = graphicBounds.YMax;
                    //create the new Envelope to be offset from the existing field
                    MapPoint newMinPoint      = MapPointBuilder.CreateMapPoint(xMinOfFieldEnvelope + fieldIncrement, yMinOfFieldEnvelope);
                    MapPoint newMaxPoint      = MapPointBuilder.CreateMapPoint(xMaxOfFieldEnvelope + fieldIncrement, YMaxOfFieldEnvelope);
                    Envelope newFieldEnvelope = EnvelopeBuilder.CreateEnvelope(newMinPoint, newMaxPoint);
                    #endregion
                    //Create field
                    GraphicElement fieldGraphic = ReportElementFactory.Instance.CreateFieldValueTextElement(reportDetailsSection, newFieldEnvelope, field);

                    #region Field title
                    Envelope envelopeOfLastField = null;
                    ILayoutElementContainer reportsSection;
                    //Field title in Page Header.
                    //Get the Page header section
                    var pageHeaderSection = mainReportSection?.Elements.OfType <ReportPageHeader>();
                    //Check if there are any elements in the page header section. If there are none, the report is "Grouped"
                    if (pageHeaderSection.FirstOrDefault().Elements.Count() == 0)                     //Page header has no child elements. The report is grouped on a field.
                    {
                        //Get Group Header.
                        // the title needs to be in the GroupHeader section.
                        var reportGroupHeader = mainReportSection?.Elements.OfType <ReportGroupHeader>().FirstOrDefault();
                        //Get the paragraph text element (the last title)
                        var lastFieldGroupHeaderGraphic = reportGroupHeader.Elements.FirstOrDefault((h) =>
                        {
                            var graphic = h as GraphicElement;
                            if (graphic == null)
                            {
                                return(false);
                            }
                            return(graphic.GetGraphic() is CIMParagraphTextGraphic ? true : false);
                        });
                        //Get the Envelope of the last field header
                        envelopeOfLastField = lastFieldGroupHeaderGraphic?.GetBounds();
                        //The ILayoutElementContainer is the "GroupHeader". Needed for the CreateRectangleParagraphGraphicElement method
                        reportsSection = reportGroupHeader;
                    }
                    else                     //not grouped
                    {
                        //Get the "ReportPageHeader" within the ReportSectionElement. ReportPageHeader is where "fields titles" are.
                        var reportPageHeader = mainReportSection?.Elements.OfType <ReportPageHeader>().FirstOrDefault();
                        //Get the paragraph text element (the last title)
                        var lastFieldPageHeaderGraphic = reportPageHeader.Elements.FirstOrDefault((h) =>
                        {
                            var graphic = h as GraphicElement;
                            if (graphic == null)
                            {
                                return(false);
                            }
                            return(graphic.GetGraphic() is CIMParagraphTextGraphic ? true : false);
                        });
                        //Get the Envelope of the last field header
                        envelopeOfLastField = lastFieldPageHeaderGraphic?.GetBounds();
                        //The ILayoutElementContainer is the "PageHeader". Needed for the CreateRectangleParagraphGraphicElement method
                        reportsSection = reportPageHeader;
                    }

                    //Min and Max values of the envelope
                    var xMinOfHeaderFieldEnvelope = envelopeOfLastField.XMin;
                    var yMinOfHeaderFieldEnvelope = envelopeOfLastField.YMin;

                    var xMaxOfHeaderFieldEnvelope = envelopeOfLastField.XMax;
                    var YMaxOfHeaderFieldEnvelope = envelopeOfLastField.YMax;
                    //create the new Envelope to be offset from the existing field
                    MapPoint newHeaderMinPoint      = MapPointBuilder.CreateMapPoint(xMinOfHeaderFieldEnvelope + fieldIncrement, yMinOfHeaderFieldEnvelope);
                    MapPoint newHeaderMaxPoint      = MapPointBuilder.CreateMapPoint(xMaxOfHeaderFieldEnvelope + fieldIncrement, YMaxOfHeaderFieldEnvelope);
                    Envelope newHeaderFieldEnvelope = EnvelopeBuilder.CreateEnvelope(newHeaderMinPoint, newHeaderMaxPoint);
                    #endregion
                    //Create field header title
                    GraphicElement fieldHeaderGraphic = ReportElementFactory.Instance.CreateRectangleParagraphGraphicElement(reportsSection, newHeaderFieldEnvelope, field.Name);
                }
            });
        }
        internal async Task <string> AddGraphicToMap(Geometry geom, CIMColor color, bool IsTempGraphic = false, double size = 1.0, string text = "", SimpleMarkerStyle markerStyle = SimpleMarkerStyle.Circle, string tag = "")
        {
            if (geom == null || MapView.Active == null)
            {
                return(string.Empty);
            }

            CIMSymbolReference symbol = null;

            if (!string.IsNullOrWhiteSpace(text) && geom.GeometryType == GeometryType.Point)
            {
                await QueuedTask.Run(() =>
                {
                    // TODO add text graphic
                    //var tg = new CIMTextGraphic() { Placement = Anchor.CenterPoint, Text = text};
                });
            }
            else if (geom.GeometryType == GeometryType.Point)
            {
                await QueuedTask.Run(() =>
                {
                    var s  = SymbolFactory.Instance.ConstructPointSymbol(color, size, markerStyle);
                    symbol = new CIMSymbolReference()
                    {
                        Symbol = s
                    };
                });
            }
            else if (geom.GeometryType == GeometryType.Polyline)
            {
                await QueuedTask.Run(() =>
                {
                    var s  = SymbolFactory.Instance.ConstructLineSymbol(color, size);
                    symbol = new CIMSymbolReference()
                    {
                        Symbol = s
                    };
                });
            }
            else if (geom.GeometryType == GeometryType.Polygon)
            {
                await QueuedTask.Run(() =>
                {
                    var outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Solid);
                    var s       = SymbolFactory.Instance.ConstructPolygonSymbol(color, SimpleFillStyle.Solid, outline);
                    symbol      = new CIMSymbolReference()
                    {
                        Symbol = s
                    };
                });
            }

            var result = await QueuedTask.Run(() =>
            {
                var disposable = MapView.Active.AddOverlay(geom, symbol);
                var guid       = Guid.NewGuid().ToString();
                ProGraphicsList.Add(new ProGraphic(disposable, guid, geom, IsTempGraphic, tag));
                return(guid);
            });

            return(result);
        }
Exemplo n.º 30
0
 protected override void RunTask(QueuedTask queuedTask)
 {
     _log.Info($"Running task {queuedTask.Id}");
     if (queuedTask.GetType() == typeof(QueuedModuleTask))
     {
         RunModuleTask(queuedTask as QueuedModuleTask);
     }
     else
     {
         if (queuedTask.GetType() == typeof(QueuedInternalTask))
         {
             var task = (QueuedInternalTask)queuedTask;
             switch(task.TaskType)
             {
                 case InternalTaskType.PersistResults:
                     internalTaskPersistResults();
                     break;
                 case InternalTaskType.UploadResults:
                     internalTaskUploadResults();
                     break;
                 case InternalTaskType.SendHeartbeat:
                     internalTaskSendHeartbeat();
                     break;
                 default:
                 break;
             }
         }
     }
 }
Exemplo n.º 31
0
        private async Task SetupDefinitionAsync()
        {
            try
            {
                var lstDefinitions = await QueuedTask.Run <List <DatasetInfo> >(() =>
                {
                    List <DatasetInfo> definitions = new List <DatasetInfo>();
                    if (_datastore is Geodatabase)
                    {
                        var geodatabase = _datastore as Geodatabase;
                        switch (DatasetTypeCategory.DatasetType)
                        {
                        case DatasetType.Table:
                            definitions = geodatabase.GetDefinitions <TableDefinition>().Select(CreateDataSetInfo).ToList();
                            break;

                        case DatasetType.FeatureClass:
                            definitions = geodatabase.GetDefinitions <FeatureClassDefinition>().Select(CreateDataSetInfo).ToList();
                            break;

                        case DatasetType.FeatureDataset:
                            definitions = geodatabase.GetDefinitions <FeatureDatasetDefinition>().Select(CreateDataSetInfo).ToList();
                            break;

                        case DatasetType.RelationshipClass:
                            definitions = geodatabase.GetDefinitions <RelationshipClassDefinition>().Select(CreateDataSetInfo).ToList();
                            break;

                        case DatasetType.AttributedRelationshipClass:
                            definitions = geodatabase.GetDefinitions <AttributedRelationshipClassDefinition>().Select(CreateDataSetInfo).ToList();
                            break;
                        }
                    }
                    else if (_datastore is Database)
                    {
                        var database = _datastore as Database;
                        IReadOnlyList <string> tableNames = database.GetTableNames();
                        foreach (string tableName in tableNames)
                        {
                            QueryDescription queryDescription = database.GetQueryDescription(tableName);
                            TableDefinition tableDefinition   = database.GetDefinition(queryDescription);
                            if (DatasetTypeCategory.DatasetType == DatasetType.Table || DatasetTypeCategory.DatasetType == DatasetType.FeatureClass)
                            {
                                definitions.Add(new DatasetInfo
                                {
                                    Name = tableDefinition.GetName(),
                                    DatasetDefinition = tableDefinition
                                });
                            }
                        }
                    }
                    else if (_datastore is FileSystemDatastore)
                    {
                        var shapefile = _datastore as FileSystemDatastore;
                        FileSystemConnectionPath shapefileConnectionPath = (FileSystemConnectionPath)shapefile.GetConnector();
                        DirectoryInfo directoryInfo = new DirectoryInfo(shapefileConnectionPath.Path.LocalPath);

                        if (DatasetTypeCategory.DatasetType == DatasetType.FeatureClass)
                        {
                            FileInfo[] filesWithShpExtension = directoryInfo.GetFiles("*.shp");

                            foreach (FileInfo file in filesWithShpExtension)
                            {
                                definitions.Add(CreateDataSetInfo(shapefile.GetDefinition <FeatureClassDefinition>(file.Name)));
                            }
                        }
                        if (DatasetTypeCategory.DatasetType == DatasetType.Table)
                        {
                            FileInfo[] filesWithDbfExtension = directoryInfo.GetFiles("*.dbf");

                            foreach (FileInfo file in filesWithDbfExtension)
                            {
                                definitions.Add(CreateDataSetInfo(shapefile.GetDefinition <TableDefinition>(file.Name)));
                            }
                        }
                    }
                    return(definitions);
                });

                Datasets.Clear();
                Datasets.AddRange(lstDefinitions);
                DefinitionDetails.Clear();
            }
            catch (Exception exObj)
            {
                MessageBox.Show(exObj.Message, "Error");
            }
        }
        //
        // TODO ITEMS:
        //   * Need to change this to use HttpWebRequest, since I need to erad
        //     the result back and create a tweet out of it, and insert in DB.
        //
        //   * Report error to the user?   Perhaps have a priority flag
        //     (posts show dialog, btu starring does not?
        //
        // Runs on a thread from the threadpool.
        void PostTask(QueuedTask [] tasks)
        {
            var client = GetClient ();
            try {
                Util.PushNetworkActive ();
                foreach (var task in tasks){
                    Uri taskUri = new Uri (task.Url);
                    client.Headers [HttpRequestHeader.Authorization] = OAuthAuthorizer.AuthorizeRequest (OAuthConfig, OAuthToken, OAuthTokenSecret, "POST", taskUri, task.PostData);
                    try {
                        client.UploadData (taskUri, "POST", Encoding.UTF8.GetBytes (task.PostData));
                    } catch (Exception){
                        // Can happen if we had already favorited this status
                    }

                    lock (Database.Main)
                        Database.Main.Execute ("DELETE FROM QueuedTask WHERE TaskId = ?", task.TaskId);
                }
            } catch (Exception e) {
                Console.WriteLine (e);
            } finally {
                Util.PopNetworkActive ();
            }
        }
Exemplo n.º 33
0
        public async void SearchAndSubscribeToStreamData()
        {
            Map         map         = MapView.Active.Map;
            StreamLayer streamLayer = null;
            QueryFilter qfilter     = null;

            #region Search And Subscribe for Streaming Data

            await QueuedTask.Run(async() =>
            {
                //query filter can be null to search and retrieve all rows
                //true means recycling cursor
                using (var rc = streamLayer.SearchAndSubscribe(qfilter, true))
                {
                    //waiting for new features to be streamed
                    //default is no cancellation
                    while (await rc.WaitForRowsAsync())
                    {
                        while (rc.MoveNext())
                        {
                            using (var row = rc.Current)
                            {
                                //determine the origin of the row event
                                switch (row.GetRowSource())
                                {
                                case RealtimeRowSource.PreExisting:
                                    //pre-existing row at the time of subscribe
                                    continue;

                                case RealtimeRowSource.EventInsert:
                                    //row was inserted after subscribe
                                    continue;

                                case RealtimeRowSource.EventDelete:
                                    //row was deleted after subscribe
                                    continue;
                                }
                            }
                        }
                    }
                }//row cursor is disposed. row cursor is unsubscribed

                //....or....
                //Use the feature class instead of the layer
                using (var rfc = streamLayer.GetFeatureClass())
                {
                    //non-recycling cursor - 2nd param "false"
                    using (var rc = rfc.SearchAndSubscribe(qfilter, false))
                    {
                        //waiting for new features to be streamed
                        //default is no cancellation
                        while (await rc.WaitForRowsAsync())
                        {
                            //etc
                        }
                    }
                }
            });

            #endregion

            #region Search And Subscribe With Cancellation

            await QueuedTask.Run(async() =>
            {
                //Recycling cursor - 2nd param "true"
                //or streamLayer.Subscribe(qfilter, true) to just subscribe
                using (var rc = streamLayer.SearchAndSubscribe(qfilter, true))
                {
                    //auto-cancel after 20 seconds
                    var cancel = new CancellationTokenSource(new TimeSpan(0, 0, 20));
                    //catch TaskCanceledException
                    try
                    {
                        while (await rc.WaitForRowsAsync(cancel.Token))
                        {
                            //check for row events
                            while (rc.MoveNext())
                            {
                                using (var row = rc.Current)
                                {
                                    //etc
                                }
                            }
                        }
                    }
                    catch (TaskCanceledException tce)
                    {
                        //Handle cancellation as needed
                    }
                    cancel.Dispose();
                }
            });

            #endregion
        }