Наследование: MonoBehaviour
        protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry)
        {
            //Check we only have one feature to extend to
            if (MapView.Active.Map.SelectionCount != 1)
            {
                MessageBox.Show("Please select one polyline or polygon feature to extend to", "Extend");
                return Task.FromResult(true);
            }

            //Run on MCT
            return QueuedTask.Run(() =>
            {
                //get selected feature geometry
                var selectedFeatures = MapView.Active.Map.GetSelection();
                var insp = new Inspector();
                insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First());
                var selGeom = insp.Shape;
                if (!(selGeom.GeometryType == GeometryType.Polygon
                    || selGeom.GeometryType == GeometryType.Polyline))
                {
                    MessageBox.Show("Please choose as the selected feature either a polyline or polygon feature to extend to");
                    return false;
                }

                //find feature at the click
                var clickFeatures = MapView.Active.GetFeatures(geometry);
                insp.Load(clickFeatures.First().Key, clickFeatures.First().Value);
                var clickGeom = insp.Shape as Polyline;
                if (clickGeom == null)
                {
                    MessageBox.Show("Please select a polyline feature to extend");
                    return false;
                }

                //extend the line to the poly?
                ArcGIS.Core.Geometry.Polyline extPolyline;
                extPolyline = GeometryEngine.Extend(clickGeom, (selGeom.GeometryType == GeometryType.Polygon ? GeometryEngine.Boundary(selGeom) as Polyline : selGeom as Polyline), ExtendFlags.Default);
                if (extPolyline == null)
                {
                    MessageBox.Show(string.Format("Unable to extend the clicked {0} to the selected {1}",
                        clickGeom.GeometryType, selGeom.GeometryType));
                    return false;
                }

                //set the new geometry back on the feature
                insp.Shape = extPolyline;

                //create and execute the edit operation
                var op = new EditOperation();
                op.Name = "Extend";
                op.SelectModifiedFeatures = false;
                op.SelectNewFeatures = false;
                op.Modify(insp);
                return op.Execute();
            });
        }
    public void Dispose ()
    {
      _appointment.AfterWrite -= Appointment_AfterWrite;
      _appointment.BeforeDelete -= Appointment_BeforeDelete;
      ((InspectorEvents_10_Event) _inspector).Close -= AppointmentItemWrapper_Close;

      _appointment = null;
      _inspector = null;
    }
Пример #3
0
    public SMTLibProcess(ProcessStartInfo psi, SMTLibProverOptions options)
    {
      this.options = options;
      this.smtProcessId = smtProcessIdSeq++;

      if (options.Inspector != null) {
        this.inspector = new Inspector(options);
      }

      foreach (var arg in options.SolverArguments)
        psi.Arguments += " " + arg;

      if (cancelEvent == null && CommandLineOptions.Clo.RunningBoogieFromCommandLine) {
        cancelEvent = new ConsoleCancelEventHandler(ControlCHandler);
        Console.CancelKeyPress += cancelEvent;
      }

      if (options.Verbosity >= 1) {
        Console.WriteLine("[SMT-{0}] Starting {1} {2}", smtProcessId, psi.FileName, psi.Arguments);
      }


      try {
        prover = new Process();
        prover.StartInfo = psi;        
        prover.ErrorDataReceived += prover_ErrorDataReceived;
        prover.OutputDataReceived += prover_OutputDataReceived;
        prover.Start();
        toProver = prover.StandardInput;
        prover.BeginErrorReadLine();
        prover.BeginOutputReadLine();        
      } catch (System.ComponentModel.Win32Exception e) {
        throw new ProverException(string.Format("Unable to start the process {0}: {1}", psi.FileName, e.Message));
      }
    }
Пример #4
0
		protected virtual void Dispose(bool isDisposing)
		{
			Logger.LogInfo("EMAILTRACKING: Disposing Mail Selection - " + isDisposing);
			if (isDisposing)
			{
				GC.SuppressFinalize(this);
            }

            if (_inspector != null)
                Marshal.ReleaseComObject(_inspector);

            if (_explorer != null)
                Marshal.ReleaseComObject(_explorer);

            if (_ns != null)
                Marshal.ReleaseComObject(_ns);

            if (_outlookApplication != null)
                Marshal.ReleaseComObject(_outlookApplication);

            _inspector = null;
			_explorer = null;
			_ns = null;
            _outlookApplication = null;
		}
        /// <summary>
        /// Converts the specified inspector.
        /// </summary>
        /// <param name="inspector">The inspector.</param>
        /// <returns></returns>
        public static OutlookRibbonType Convert(Inspector inspector)
        {
            object item = inspector.CurrentItem;
            var type = item.GetType();

            var messageClass = (string)type.InvokeMember(
                "MessageClass",
                BindingFlags.GetProperty,
                null, item, null);

            if (messageClass.StartsWith("IPM.Appointment"))
                return OutlookRibbonType.OutlookAppointment;
            if (messageClass.StartsWith("IPM.Contact"))
                return OutlookRibbonType.OutlookContact;
            if (messageClass.StartsWith("IPM.Activity"))
                return OutlookRibbonType.OutlookJournal;
            if (messageClass.StartsWith("IPM.Note"))
                return ConvertMail(item);
            if (messageClass.StartsWith("IPM.Schedule.Meeting"))
                return ConvertMeeting(item);
            if (messageClass.StartsWith("IPM.Post"))
                return ConvertPost(item);
            if (messageClass.StartsWith("IPM.Task"))
                return OutlookRibbonType.OutlookTask;
            if (messageClass.StartsWith("IPM.OLE.CLASS"))
                return OutlookRibbonType.OutlookAppointment;

            throw new ArgumentOutOfRangeException(string.Format("MessageClass {0} is unrecognised", messageClass));
        }
Пример #6
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (username_box.Text.Trim().Count() == 0 || name_box.Text.Trim().Count() == 0 || familiy_box.Text.Trim().Count() == 0 || accessLevel.SelectedItem == null)
     {
         MessageBox.Show(new IncompleteFormException().Message);
     }
     User user = UserStorage.getInstance().all().Find(x => x.Username.Equals(username_box.Text));
     if (user != null)
     {
         MessageBox.Show(new UserExistsException().Message);
     }
     else
     {
         String alevel = accessLevel.SelectedText;
         AccessLevel access_Level = null;
         if (alevel.Equals("کاربر میانی"))
         {
             access_Level = new Manager();
         }
         else if (alevel.Equals("کاربر ارشد"))
         {
             access_Level = new HeadManager();
         }
         else
         {
             access_Level = new Inspector();
         }
         User new_user = new User(name_box.Text, familiy_box.Text, username_box.Text, access_Level);
         UserStorage.getInstance().create(new_user);
         this.Close();
     }
 }
    protected override void OnClick()
    {
      //get the screen location of the right click
      var cmdc = (System.Windows.Point)FrameworkApplication.ContextMenuDataContext;

      QueuedTask.Run(async() =>
        {
          var mapPoint = MapView.Active.ScreenToMap(cmdc);
          
          //create search polygon at 5 pixels
          var searchPoly = CreateSearchPolygon(mapPoint, 5);

          //find features under the search geometry
          var searchFeatures = MapView.Active.GetFeatures(searchPoly);

          //get the sketch geometry
          var sketchGeom = await MapView.Active.GetCurrentSketchAsync();

          //loop through underlying features for the first one that matches sketch geometry type
          foreach (var layer in searchFeatures.Keys)
          {
            //load the first feature into the inspector
            var insp = new Inspector();
            insp.Load(layer, searchFeatures[layer].First());

            if (sketchGeom.GeometryType == insp.Shape.GeometryType)
            {
              await MapView.Active.SetCurrentSketchAsync(insp.Shape);
              break;
            }
          }
        });
    }
    protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry)
    {
      //Simple check for selected layer
      if (MapView.Active.GetSelectedLayers().Count == 0)
      {
        MessageBox.Show("Please select a layer in the toc","Update attributes with sketch");
        return Task.FromResult(true);
      }

      //Run on MCT
      return QueuedTask.Run(() =>
      {
        //Get the selected layer in toc
        var featLayer = MapView.Active.GetSelectedLayers().First() as FeatureLayer;

        //find feature oids under the sketch for the selected layer
        var features = MapView.Active.GetFeatures(geometry);
        var featOids = features[featLayer];

        //update the attributes of those features
        var insp = new Inspector();
        insp.Load(featLayer, featOids);
        insp["PARCEL_ID"] = 42;

        //create and execute the edit operation
        var op = new EditOperation();
        op.Name = "Update parcel";
        op.SelectModifiedFeatures = true;
        op.SelectNewFeatures = false;
        op.Modify(insp);
        return op.Execute();
      });
    }
Пример #9
0
 private void NewInspector(Inspector Inspector)
 {
     if (Inspector.CurrentItem is MailItem)
     {
         InspectorWrappers.Add(Inspector, new InspectorWrapper(Inspector));
     }
 }
Пример #10
0
 private void OnNewInspector(Inspector Inspector)
 {
     var wsInspector = new WsInspector(Inspector);
     wsInspector.Activated += id => Activated(id);
     _wsInspectors.Add(wsInspector);
     if (NewInspector != null)
         NewInspector(wsInspector);
 }
Пример #11
0
		public MailSelection()
		{
            _outlookApplication = new Application();
            _ns = _outlookApplication.GetNamespace("MAPI");
            _inspector = _outlookApplication.ActiveInspector();
            _explorer = _outlookApplication.ActiveExplorer();
			Logger.LogInfo("EMAILTRACKING: Initialised Mail Selection");
		}
 void Start()
 {
     inspector = GameObject.Find ("Inspector").GetComponent ("Inspector") as Inspector;
     objectList = GameObject.Find ("ObjectList").GetComponent ("ObjectList") as ObjectList;
     parameterList = GameObject.Find ("ParameterList").GetComponent ("ParameterList") as ParameterList;
     startPosition = transform.position;
     startRotation = transform.eulerAngles;
 }
Пример #13
0
 public InspWrap(Inspector insp)
 {
     if (insp == null)
     {
         return;
     }
     Key = Guid.NewGuid().ToString();
     Inspector = insp;
 }
Пример #14
0
        public InspectorWrapper(Inspector Inspector)
        {
            inspector = Inspector;
            ((InspectorEvents_Event)inspector).Close += InspectorWrapper_Close;

            taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(new TaskPaneControl("Inspector", _count++), "My task pane", inspector);
            taskPane.VisibleChanged += TaskPane_VisibleChanged;
            taskPane.Visible = true;
        }
    public AppointmentItemAdapter (Inspector inspector, AppointmentItem appointment)
    {
      _appointment = appointment;
      _inspector = inspector;

      _appointment.AfterWrite += Appointment_AfterWrite;
      _appointment.BeforeDelete += Appointment_BeforeDelete;
      ((InspectorEvents_10_Event) _inspector).Close += AppointmentItemWrapper_Close;
    }
Пример #16
0
 private void ToggleInspector(RibbonToggleButton button, Inspector inspector)
 {
     if (inspector == null) return;
     var inspectorWrapper = Globals.ThisAddIn.InspectorWrappers[inspector];
     CustomTaskPane taskPane = inspectorWrapper.CustomTaskPane;
     if (taskPane != null)
     {
         taskPane.Visible = button.Checked;
     }
 }
Пример #17
0
        private void InspectorClose()
        {
            ((InspectorEvents_10_Event)Inspector).Close -= InspectorClose;

            var handler = Closed;
            if (handler != null)
                Closed(this, new InspectorClosedEventArgs(Inspector, CurrentContext));

            Inspector = null;
        }
Пример #18
0
        void NewInspector(Inspector inspector)
        {
            var wrapper = new InspectorWrapper(inspector);
            wrapper.Closed += InspectorClosed;

            var ribbonType = InspectorToRibbonTypeConverter.Convert(inspector);
            var newViewEventArgs = new NewViewEventArgs(inspector, wrapper.CurrentContext, ribbonType.GetEnumDescription());
            NewView(this, newViewEventArgs);

            if (!newViewEventArgs.Handled)
                inspector.ReleaseComObject();
        }
Пример #19
0
        public InspectorWrapper(Inspector inspector)
        {
            this.inspector = inspector;
            TheActivateHandler = new InspectorEvents_ActivateEventHandler(activateHandler);
            ((Microsoft.Office.Interop.Outlook.InspectorEvents_Event)this.inspector).Activate += TheActivateHandler;

            if (this.inspector.CurrentItem is AppointmentItem)
            {
                AppointmentItem theItem = this.inspector.CurrentItem as AppointmentItem;
                ((Microsoft.Office.Interop.Outlook.ItemEvents_10_Event)theItem).Send += sendHander;
            }

            InitializeInspector();
        }
Пример #20
0
        private void InspectorWrapper_Close()
        {
            if (taskPane != null)
            {
                Globals.ThisAddIn.CustomTaskPanes.Remove(taskPane);
            }

            taskPane = null;
            Globals.ThisAddIn.InspectorWrappers.Remove(inspector);

            ((InspectorEvents_Event)inspector).Close -= InspectorWrapper_Close;

            inspector = null;
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeSchema"/> class.
        /// </summary>
        /// <param name="inspector">
        /// The inspector.
        /// </param>
        /// <param name="handlePropertyIgnore">
        /// The handle property ignore.
        /// </param>
        internal TypeSchema(Inspector inspector, bool handlePropertyIgnore)
        {
            var properties = new List<TypeSchemaProperty>(inspector.Properties.Count);
            foreach (var property in inspector.Properties.Where(property => !handlePropertyIgnore || !property.Ignore))
            {
                var typeSchemaProperty = new TypeSchemaProperty();
                typeSchemaProperty.PropertyName = property.Name;
                typeSchemaProperty.InspectedProperty = property;
                Encoder.TryGetEncoder(property.PropertyType, out typeSchemaProperty.EncoderInfo);
                properties.Add(typeSchemaProperty);
            }

            this.typeSchemaProperties = properties.ToArray();
            this.writeObject = TypeSchema.CompileWriteObjectDelegate(this.typeSchemaProperties);
            this.serializedSchema = new Lazy<byte[]>(() => this.GetSerializedSchema());
        }
 private void Inspectors_NewInspector (Inspector inspector)
 {
   try
   {
     var item = TryCreateItem (inspector);
     if (item != null)
     {
       _isChangedByItem.Add (item, false);
       item.Closed += Item_Closed;
       item.SavedOrDeleted += Item_SavedOrDeleted;
     }
   }
   catch (Exception x)
   {
     ExceptionHandler.Instance.LogException (x, s_logger);
   }
 }
Пример #23
0
        public static void Main(string[] args)
        {
            var thread = new Thread (() => {
                var listener = new TcpListener (IPAddress.Any, 8888);
                listener.Start ();

                while (true) {
                    var socket = listener.AcceptSocket ();
                    var stream = new NetworkStream (socket);
                    var inspector = new Inspector (stream);
                    var history = new History (inspector);

                    InspectorModel.Inspector = inspector;
                    HistoryModel.History = history;

                    inspector.Run ();
                }
            });

            thread.Start ();

            using (var nancyHost = new NancyHost (new Uri ("http://127.0.0.1:8080/"), new Uri ("http://localhost:8080/"))) {
                StaticConfiguration.DisableErrorTraces = false;
                StaticConfiguration.Caching.EnableRuntimeViewUpdates = true;

                nancyHost.Start ();

                Console.WriteLine ("Nancy now listening - navigating to http://127.0.0.1:8080/. Press key to stop");

                while (true) {
                    if (Console.ReadKey ().Key == ConsoleKey.Enter) {
                        break;
                    }

                    Thread.Sleep (100);
                }
            }
        }
Пример #24
0
        public override void onInspect(int itemOrObjectId)
        {
            Inspector Inspector = "Inspector";

            Inspector.inspect(itemOrObjectId);
        }
Пример #25
0
        /*
         * Draws the scene view helpers for IKSolverTrigonometric
         * */
        public static void AddScene(IKSolverLeg solver, Color color, bool modifiable)
        {
            if (Application.isPlaying && !solver.initiated)
            {
                return;
            }
            if (!Application.isPlaying && !solver.IsValid())
            {
                return;
            }

            //float length = Vector3.Distance(solver.bone1.transform.position, solver.bone2.transform.position) + Vector3.Distance(solver.bone2.transform.position, solver.bone3.transform.position);
            //float size = length * 0.05f;

            Handles.color = color;
            GUI.color     = color;

            // Chain lines
            Handles.DrawLine(solver.pelvis.transform.position, solver.thigh.transform.position);
            Handles.DrawLine(solver.thigh.transform.position, solver.calf.transform.position);
            Handles.DrawLine(solver.calf.transform.position, solver.foot.transform.position);
            Handles.DrawLine(solver.foot.transform.position, solver.toe.transform.position);

            // Joints
            Inspector.SphereCap(0, solver.pelvis.transform.position, Quaternion.identity, GetHandleSize(solver.pelvis.transform.position));
            Inspector.SphereCap(0, solver.thigh.transform.position, Quaternion.identity, GetHandleSize(solver.thigh.transform.position));
            Inspector.SphereCap(0, solver.calf.transform.position, Quaternion.identity, GetHandleSize(solver.calf.transform.position));
            Inspector.SphereCap(0, solver.foot.transform.position, Quaternion.identity, GetHandleSize(solver.foot.transform.position));
            Inspector.SphereCap(0, solver.toe.transform.position, Quaternion.identity, GetHandleSize(solver.toe.transform.position));

            if (Application.isPlaying && (solver.IKPositionWeight > 0 || solver.IKRotationWeight > 0))
            {
                if (modifiable)
                {
                    Inspector.CubeCap(0, solver.IKPosition, solver.IKRotation, GetHandleSize(solver.IKPosition));

                    // Manipulating position and rotation
                    switch (Tools.current)
                    {
                    case Tool.Move:
                        if (solver.leg.target == null)
                        {
                            solver.IKPosition = Handles.PositionHandle(solver.IKPosition, Quaternion.identity);
                        }
                        break;

                    case Tool.Rotate:
                        if (solver.leg.target == null)
                        {
                            solver.IKRotation = Handles.RotationHandle(solver.IKRotation, solver.IKPosition);
                        }
                        break;
                    }
                }

                // Target
                Handles.color = new Color(color.r, color.g, color.b, color.a * Mathf.Max(solver.IKPositionWeight, solver.IKRotationWeight));
                Handles.DrawLine(solver.toe.transform.position, solver.IKPosition);
            }

            Handles.color = Color.white;
            GUI.color     = Color.white;
        }
Пример #26
0
        public void OnSceneGUI()
        {
            GUI.changed = false;

            // Set defaultLocalRotation so that the initial local rotation will be the zero point for the rotation limit
            if (!Application.isPlaying)
            {
                script.defaultLocalRotation = script.transform.localRotation;
            }
            if (script.axis == Vector3.zero)
            {
                return;
            }

            // Quick Editing Tools
            Handles.BeginGUI();
            GUILayout.BeginArea(new Rect(10, Screen.height - 180, 550, 130), "Rotation Limit Polygonal", "Window");

            // Cloning values from another RotationLimitPolygonal
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Clone From", "Make this rotation limit identical to another", script, GUILayout.Width(220)))
            {
                CloneLimit();
            }
            clone = (RotationLimitPolygonal)EditorGUILayout.ObjectField("", clone, typeof(RotationLimitPolygonal), true);
            EditorGUILayout.EndHorizontal();

            // Symmetry
            symmetry = (Symmetry)EditorGUILayout.EnumPopup("Symmetry", symmetry, GUILayout.Width(220));

            // Flipping
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Flip X", "Flip points along local X axis", script, GUILayout.Width(100)))
            {
                FlipLimit(0);
            }
            if (Inspector.Button("Flip Y", "Flip points along local Y axis", script, GUILayout.Width(100)))
            {
                FlipLimit(1);
            }
            if (Inspector.Button("Flip Z", "Flip points along local Z axis", script, GUILayout.Width(100)))
            {
                FlipLimit(2);
            }
            GUILayout.Label("Flip everything along axis");
            EditorGUILayout.EndHorizontal();

            // Rotating
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Rotate X", "Rotate points along X axis by Degrees", script, GUILayout.Width(100)))
            {
                RotatePoints(degrees, Vector3.right);
            }
            if (Inspector.Button("Rotate Y", "Rotate points along Y axis by Degrees", script, GUILayout.Width(100)))
            {
                RotatePoints(degrees, Vector3.up);
            }
            if (Inspector.Button("Rotate Z", "Rotate points along Z axis by Degrees", script, GUILayout.Width(100)))
            {
                RotatePoints(degrees, Vector3.forward);
            }

            degrees = EditorGUILayout.FloatField("Degrees", degrees, GUILayout.Width(200));
            EditorGUILayout.EndHorizontal();

            // Smooth/Optimize
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Smooth", "Double the points", script))
            {
                Smooth();
            }
            if (Inspector.Button("Optimize", "Delete every second point", script))
            {
                Optimize();
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.EndArea();
            Handles.EndGUI();

            // Rebuild reach cones
            script.BuildReachCones();

            // Draw a white transparent sphere
            DrawRotationSphere(script.transform.position);

            // Draw Axis
            DrawArrow(script.transform.position, Direction(script.axis), colorDefault, "Axis", 0.02f);

            // Display limit points
            for (int i = 0; i < script.points.Length; i++)
            {
                Color color = GetColor(i);                 // Paint the point in green or red if it belongs to an invalid reach cone

                Handles.color = color;
                GUI.color     = color;

                // Line from the center to the point and the label
                Handles.DrawLine(script.transform.position, script.transform.position + Direction(script.points[i].point));
                Handles.Label(script.transform.position + Direction(script.points[i].point + new Vector3(-0.02f, 0, 0)), " " + i.ToString());

                // Selecting points
                Handles.color = colorHandles;
                if (Handles.Button(script.transform.position + Direction(script.points[i].point), script.transform.rotation, 0.02f, 0.02f, Handles.DotCap))
                {
                    selectedPoint = i;
                }

                Handles.color = Color.white;
                GUI.color     = Color.white;

                // Limit point GUI
                if (i == selectedPoint)
                {
                    Handles.BeginGUI();

                    GUILayout.BeginArea(new Rect(Screen.width - 240, Screen.height - 180, 230, 130), "Limit Point " + i.ToString(), "Window");

                    if (Inspector.Button("Delete", "Delete this point", script))
                    {
                        if (script.points.Length > 3)
                        {
                            // Using the deletePoint index here because we dont want to delete points from the array that we are iterating
                            deletePoint = i;
                        }
                        else if (!Warning.logged)
                        {
                            script.LogWarning("Polygonal Rotation Limit should have at least 3 limit points");
                        }
                    }
                    if (Inspector.Button("Add Point", "Add a new point next to this one", script))
                    {
                        addPoint = i;
                    }

                    // Store point for undo
                    Vector3 oldPoint = script.points[i].point;

                    // Manual input for the point position
                    Inspector.AddVector3(ref script.points[i].point, "Point", script, GUILayout.Width(210));

                    EditorGUILayout.Space();

                    // Tangent weight
                    Inspector.AddFloat(ref script.points[i].tangentWeight, "Tangent Weight", "Weight of this point's tangent. Used in smoothing.", script, -Mathf.Infinity, Mathf.Infinity, GUILayout.Width(150));

                    GUILayout.EndArea();

                    Handles.EndGUI();

                    // Moving Points
                    Vector3 pointWorld = Handles.PositionHandle(script.transform.position + Direction(script.points[i].point), Quaternion.identity);
                    Vector3 newPoint   = InverseDirection(pointWorld - script.transform.position);
                    if (newPoint != script.points[i].point)
                    {
                        if (!Application.isPlaying)
                        {
                            Undo.RecordObject(script, "Move Limit Point");
                        }
                        script.points[i].point = newPoint;
                    }

                    // Symmetry
                    if (symmetry != Symmetry.Off && script.points.Length > 3 && oldPoint != script.points[i].point)
                    {
                        RotationLimitPolygonal.LimitPoint symmetryPoint = GetClosestPoint(Symmetrize(oldPoint, symmetry));
                        if (symmetryPoint != script.points[i])
                        {
                            symmetryPoint.point = Symmetrize(script.points[i].point, symmetry);
                        }
                    }
                }

                // Normalize the point
                script.points[i].point = script.points[i].point.normalized;
            }

            // Display smoothed polygon
            for (int i = 0; i < script.P.Length; i++)
            {
                Color color = GetColor(i);

                // Smoothed triangles are transparent
                Handles.color = new Color(color.r, color.g, color.b, 0.25f);
                Handles.DrawLine(script.transform.position, script.transform.position + Direction(script.P[i]));

                Handles.color = color;

                if (i < script.P.Length - 1)
                {
                    Handles.DrawLine(script.transform.position + Direction(script.P[i]), script.transform.position + Direction(script.P[i + 1]));
                }
                else
                {
                    Handles.DrawLine(script.transform.position + Direction(script.P[i]), script.transform.position + Direction(script.P[0]));
                }

                Handles.color = Color.white;
            }

            // Deleting points
            if (deletePoint != -1)
            {
                DeletePoint(deletePoint);
                selectedPoint = -1;
                deletePoint   = -1;
            }

            // Adding points
            if (addPoint != -1)
            {
                AddPoint(addPoint);
                addPoint = -1;
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(script);
            }
        }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the edit 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 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;
                var insp = new Inspector();
                foreach (var annoLayer in features.Keys.OfType <AnnotationLayer>())
                {
                    // are there features?
                    var featOids = features[annoLayer];
                    if (featOids.Count == 0)
                    {
                        continue;
                    }

                    // for each feature
                    foreach (var oid in featOids)
                    {
                        // load an inspector
                        insp.Load(annoLayer, oid);

                        // get the annotation properties
                        var annoProperties = insp.GetAnnotationProperties();

                        // get the text graphic
                        var cimTextGraphic = annoProperties.TextGraphic;
                        if (cimTextGraphic != null)
                        {
                            //
                            // add a leader point to the text graphic
                            //

                            // get the feature shape
                            var textExtent = insp.Shape;

                            // find the lower left of the text extent
                            var extent = textExtent.Extent;
                            var lowerLeft = MapPointBuilder.CreateMapPoint(extent.XMin, extent.YMin, textExtent.SpatialReference);
                            // move it a little to the left and down
                            var newPoint = GeometryEngine.Instance.Move(lowerLeft, -40, -40);

                            // create a leader point
                            CIMLeaderPoint leaderPt = new CIMLeaderPoint();
                            leaderPt.Point = newPoint as MapPoint;

                            // add to a list
                            List <CIMLeader> leaderArray = new List <CIMLeader>();
                            leaderArray.Add(leaderPt);

                            // assign to the textGraphic
                            cimTextGraphic.Leaders = leaderArray.ToArray();


                            //
                            // add the balloon callout
                            //

                            // create the callout
                            CIMBalloonCallout balloon = new CIMBalloonCallout();
                            // yellow background
                            balloon.BackgroundSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.CreateRGBColor(255, 255, 0));
                            // set the balloon style
                            balloon.BalloonStyle = BalloonCalloutStyle.RoundedRectangle;
                            // add a text margin
                            CIMTextMargin textMargin = new CIMTextMargin()
                            {
                                Left = 4, Right = 4, Bottom = 4, Top = 4
                            };
                            balloon.Margin = textMargin;

                            // asign it to the textSymbol
                            var symbol = cimTextGraphic.Symbol.Symbol;
                            var textSymbol = symbol as CIMTextSymbol;

                            textSymbol.Callout = balloon;

                            // assign the text graphic back to the annotation properties
                            annoProperties.LoadFromTextGraphic(cimTextGraphic);

                            // assign the annotation properties back to the inspector
                            insp.SetAnnotationProperties(annoProperties);
                        }

                        // create the edit operation
                        if (op == null)
                        {
                            op = new EditOperation();
                            op.Name = "Alter symbol to balloon callout";
                            op.SelectModifiedFeatures = true;
                            op.SelectNewFeatures = false;
                        }

                        // modify the feature
                        op.Modify(insp);
                    }
                }

                if ((op != null) && !op.IsEmpty)
                {
                    bool result = op.Execute();
                    return result;
                }
                return
                false;
            }));
        }
Пример #28
0
        public void EditQANoteFieldValue(string NoteValue)
        {
            try
            {
                // Update value of EditNoteComboBox
                var qaFieldValue = QAFieldComboBox.Text;
                if (qaFieldValue == null || qaFieldValue == "")
                {
                    MessageBox.Show("Choose a note field to store the update.", "Note Field Required");
                    return;
                }

                QueuedTask.Run(() =>
                {
                    if (NoteValue == "QANoteCombo")
                    {
                        // Update value of EditNoteComboBox
                        var qaNoteValue = EditNoteComboBox.Text;
                        if (qaNoteValue == "Load or add...")
                        {
                            return;
                        }
                        if (qaNoteValue == null)
                        {
                            NoteValue = "";
                        }
                        else
                        {
                            NoteValue = qaNoteValue.ToString();
                        }
                    }

                    // Get the chosen QA field and set the selected records to the NoteValue
                    // if selection is empty, present error dialog box
                    var LayerName       = LayerComboBox.Text;
                    var QANoteFieldName = QAFieldComboBox.Text;
                    // Get all the fields from the selected item in LayerComboBox
                    // Get the layer in the ComboBox selection
                    var QALayer = MapView.Active.Map.FindLayers(LayerName).FirstOrDefault() as FeatureLayer;
                    if (QALayer == null)
                    {
                        return;
                    }

                    // check to make sure that the QA note field exists
                    string QAfieldname = QAFieldComboBox.Text.ToString();
                    if (QAfieldname == "Choose...")
                    {
                        MessageBox.Show("Choose a valid note field.", "Choose Note Field");
                        return;
                    }
                    // check if field exists
                    int qaFieldIndex = QALayer.GetTable().GetDefinition().FindField(QAfieldname);
                    if (qaFieldIndex == -1)                     // field not found
                    {
                        MessageBox.Show("The field: " + QAfieldname + ", does not exist. Update your note field choice.", "Error");
                        QAFieldComboBox.Text = "Choose...";
                        return;
                    }

                    // Get the selection
                    Selection QASelection = QALayer.GetSelection();
                    var selectionSet      = QASelection.GetObjectIDs();
                    if (QASelection.GetCount() == 0)
                    {
                        MessageBox.Show("No selection available for operation.", "Edit Note");
                        return;
                    }
                    // 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(QALayer, selectionSet);
                    inspector[QANoteFieldName] = NoteValue;
                    // apply the changes as an edit operation
                    var editOp  = new EditOperation();
                    editOp.Name = "Edit: " + NoteValue;
                    editOp.Modify(inspector);
                    bool result = editOp.Execute();
                    if (!result)
                    {
                        MessageBox.Show("Operation was not added to undo stack.");
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in EditQANoteFieldValue:  " + ex.ToString(), "Error");
            }
        }
Пример #29
0
 public InspectorViewModel(Inspector elem)
 {
     this.elem = elem;
 }
Пример #30
0
 internal override void Inspect(Inspector Inspector)
 {
     Inspector.InspectNewobj(this);
 }
Пример #31
0
 internal void AddWrapper(Inspector inspector)
 {
     const string SOURCE = CLASS_NAME + "AddWrapper";
     dynamic currentItem = null;
     try
     {
         currentItem = inspector.CurrentItem;
         if (!(currentItem is MailItem)) return;
         if (currentItem.Sent) return;
         Logger.Verbose(SOURCE, "creating new wrapper");
         var wrapper = new InspWrap(inspector);
         //don't know how this could happen, but just in case
         if (_inspWrappers.ContainsKey(wrapper.Key))
         {
             _inspWrappers.Remove(wrapper.Key);
         }
         //is this a forward or reply?
         var item = (MailItem)currentItem;
         if (!item.Sent && !string.IsNullOrEmpty(item.ConversationIndex) &&
             item.ConversationIndex.Length > 44)
         {
             //find the parent
             var parent = FindParentByConversation(item);
             if (parent == null)
             {
                 Logger.Error(SOURCE, string.Format(
                     "failed to retrieve parent message for reply/forward {0}; unable to check for ECS-enabled content",
                     item.Subject));
             }
             else
             {
                 Logger.Verbose(SOURCE, string.Format(
                     "found parent {0} for reply/forward",
                     parent.Subject));
                 if (Utils.HasChiaraHeader(parent))
                     HandleReplyForward(parent, item, ref wrapper);
             }
         }
         Logger.Verbose(SOURCE, "adding wrapper to collection with key " + wrapper.Key);
         _inspWrappers.Add(wrapper.Key, wrapper);
         ResetInspButtons();
     }
     catch (Exception ex)
     {
         Logger.Error(SOURCE, ex.ToString());
     }
     finally
     {
         if (currentItem != null)
         {
             Marshal.ReleaseComObject(currentItem);
             GC.Collect();
             GC.WaitForPendingFinalizers();
             GC.Collect();
         }
     }
 }
Пример #32
0
 // Use this for initialization
 void Start()
 {
     instance = this;
 }
Пример #33
0
 private bool OnValueSubmitted(BoundInputField source, string input)
 {
     Inspector.RefreshDelayed();
     return(OnValueChanged(source, input));
 }
Пример #34
0
 internal override void Inspect(Inspector Inspector)
 {
     Inspector.InspectStIndR8(this);
 }
        void OnSceneGUI()
        {
            GUI.changed = false;
            // Get the keyframes of the AnimationCurve to be manipulated
            Keyframe[] keys = script.spline.keys;

            // Set defaultLocalRotation so that the initial local rotation will be the zero point for the rotation limit
            if (!Application.isPlaying && !script.defaultLocalRotationOverride)
            {
                script.defaultLocalRotation = script.transform.localRotation;
            }
            if (script.axis == Vector3.zero)
            {
                return;
            }

            // Make the curve loop
            script.spline.postWrapMode = WrapMode.Loop;
            script.spline.preWrapMode  = WrapMode.Loop;

            DrawRotationSphere(script.transform.position);

            // Display the main axis
            DrawArrow(script.transform.position, Direction(script.axis), colorDefault, "Axis", 0.02f);

            Vector3 swing = script.axis.normalized;

            // Editing tools GUI
            Handles.BeginGUI();
            GUILayout.BeginArea(new Rect(10, 10, 440, 100), "Rotation Limit Spline", "Window");

            // Scale Mode and Tangent Mode
            GUILayout.BeginHorizontal();
            scaleMode   = (ScaleMode)EditorGUILayout.EnumPopup("Drag Handle", scaleMode);
            tangentMode = (TangentMode)EditorGUILayout.EnumPopup("Drag Tangents", tangentMode);
            GUILayout.EndHorizontal();

            EditorGUILayout.Space();

            if (Inspector.Button("Rotate 90 degrees", "Rotate rotation limit around axis.", script, GUILayout.Width(220)))
            {
                if (!Application.isPlaying)
                {
                    Undo.RecordObject(script, "Handle Value");
                }
                for (int i = 0; i < keys.Length; i++)
                {
                    keys[i].time += 90;
                }
            }

            // Cloning values from another RotationLimitSpline
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Clone From", "Make this rotation limit identical to another", script, GUILayout.Width(220)))
            {
                CloneLimit();
                keys = script.spline.keys;
            }
            clone = (RotationLimitSpline)EditorGUILayout.ObjectField("", clone, typeof(RotationLimitSpline), true);
            EditorGUILayout.EndHorizontal();

            GUILayout.EndArea();
            Handles.EndGUI();

            // Draw keyframes
            for (int i = 0; i < keys.Length - 1; i++)
            {
                float angle = keys[i].time;

                // Start drawing handles
                Quaternion offset   = Quaternion.AngleAxis(angle, swing);
                Quaternion rotation = Quaternion.AngleAxis(keys[i].value, offset * script.crossAxis);
                Vector3    position = script.transform.position + Direction(rotation * swing);
                Handles.Label(position, "  " + i.ToString());

                // Dragging Values
                if (selectedHandle == i)
                {
                    Handles.color = colorHandles;
                    switch (scaleMode)
                    {
                    case ScaleMode.Limit:
                        float inputValue = keys[i].value;
                        inputValue = Mathf.Clamp(Inspector.ScaleValueHandleSphere(inputValue, position, Quaternion.identity, 0.5f, 0), 0.01f, 180);
                        if (keys[i].value != inputValue)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Handle Value");
                            }
                            keys[i].value = inputValue;
                        }
                        break;

                    case ScaleMode.Angle:
                        float inputTime = keys[i].time;
                        inputTime = Inspector.ScaleValueHandleSphere(inputTime, position, Quaternion.identity, 0.5f, 0);
                        if (keys[i].time != inputTime)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Handle Angle");
                            }
                            keys[i].time = inputTime;
                        }
                        break;
                    }
                }

                // Handle select button
                if (selectedHandle != i)
                {
                    Handles.color = Color.blue;
                    if (Inspector.SphereButton(position, script.transform.rotation, 0.05f, 0.05f))
                    {
                        selectedHandle = i;
                    }
                }

                // Tangents
                if (selectedHandle == i)
                {
                    // Evaluate positions before and after the key to get the tangent positions
                    Vector3 prevPosition = GetAnglePosition(keys[i].time - 1);
                    Vector3 nextPosition = GetAnglePosition(keys[i].time + 1);

                    // Draw handles for the tangents
                    Handles.color = Color.white;
                    Vector3 toNext     = (nextPosition - position).normalized * 0.3f;
                    float   outTangent = keys[i].outTangent;
                    outTangent = Inspector.ScaleValueHandleSphere(outTangent, position + toNext, Quaternion.identity, 0.2f, 0);

                    Vector3 toPrev    = (prevPosition - position).normalized * 0.3f;
                    float   inTangent = keys[i].inTangent;
                    inTangent = Inspector.ScaleValueHandleSphere(inTangent, position + toPrev, Quaternion.identity, 0.2f, 0);

                    if (outTangent != keys[i].outTangent || inTangent != keys[i].inTangent)
                    {
                        selectedHandle = i;
                    }

                    // Make the other tangent match the dragged tangent (if in "Smooth" TangentMode)
                    switch (tangentMode)
                    {
                    case TangentMode.Smooth:
                        if (outTangent != keys[i].outTangent)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Tangents");
                            }
                            keys[i].outTangent = outTangent;
                            keys[i].inTangent  = outTangent;
                        }
                        else if (inTangent != keys[i].inTangent)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Tangents");
                            }
                            keys[i].outTangent = inTangent;
                            keys[i].inTangent  = inTangent;
                        }
                        break;

                    case TangentMode.Independent:
                        if (outTangent != keys[i].outTangent)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Tangents");
                            }
                            keys[i].outTangent = outTangent;
                        }
                        else if (inTangent != keys[i].inTangent)
                        {
                            if (!Application.isPlaying)
                            {
                                Undo.RecordObject(script, "Tangents");
                            }
                            keys[i].inTangent = inTangent;
                        }
                        break;
                    }

                    // Draw lines and labels to tangent handles
                    Handles.color = Color.white;
                    GUI.color     = Color.white;

                    Handles.DrawLine(position, position + toNext);
                    Handles.Label(position + toNext, " Out");

                    Handles.DrawLine(position, position + toPrev);
                    Handles.Label(position + toPrev, " In");
                }
            }

            // Selected Point GUI
            if (selectedHandle != -1)
            {
                Handles.BeginGUI();
                GUILayout.BeginArea(new Rect(Screen.width - 240, Screen.height - 200, 230, 150), "Handle " + selectedHandle.ToString(), "Window");

                if (Inspector.Button("Delete", "Delete this handle", script))
                {
                    if (keys.Length > 4)
                    {
                        deleteHandle = selectedHandle;
                    }
                    else if (!Warning.logged)
                    {
                        script.LogWarning("Spline Rotation Limit should have at least 3 handles");
                    }
                }
                if (Inspector.Button("Add Handle", "Add a new handle next to this one", script))
                {
                    addHandle = selectedHandle;
                }

                // Clamp the key angles to previous and next handle angles
                float prevTime = 0, nextTime = 0;
                if (selectedHandle < keys.Length - 2)
                {
                    nextTime = keys[selectedHandle + 1].time;
                }
                else
                {
                    nextTime = keys[0].time + 360;
                }

                if (selectedHandle == 0)
                {
                    prevTime = keys[keys.Length - 2].time - 360;
                }
                else
                {
                    prevTime = keys[selectedHandle - 1].time;
                }

                // Angles
                float inputTime = keys[selectedHandle].time;
                inputTime = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("Angle", "Angle of the point (0-360)."), inputTime), prevTime, nextTime);

                if (keys[selectedHandle].time != inputTime)
                {
                    if (!Application.isPlaying)
                    {
                        Undo.RecordObject(script, "Handle Angle");
                    }
                    keys[selectedHandle].time = inputTime;
                }

                // Limits
                float inputValue = keys[selectedHandle].value;
                inputValue = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("Limit", "Max angular limit from Axis at this angle"), inputValue), 0, 180);
                if (keys[selectedHandle].value != inputValue)
                {
                    if (!Application.isPlaying)
                    {
                        Undo.RecordObject(script, "Handle Limit");
                    }
                    keys[selectedHandle].value = inputValue;
                }

                // In Tangents
                float inputInTangent = keys[selectedHandle].inTangent;
                inputInTangent = EditorGUILayout.FloatField(new GUIContent("In Tangent", "In tangent of the handle point on the spline"), inputInTangent);
                if (keys[selectedHandle].inTangent != inputInTangent)
                {
                    if (!Application.isPlaying)
                    {
                        Undo.RecordObject(script, "Handle In Tangent");
                    }
                    keys[selectedHandle].inTangent = inputInTangent;
                }

                // Out tangents
                float inputOutTangent = keys[selectedHandle].outTangent;
                inputOutTangent = EditorGUILayout.FloatField(new GUIContent("Out Tangent", "Out tangent of the handle point on the spline"), inputOutTangent);
                if (keys[selectedHandle].outTangent != inputOutTangent)
                {
                    if (!Application.isPlaying)
                    {
                        Undo.RecordObject(script, "Handle Out Tangent");
                    }
                    keys[selectedHandle].outTangent = inputOutTangent;
                }

                GUILayout.EndArea();
                Handles.EndGUI();
            }

            // Make sure the keyframes are valid;
            ValidateKeyframes(keys);

            // Replace the AnimationCurve keyframes with the manipulated keyframes
            script.spline.keys = keys;

            // Display limits
            for (int i = 0; i < 360; i += 2)
            {
                float      evaluatedLimit    = script.spline.Evaluate((float)i);
                Quaternion offset            = Quaternion.AngleAxis(i, swing);
                Quaternion evaluatedRotation = Quaternion.AngleAxis(evaluatedLimit, offset * script.crossAxis);
                Quaternion testRotation      = Quaternion.AngleAxis(179.9f, offset * script.crossAxis);

                Quaternion limitedRotation = script.LimitSwing(testRotation);

                Vector3 evaluatedDirection = evaluatedRotation * swing;
                Vector3 limitedDirection   = limitedRotation * swing;

                // Display the limit points in red if they are out of range
                bool  isValid = Vector3.Distance(evaluatedDirection, limitedDirection) < 0.01f && evaluatedLimit >= 0;
                Color color   = isValid ? colorDefaultTransparent : colorInvalid;

                Vector3 limitPoint = script.transform.position + Direction(evaluatedDirection);

                Handles.color = color;
                if (i == 0)
                {
                    zeroPoint = limitPoint;
                }

                Handles.DrawLine(script.transform.position, limitPoint);

                if (i > 0)
                {
                    Handles.color = isValid ? colorDefault : colorInvalid;
                    Handles.DrawLine(limitPoint, lastPoint);
                    if (i == 358)
                    {
                        Handles.DrawLine(limitPoint, zeroPoint);
                    }
                }

                lastPoint = limitPoint;
            }

            // Deleting points
            if (deleteHandle != -1)
            {
                DeleteHandle(deleteHandle);
                selectedHandle = -1;
                deleteHandle   = -1;
            }

            // Adding points
            if (addHandle != -1)
            {
                AddHandle(addHandle);
                addHandle = -1;
            }

            Handles.color = Color.white;
            if (GUI.changed)
            {
                EditorUtility.SetDirty(script);
            }
        }
        //Using Inspector...
        internal async void UpdateTextString()
        {
            BasicFeatureLayer annoLayer = MapView.Active.Map.GetLayersAsFlattenedList().First() as BasicFeatureLayer;
            var oid = 1;

            #region Update Annotation Text via attribute. Caveat: The TEXTSTRING Anno attribute must exist

            //See "Change Annotation Text Graphic" for an alternative if TEXTSTRING is missing from the schema
            await QueuedTask.Run(() =>
            {
                //annoLayer is ~your~ Annotation layer...

                // use the inspector methodology
                var insp = new Inspector();
                insp.Load(annoLayer, oid);

                // make sure TextString attribute exists.
                //It is not guaranteed to be in the schema
                ArcGIS.Desktop.Editing.Attributes.Attribute att = insp.FirstOrDefault(a => a.FieldName == "TEXTSTRING");
                if (att != null)
                {
                    insp["TEXTSTRING"] = "Hello World";

                    //create and execute the edit operation
                    EditOperation op = new EditOperation();
                    op.Name          = "Update annotation";
                    op.Modify(insp);

                    //OR using a Dictionary - again TEXTSTRING has to exist in the schema
                    //Dictionary<string, object> newAtts = new Dictionary<string, object>();
                    //newAtts.Add("TEXTSTRING", "hello world");
                    //op.Modify(annoLayer, oid, newAtts);

                    op.Execute();
                }
            });

            #endregion

            #region Rotate or Move the Annotation

            await QueuedTask.Run(() =>
            {
                //Don't use 'Shape'....Shape is the bounding box of the annotation text. This is NOT what you want...
                //
                //var insp = new Inspector();
                //insp.Load(annoLayer, oid);
                //var shape = insp["SHAPE"] as Polygon;
                //...wrong shape...

                //Instead, we must get the TextGraphic from the anno feature.
                //The TextGraphic shape will be the anno baseline...
                //At 2.1 the only way to retrieve this textLine is to obtain the TextGraphic from the AnnotationFeature
                QueryFilter qf = new QueryFilter()
                {
                    WhereClause = "OBJECTID = 1"
                };

                //annoLayer is ~your~ Annotation layer

                var rowCursor = annoLayer.Search(qf);
                rowCursor.MoveNext();
                var annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature;
                var graphic     = annoFeature.GetGraphic();
                var textGraphic = graphic as CIMTextGraphic;
                var textLine    = textGraphic.Shape as Polyline;
                // rotate the shape 90 degrees
                var origin = GeometryEngine.Instance.Centroid(textLine);
                Geometry rotatedPolyline = GeometryEngine.Instance.Rotate(textLine, origin, System.Math.PI / 2);
                //Move the line 5 "units" in the x and y direction
                //GeometryEngine.Instance.Move(textLine, 5, 5);

                EditOperation op = new EditOperation();
                op.Name          = "Change annotation angle";
                op.Modify(annoLayer, oid, rotatedPolyline);
                op.Execute();
            });

            #endregion

            #region Change Annotation Text Graphic

            await QueuedTask.Run(() =>
            {
                EditOperation op = new EditOperation();
                op.Name          = "Change annotation graphic";

                //At 2.1 we must use an edit operation Callback...
                op.Callback(context =>
                {
                    QueryFilter qf = new QueryFilter()
                    {
                        WhereClause = "OBJECTID = 1"
                    };
                    //Cursor must be non-recycling. Use the table ~not~ the layer..i.e. "GetTable().Search()"
                    //annoLayer is ~your~ Annotation layer
                    var rowCursor = annoLayer.GetTable().Search(qf, false);
                    rowCursor.MoveNext();
                    var annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature;
                    //Get the graphic from the anno feature
                    var graphic     = annoFeature.GetGraphic();
                    var textGraphic = graphic as CIMTextGraphic;

                    // change the text and the color
                    textGraphic.Text = "hello world";
                    var symbol       = textGraphic.Symbol.Symbol;
                    symbol.SetColor(ColorFactory.Instance.RedRGB);
                    textGraphic.Symbol = symbol.MakeSymbolReference();
                    // update the graphic
                    annoFeature.SetGraphic(textGraphic);
                    // store is required
                    annoFeature.Store();
                    //refresh layer cache
                    context.Invalidate(annoFeature);
                }, annoLayer.GetTable());

                op.Execute();
            });

            #endregion
        }
Пример #37
0
 internal override void Inspect(Inspector Inspector)
 {
     Inspector.InspectLdElem(this);
 }
Пример #38
0
	// Use this for initialization
	void Start () {
        instance = this;
	}
        /// <summary>
        /// Separate a selected multipart feature into individual features.
        /// </summary>
        protected override void OnClick()
        {
            //check for one selected feature
            if (MapView.Active.Map.SelectionCount != 1)
            {
                MessageBox.Show("Please select one multipart feature to explode", "Explode Multipart Feature");
                return;
            }

            //run on MCT
            QueuedTask.Run(() =>
            {
                //get selected feature geometry
                var selectedFeatures = MapView.Active.Map.GetSelection();
                var insp             = new Inspector();
                insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First());
                var selGeom     = insp.Shape;
                var selGeomType = selGeom.GeometryType;

                //early checks for geometry type and single point in a multipoint
                if (!(selGeomType == GeometryType.Multipoint || selGeomType == GeometryType.Polygon || selGeomType == GeometryType.Polyline) || selGeom.PointCount == 1)
                {
                    MessageBox.Show("Please select a multipart feature to explode", "Explode Multipart Feature");
                    return;
                }

                //check if selected feature has multiple parts
                var mpGeom = selGeom as Multipart;
                if (mpGeom != null)
                {
                    if (mpGeom.PartCount < 2)
                    {
                        MessageBox.Show("Please select a multipart feature to explode", "Explode Multipart Feature");
                        return;
                    }
                }

                //setup the edit operation
                var op  = new EditOperation();
                op.Name = "Explode Multipart Feature";

                //handle geometry types
                switch (selGeomType)
                {
                case GeometryType.Multipoint:
                    //create a new feature for each pointcount
                    var mpoint = selGeom as Multipoint;
                    for (var i = 0; i < mpoint.PointCount; i++)
                    {
                        //copy the original feature into a dictionary and update the shape.
                        var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
                        newFeature[insp.GeometryAttribute.FieldName] = new MultipointBuilder(mpoint.Points[i]).ToGeometry();
                        op.Create(insp.MapMember, newFeature);
                    }
                    break;

                case GeometryType.Polyline:
                    //create a new feature for each polyline part
                    for (var i = 0; i < mpGeom.PartCount; i++)
                    {
                        //copy the original feature into a dictionary and update the shape.
                        var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
                        newFeature[insp.GeometryAttribute.FieldName] = new PolylineBuilder(mpGeom.Parts[i]).ToGeometry();
                        op.Create(insp.MapMember, newFeature);
                    }
                    break;

                case GeometryType.Polygon:
                    //ignore donut features for now
                    //check if any part area is negative
                    for (var i = 0; i < mpGeom.PartCount; i++)
                    {
                        if ((new PolygonBuilder(mpGeom.Parts[i]).ToGeometry()).Area < 0)
                        {
                            MessageBox.Show("Please select a non-donut polygon to explode", "Explode Mutltpart Feature");
                            return;
                        }
                    }

                    //create a new feature for each polygon part
                    for (var i = 0; i < mpGeom.PartCount; i++)
                    {
                        //copy the original feature into a dictionary and update the shape.
                        var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
                        newFeature[insp.GeometryAttribute.FieldName] = new PolygonBuilder(mpGeom.Parts[i]).ToGeometry();
                        op.Create(insp.MapMember, newFeature);
                    }
                    break;
                } //switch

                //delete the original feature and execute the creates
                //op.Delete(insp.MapMember, insp.ObjectID);
                //double cast to workaround 1.1 bug
                op.Delete(insp.MapMember, (long)(int)insp.ObjectIDAttribute.CurrentValue);
                op.Execute();
            });
        }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the edit 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 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 annoLayer in features.Keys.OfType <AnnotationLayer>())
                {
                    // are there features?
                    var featOids = features[annoLayer];
                    if (featOids.Count == 0)
                    {
                        continue;
                    }

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

                    // load an inspector with all the features
                    var insp = new Inspector();
                    insp.Load(annoLayer, featOids);

                    // get the annotation properties
                    var annoProperties = insp.GetAnnotationProperties();

                    // change the text
                    annoProperties.TextString = "Hello World";
                    // you can use a textstring with embedded formatting information
                    //annoProperties.TextString = "My <CLR red = \"255\" green = \"0\" blue = \"0\" >Special</CLR> Text";

                    // change font color to red
                    annoProperties.Color = ColorFactory.Instance.RedRGB;

                    // change the horizontal alignment
                    annoProperties.HorizontalAlignment = HorizontalAlignment.Center;

                    // set the annotation properties back on the inspector
                    insp.SetAnnotationProperties(annoProperties);

                    // call modify
                    op.Modify(insp);
                }

                // execute the operation
                if ((op != null) && !op.IsEmpty)
                {
                    return op.Execute();
                }
                return
                false;
            }));
        }
Пример #41
0
 internal override void Inspect(Inspector Inspector)
 {
     Inspector.InspectDeclFunc(this);
 }
Пример #42
0
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     await this.WaitForClick();
     var inspector = new Inspector(Assembly.GetExecutingAssembly());
     DataContext = inspector.GetInstance<IMessageHolder>();
 }
Пример #43
0
 public override void BecauseOf()
 {
     //TODO: not a fan of Inspector.GetPlan - but do I really need to wrap it?
     Plan = Inspector.GetPlan(Deployment);
 }
Пример #44
0
        /// <inheritdoc/>
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            if (inspector != null)
            {
                await inspector((dc) =>
                {
                    foreach (var assignment in Assignments)
                    {
                        JToken value         = null;
                        var(val, valueError) = assignment.Value.TryGetValue(dc.State);
                        if (valueError != null)
                        {
                            throw new Exception($"Expression evaluation resulted in an error. Expression: {assignment.Value.ToString()}. Error: {valueError}");
                        }

                        if (val != null)
                        {
                            value = JToken.FromObject(val).DeepClone();
                        }

                        value        = value?.ReplaceJTokenRecursively(dc.State);
                        var property = assignment.Property.GetValue(dc.State);
                        dc.State.SetValue(property, value);
                    }
                }).ConfigureAwait(false);

                Trace.TraceInformation($"[Turn Ended => SetProperties completed]");
            }
            else
            {
                throw new InvalidOperationException("No inspector to use for setting properties");
            }
        }
Пример #45
0
        /// <summary>
        /// This function takes the selected features in the map view, finds the first field of type string in the each feature class
        /// and modifies the attribute value to a random string.
        /// </summary>
        /// <returns>Indicator if the edit operation was successful.</returns>
        private async Task <bool> PerformAttributeChange()
        {
            try
            {
                // retrieve the currently selected features in the map view
                var currentSelectedFeatures = await QueuedTask.Run(() =>
                {
                    return(MapView.Active.Map.GetSelection());
                });

                // for each of the map members in the selected layers
                foreach (var mapMember in currentSelectedFeatures.ToDictionary())
                {
                    var featureLayer = mapMember.Key as BasicFeatureLayer;
                    // .. get the underlying table
                    var table = await QueuedTask.Run(() =>
                    {
                        return(featureLayer.GetTable());
                    });

                    // retrieve the first field of type string
                    var stringField     = table.GetFieldByTypeAsync(FieldType.String).Result;
                    var stringFieldName = stringField != null ? stringField.Name : String.Empty;

                    // check if the returned string of the field name actually contains something
                    // meaning if the current MapMember actually contains a field of type string
                    if (String.IsNullOrEmpty(stringFieldName))
                    {
                        continue;
                    }
#if notthis
                    #region Use edit operations for attribute changes
                    // create a new edit operation to encapsulate the string field modifications
                    var modifyStringsOperation = new EditOperation
                    {
                        Name = String.Format("Modify string field '{0}' in layer {1}.", stringFieldName, mapMember.Key.Name)
                    };
                    ICollection <long> oidSet = new List <long>();
                    var iCnt = 0;
                    // with each ObjectID of the selected feature
                    foreach (var oid in currentSelectedFeatures[mapMember.Key])
                    {
                        // set up a new dictionary with fields to modify
                        var modifiedAttributes = new Dictionary <string, object>
                        {
                            // add the name of the string field and the new attribute value to the dictionary
                            // in this example a random string is used
                            { stringFieldName, string.Format("Update {0} on: {1:s}", ++iCnt, DateTime.Now) }
                        };

                        // put the modify operation on the editor stack
                        modifyStringsOperation.Modify(mapMember.Key, oid, modifiedAttributes);
                        oidSet.Add(oid);
                    }

                    // execute the modify operation to apply the changes
                    await modifyStringsOperation.ExecuteAsync();

                    #endregion
#endif
                    #region Use the feature inspector for attribute changes
//#if OrUseThis
                    // as an alternative approach
                    // use the feature inspector class
                    var featureInspector = new Inspector();

                    // fill the feature inspector with the oids from the feature layer
                    await featureInspector.LoadAsync(mapMember.Key, currentSelectedFeatures[mapMember.Key]);

                    // change the attribute value for the string field
                    featureInspector[stringFieldName] = Path.GetRandomFileName().Replace(".", "");

                    // app. the new values
                    await featureInspector.ApplyAsync();

//#endif
                    #endregion
                }
            }
            catch (Exception ex)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("An error occurred while updating attribute column data {0}", ex.ToString());
            }
            return(true);
        }
        /// <summary>
        /// Finds all related children
        /// </summary>
        public HierarchyRow GetRelationshipChildren(Layer member, Geodatabase gdb,
                                                    string featureClassName, long objectID, string rcException = "")
        {
            if (!QueuedTask.OnWorker)
            {
                throw new CalledOnWrongThreadException();
            }

            string displayValue = "";

            if (member != null)
            {
                if (string.IsNullOrEmpty(_displayFieldName))
                {
                    CIMFeatureLayer currentCIMFeatureLayer = member.GetDefinition() as CIMFeatureLayer;
                    _displayFieldName = currentCIMFeatureLayer?.FeatureTable.DisplayField ?? "";
                }

                var inspector = new Inspector();
                inspector.Load(member, objectID);
                if (!string.IsNullOrEmpty(_displayFieldName))
                {
                    displayValue = $"{inspector[_displayFieldName]?.ToString() ?? ""}";
                }
            }
            //Did the display value get set?
            if (string.IsNullOrEmpty(displayValue))
            {
                displayValue = $"OID: {objectID.ToString()}";
            }

            var newHRow = new HierarchyRow()
            {
                name = displayValue,
                type = $"{featureClassName}"
            };

            //Check the layer for any relationships
            var children = GetRelationshipChildrenFromLayer(member as BasicFeatureLayer, objectID);

            if (children.Count > 0)
            {
                newHRow.children = children;
                return(newHRow);//Give layer related precedence over GDB related
            }

            //If we are here we do not have any relates on the layer
            //See if we have relates in the GDB
            var relationshipClassDefinitions = GetRelationshipClassDefinitionsFromFeatureClass(gdb, featureClassName);

            foreach (var relationshipClassDefinition in relationshipClassDefinitions)
            {
                var rcName = relationshipClassDefinition.GetName(); //get the name
                if (rcException == rcName)                          //exception so we don't go in circles
                {
                    continue;
                }
                //Alternate way of getting the features classes in the relationship (new at 1.3):
                //IReadOnlyList<Definition> definitions = GetRelatedDefinitions(relationshipClassDefinition, DefinitionRelationshipType.DatasetsRelatedThrough);
                var relationshipClass = gdb.OpenDataset <RelationshipClass>(rcName);    //open the relationship class

                var    origin      = relationshipClassDefinition.GetOriginClass();      //get the origin of the relationship class
                var    destination = relationshipClassDefinition.GetDestinationClass(); //get the destination of the relationship class
                string displayName;
                if (origin == featureClassName)
                {
                    //the feature class is the origin. So we need the rows in the destination related to the origin
                    var oids = new List <long> {
                        objectID
                    };
                    IReadOnlyList <Row> relatedOriginRows = relationshipClass.GetRowsRelatedToOriginRows(oids);
                    if (relatedOriginRows.Count > 0)
                    {
                        displayName = string.Format("{0}: {1}", rcName, destination);
                        var childHRow = new HierarchyRow()
                        {
                            name = displayName,
                            type = rcName
                        };
                        foreach (var row in relatedOriginRows)
                        {
                            //var lyr = GetRelationshipClassDefinitionsFromFeatureClass();
                            //childHRow.children.Add(GetRelationshipChildren(lyr, gdb, destination, row.GetObjectID(), rcName)); //recursive: to get the attributes of the related feature
                        }
                        newHRow.children.Add(childHRow);
                        continue;
                    }
                }
                IReadOnlyList <Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToDestinationRows(new List <long> {
                    objectID
                });                                                                                                                         //Feature class is the destination so get the rows related to it
                if (relatedDestinationRows.Count > 0)

                {
                    displayName = string.Format("{0}: {1}", rcName, origin);
                    var childHRow = new HierarchyRow()
                    {
                        name = displayName,
                        type = rcName
                    };
                    foreach (var row in relatedDestinationRows)
                    {
                        //childHRow.children.Add(GetRelationshipChildren(null, gdb, origin, row.GetObjectID(), rcName));
                    }
                    newHRow.children.Add(childHRow);
                }
            }
            return(newHRow);
        }
Пример #47
0
 public void PIK_Errors()
 {
     CommandStart.StartWoStat(d => Inspector.ShowLast());
 }
Пример #48
0
        public static void ExportLayouts(string folder, out List <string> exportLayouts)
        {
            exportLayouts = new List <string>();
            var doc    = Application.DocumentManager.MdiActiveDocument;
            var db     = doc.Database;
            var editor = doc.Editor;

            if ((short)Application.GetSystemVariable("DWGTITLED") == 0)
            {
                editor.WriteMessage("\nCommand cannot be used on an unnamed drawing");
                return;
            }
            string path = Path.Combine(folder, Path.GetFileNameWithoutExtension(doc.Name));

            Dictionary <string, ObjectId> layouts = null;

            using (doc.LockDocument())
            {
                using (var t = doc.TransactionManager.StartTransaction())
                {
                    // Get the localized name of the model tab:
                    var    btr    = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForRead);
                    var    layout = (Layout)btr.LayoutId.GetObject(OpenMode.ForRead);
                    string model  = layout.LayoutName;
                    // Open the Layout dictionary:
                    var layoutDictionary = (IDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
                    // Get the names and ids of all paper space layouts
                    // into a Dictionary<string,ObjectId>:
                    layouts = layoutDictionary.Cast <DictionaryEntry>()
                              .Where(e => ((string)e.Key) != model)
                              .ToDictionary(
                        e => (string)e.Key,
                        e => (ObjectId)e.Value);

                    t.Commit();
                }

                /// Get the export layout 'engine':
                var engine = AcExportLayout.Engine.Instance();

                using (new ManagedSystemVariable("CTAB"))
                {
                    var entry = layouts.First();
                    //foreach (var entry in layouts)
                    {
                        try
                        {
                            string filename = $"{path}_{entry.Key}.dwg";
                            editor.WriteMessage($"\nЭкспорт листа {entry.Key} => {filename}");
                            Application.SetSystemVariable("CTAB", entry.Key);
                            using (Database database = engine.ExportLayout(entry.Value))
                            {
                                if (engine.EngineStatus == AcExportLayout.ErrorStatus.Succeeded)
                                {
                                    database.SaveAs(filename, DwgVersion.Newest);
                                    exportLayouts.Add(filename);
                                }
                                else
                                {
                                    Inspector.AddError($"\nОшибка экспорта листа {entry.Key} из файла {Path.GetFileName(doc.Name)}: {engine.EngineStatus}",
                                                       System.Drawing.SystemIcons.Error);
                                    editor.WriteMessage($"\nОшибка экспорта листа: {engine.EngineStatus}");
                                    //break;
                                }
                            }
                        }
                        catch
                        {
                            Inspector.AddError($"Ошибка экспорта листа {entry.Key} из файла {Path.GetFileName(doc.Name)}");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// This method must be called on the MCT
        /// </summary>
        /// <remarks>If multiple features are selected just the ObjectID of the first feature
        /// in the selected set is returned</remarks>
        /// <param name="point"></param>
        /// <returns>The object id of the selected feature or -1</returns>
        internal static Polyline SelectLineFeature(MapPoint point) {
            if (OnUIThread)
                throw new CalledOnWrongThreadException();

            var pt = MapView.Active.MapToClient(point);

            double llx = pt.X - 5;
            double lly = pt.Y - 5;
            double urx = pt.X + 5;
            double ury = pt.Y + 5;

            EnvelopeBuilder envBuilder = new EnvelopeBuilder(MapView.Active.ClientToMap(new Point(llx, lly)),
                                                             MapView.Active.ClientToMap(new Point(urx, ury)));

            //Just get feature layers that are line types
            var selection = MapView.Active.SelectFeatures(envBuilder.ToGeometry()).Where(
                k => k.Key.ShapeType == esriGeometryType.esriGeometryPolyline
            ).ToList();

            Polyline selectedLine = null;
            if (selection.Count() > 0) {
                //return the first of the selected features
                var flayer = selection.First().Key;
                var oid = selection.First().Value[0];
                var inspector = new Inspector();
                inspector.Load(flayer, oid);
                selectedLine = inspector["SHAPE"] as Polyline;
            }
            return selectedLine;
        }
Пример #50
0
        /// <inheritdoc/>
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            if (inspector != null)
            {
                await inspector((dc) =>
                {
                    foreach (var assertion in Assertions)
                    {
                        var(val, error) = Expression.Parse(assertion).TryEvaluate <bool>(dc.State);
                        if (error != null || !val)
                        {
                            throw new Exception($"{Description} {assertion} failed");
                        }
                    }
                }).ConfigureAwait(false);

                Trace.TraceInformation($"[Turn Ended => {Description} MemoryAssertions passed]");
            }
            else
            {
                Trace.TraceInformation($"[Turn Ended => No inspector for {Description} MemoryAssertions]");
            }
        }
Пример #51
0
        public void CreateTemplate()
        {
            string value1 = "";
            string value2 = "";
            string value3 = "";

            #region Create New Template using layer.CreateTemplate

            var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault();
            if (layer == null)
            {
                return;
            }
            QueuedTask.Run(() =>
            {
                var insp = new Inspector();
                insp.LoadSchema(layer);

                insp["Field1"] = value1;
                insp["Field2"] = value2;
                insp["Field3"] = value3;

                var tags = new[] { "Polygon", "tag1", "tag2" };

                // set defaultTool using a daml-id
                string defaultTool = "esri_editing_SketchCirclePolygonTool";

                // tool filter is the tools to filter OUT
                var toolFilter = new[] { "esri_editing_SketchTracePolygonTool" };

                // create a new template
                var newTemplate = layer.CreateTemplate("My new template", "description", insp, defaultTool, tags, toolFilter);
            });
            #endregion

            #region Create Annotation Template

            // get an anno layer
            AnnotationLayer annoLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <AnnotationLayer>().FirstOrDefault();
            if (annoLayer == null)
            {
                return;
            }

            QueuedTask.Run(() =>
            {
                Inspector insp = null;
                // get the anno feature class
                var fc = annoLayer.GetFeatureClass() as ArcGIS.Core.Data.Mapping.AnnotationFeatureClass;

                // get the featureclass CIM definition which contains the labels, symbols
                var cimDefinition = fc.GetDefinition() as ArcGIS.Core.Data.Mapping.AnnotationFeatureClassDefinition;
                var labels        = cimDefinition.GetLabelClassCollection();
                var symbols       = cimDefinition.GetSymbolCollection();

                // make sure there are labels, symbols
                if ((labels.Count == 0) || (symbols.Count == 0))
                {
                    return;
                }

                // find the label class required
                //   typically you would use a subtype name or some other characteristic
                // in this case lets just use the first one

                var label = labels[0];

                // each label has a textSymbol
                // the symbolName *should* be the symbolID to be used
                var symbolName = label.TextSymbol.SymbolName;
                int symbolID   = -1;
                if (!int.TryParse(symbolName, out symbolID))
                {
                    // int.TryParse fails - attempt to find the symbolName in the symbol collection
                    foreach (var symbol in symbols)
                    {
                        if (symbol.Name == symbolName)
                        {
                            symbolID = symbol.ID;
                            break;
                        }
                    }
                }
                // no symbol?
                if (symbolID == -1)
                {
                    return;
                }

                // load the schema
                insp = new Inspector();
                insp.LoadSchema(annoLayer);

                // ok to assign these fields using the inspector[fieldName] methodology
                //   these fields are guaranteed to exist in the annotation schema
                insp["AnnotationClassID"] = label.ID;
                insp["SymbolID"]          = symbolID;

                // set up some additional annotation properties
                AnnotationProperties annoProperties = insp.GetAnnotationProperties();
                annoProperties.FontSize             = 36;
                annoProperties.TextString           = "My Annotation feature";
                annoProperties.VerticalAlignment    = VerticalAlignment.Top;
                annoProperties.HorizontalAlignment  = HorizontalAlignment.Justify;

                insp.SetAnnotationProperties(annoProperties);

                var tags = new[] { "Annotation", "tag1", "tag2" };

                // use daml-id rather than guid
                string defaultTool = "esri_editing_SketchStraightAnnoTool";

                // tool filter is the tools to filter OUT
                var toolFilter = new[] { "esri_editing_SketchCurvedAnnoTool" };

                // create a new template
                var newTemplate = annoLayer.CreateTemplate("new anno template", "description", insp, defaultTool, tags, toolFilter);
            });

            #endregion
        }
Пример #52
0
        //Using Inspector...
        internal async void UpdateAnnotation()
        {
            BasicFeatureLayer annoLayer = MapView.Active.Map.GetLayersAsFlattenedList().First() as BasicFeatureLayer;
            var oid = 1;

            #region Update Annotation Text

            await QueuedTask.Run(() =>
            {
                //annoLayer is ~your~ Annotation layer...

                // use the inspector methodology
                var insp = new Inspector(true);
                insp.Load(annoLayer, oid);

                // get the annotation properties
                AnnotationProperties annoProperties = insp.GetAnnotationProperties();
                // set the attribute
                annoProperties.TextString = "Hello World";
                // assign the annotation proeprties back to the inspector
                insp.SetAnnotationProperties(annoProperties);

                //create and execute the edit operation
                EditOperation op = new EditOperation();
                op.Name          = "Update annotation";
                op.Modify(insp);
                op.Execute();
            });

            #endregion

            #region Modify Annotation Shape

            await QueuedTask.Run(() =>
            {
                //Don't use 'Shape'....Shape is the bounding box of the annotation text. This is NOT what you want...
                //
                //var insp = new Inspector();
                //insp.Load(annoLayer, oid);
                //var shape = insp["SHAPE"] as Polygon;
                //...wrong shape...

                //Instead, we must use the AnnotationProperties

                //annoLayer is ~your~ Annotation layer
                var insp = new Inspector(true);
                insp.Load(annoLayer, oid);

                AnnotationProperties annoProperties = insp.GetAnnotationProperties();
                var shape = annoProperties.Shape;
                if (shape.GeometryType != GeometryType.GeometryBag)
                {
                    var newGeometry      = GeometryEngine.Instance.Move(shape, 10, 10);
                    annoProperties.Shape = newGeometry;
                    insp.SetAnnotationProperties(annoProperties);

                    EditOperation op = new EditOperation();
                    op.Name          = "Change annotation angle";
                    op.Modify(insp);
                    op.Execute();
                }
            });

            #endregion

            #region Modify Annotation Text Graphic

            await QueuedTask.Run(() =>
            {
                var selection = annoLayer.GetSelection();
                if (selection.GetCount() == 0)
                {
                    return;
                }

                // use the first selelcted feature
                var insp = new Inspector(true);
                insp.Load(annoLayer, selection.GetObjectIDs().FirstOrDefault());

                // getAnnoProperties should return null if not an annotation feature
                AnnotationProperties annoProperties = insp.GetAnnotationProperties();
                // get the textGraphic
                CIMTextGraphic textGraphic = annoProperties.TextGraphic;

                // change text
                textGraphic.Text = "Hello world";

                // set x,y offset via the symbol
                var symbol         = textGraphic.Symbol.Symbol;
                var textSymbol     = symbol as CIMTextSymbol;
                textSymbol.OffsetX = 2;
                textSymbol.OffsetY = 3;

                textSymbol.HorizontalAlignment = HorizontalAlignment.Center;

                // load the updated textGraphic
                annoProperties.LoadFromTextGraphic(textGraphic);
                // assign the annotation properties back
                insp.SetAnnotationProperties(annoProperties);

                EditOperation op = new EditOperation();
                op.Name          = "modify symbol";
                op.Modify(insp);
                bool result = op.Execute();
            });

            #endregion
        }
        public TResult Execute <TResult>(Expression expression)
        {
            try
            {
                var resultType = typeof(TResult);
                Inspector.StartQueryExecuteInterceptor(resultType, expression);

                var sourceExpression = ConvertDestinationExpressionToSourceExpression(expression);

                var destResultType   = typeof(TResult);
                var sourceResultType = CreateSourceResultType(destResultType);

                object destResult = null;

                // case #1: query is a projection from complex Source to complex Destination
                // example: users.UseAsDataSource().For<UserDto>().Where(x => x.Age > 20).ToList()
                if (IsProjection <TDestination>(resultType))
                {
                    // in case of a projection, we need an IQueryable
                    var sourceResult = _dataSource.Provider.CreateQuery(sourceExpression);
                    Inspector.SourceResult(sourceExpression, sourceResult);

                    var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
                                           (
                        sourceResult.ElementType,
                        typeof(TDestination),
                        _parameters,
                        _membersToExpand.Select
                        (
                            m => new MemberPath
                            (
                                m.Distinct().ToArray()
                            )
                        ).ToArray()
                                           );

                    destResult = (IQueryable <TDestination>)GetMapExpressions(queryExpressions).Aggregate(sourceResult, Select);
                }
                // case #2: query is arbitrary ("manual") projection
                // example: users.UseAsDataSource().For<UserDto>().Select(user => user.Age).ToList()
                // in case an arbitrary select-statement is enumerated, we do not need to map the expression at all
                // and can safely return it
                else if (IsProjection(resultType, sourceExpression))
                {
                    var sourceResult    = _dataSource.Provider.CreateQuery(sourceExpression);
                    var elementType     = ElementTypeHelper.GetElementType(typeof(TResult));
                    var constructorInfo = typeof(List <>).MakeGenericType(elementType).GetDeclaredConstructor(new Type[0]);
                    if (constructorInfo != null)
                    {
                        var listInstance = (IList)constructorInfo.Invoke(null);
                        foreach (var element in sourceResult)
                        {
                            listInstance.Add(element);
                        }
                        destResult = listInstance;
                    }
                }
                // case #2: projection to simple type
                // example: users.UseAsDataSource().For<UserDto>().FirstOrDefault(user => user.Age > 20)
                else
                {
                    /*
                     *  in case of an element result (so instead of IQueryable<TResult>, just TResult)
                     *  we still want to support parameters.
                     *  This is e.g. the case, when the developer writes "UseAsDataSource().For<TResult>().FirstOrDefault(x => ...)
                     *  To still be able to support parameters, we need to create a query from it.
                     *  That said, we need to replace the "element" operator "FirstOrDefault" with a "Where" operator, then apply our "Select"
                     *  to map from TSource to TResult and finally re-apply the "element" operator ("FirstOrDefault" in our case) so only
                     *  one element is returned by our "Execute<TResult>" method. Otherwise we'd get an InvalidCastException
                     *
                     * So first we visit the sourceExpression and replace "element operators" with "where"
                     * then we create our mapping expression from TSource to TDestination (select) and apply it
                     * finally, we search for the element expression overload of our replaced "element operator" that has no expression as parameter
                     *      this expression is not needed anymore as it has already been applied to the "Where" operation and can be safely omitted
                     * when we're done creating our new expression, we call the underlying provider to execute it
                     */

                    // as we need to replace the innermost element of the expression,
                    // we need to traverse it first in order to find the node to replace or potential caveats
                    // e.g. .UseAsDataSource().For<Dto>().Select(e => e.Name).First()
                    //      in the above case we cannot map anymore as the "select" operator overrides our mapping.
                    var searcher = new ReplaceableMethodNodeFinder <TSource>();
                    searcher.Visit(sourceExpression);
                    // provide the replacer with our found MethodNode or <null>
                    var replacer = new MethodNodeReplacer <TSource>(searcher.MethodNode);

                    // default back to simple mapping of object instance for backwards compatibility (e.g. mapping non-nullable to nullable fields)
                    sourceExpression = replacer.Visit(sourceExpression);

                    if (replacer.FoundElementOperator)
                    {
                        /*  in case of primitive element operators (e.g. Any(), Sum()...)
                         *  we need to map the originating types (e.g. Entity to Dto) in this query
                         *  as the final value will be projected automatically
                         *
                         *  == example 1 ==
                         *  UseAsDataSource().For<Dto>().Any(entity => entity.Name == "thename")
                         *  ..in that case sourceResultType and destResultType would both be "Boolean" which is not mappable for AutoMapper
                         *
                         *  == example 2 ==
                         *  UseAsDataSource().For<Dto>().FirstOrDefault(entity => entity.Name == "thename")
                         *  ..in this case the sourceResultType would be Entity and the destResultType Dto, so we can map the query directly
                         */

                        if (sourceResultType == destResultType)// && destResultType.IsPrimitive)
                        {
                            sourceResultType = typeof(TSource);
                            destResultType   = typeof(TDestination);
                        }

                        var queryExpressions = _mapper.ConfigurationProvider.Internal().ProjectionBuilder.GetProjection
                                               (
                            sourceResultType,
                            destResultType,
                            _parameters,
                            _membersToExpand.Select
                            (
                                m => new MemberPath
                                (
                                    m.Distinct().ToArray()
                                )
                            ).ToArray()
                                               );
                        // add projection via "select" operator
                        var expr = GetMapExpressions(queryExpressions).Aggregate(sourceExpression, (source, lambda) => Select(source, lambda));
                        // in case an element operator without predicate expression was found (and thus not replaced)
                        var replacementMethod = replacer.ElementOperator;
                        // in case an element operator with predicate expression was replaced
                        if (replacer.ReplacedMethod != null)
                        {
                            // find replacement method that has no more predicates
                            replacementMethod = typeof(Queryable).GetAllMethods()
                                                .Single(m => m.Name == replacer.ReplacedMethod.Name
#if NET45
                                                        && m.GetParameters().All(p => typeof(Queryable).IsAssignableFrom(p.Member.ReflectedType))
#endif
                                                        && m.GetParameters().Length == replacer.ReplacedMethod.GetParameters().Length - 1);
                        }

                        // reintroduce element operator that was replaced with a "where" operator to make it queryable
                        expr = Call(null,
                                    replacementMethod.MakeGenericMethod(destResultType), expr);

                        destResult = _dataSource.Provider.Execute(expr);
                    }
                    // If there was no element operator that needed to be replaced by "where", just map the result
                    else
                    {
                        var sourceResult = _dataSource.Provider.Execute(sourceExpression);
                        Inspector.SourceResult(sourceExpression, sourceResult);
                        destResult = _mapper.Map(sourceResult, sourceResultType, destResultType);
                    }
                }

                Inspector.DestResult(destResult);

                // implicitly convert types in case of valuetypes which cannot be casted explicitly
                if (typeof(TResult).IsValueType() && destResult?.GetType() != typeof(TResult))
                {
                    return((TResult)System.Convert.ChangeType(destResult, typeof(TResult)));
                }

                // if it is not a valuetype, we can safely cast it
                return((TResult)destResult);
            }
            catch (Exception x)
            {
                _exceptionHandler(x);
                throw;
            }
        }
        internal List <HierarchyRow> GetRelationshipChildrenFromLayer(BasicFeatureLayer member,
                                                                      long objectID)
        {
            var children = new List <HierarchyRow>();

            CIMBasicFeatureLayer bfl = member.GetDefinition() as CIMBasicFeatureLayer;
            var relates = bfl.FeatureTable.Relates;

            if (relates == null || relates.Length == 0)
            {
                return(children);
            }

            foreach (var relate in relates)
            {
                if (!(relate.DataConnection is CIMStandardDataConnection) &&
                    !(relate.DataConnection is CIMFeatureDatasetDataConnection))
                {
                    continue;//Not supported in this sample
                }
                var sdc     = relate.DataConnection as CIMStandardDataConnection;
                var fdc     = relate.DataConnection as CIMFeatureDatasetDataConnection;
                var factory = sdc?.WorkspaceFactory ?? fdc.WorkspaceFactory;
                var path    = sdc?.WorkspaceConnectionString ?? fdc.WorkspaceConnectionString;
                if (string.IsNullOrEmpty(path))
                {
                    continue;//No connection information we can use
                }
                path = path.Replace("DATABASE=", "");
                var dstype = sdc?.DatasetType ?? fdc.DatasetType;

                if (dstype != esriDatasetType.esriDTFeatureClass &&
                    dstype != esriDatasetType.esriDTTable)
                {
                    continue;//Not supported in the sample
                }

                var dsname          = sdc?.Dataset ?? fdc.Dataset;
                var featDatasetName = fdc?.FeatureDataset ?? "";

                Geodatabase gdb = null;
                if (factory == WorkspaceFactory.FileGDB)
                {
                    gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(path, UriKind.Absolute)));
                }
                else if (factory == WorkspaceFactory.SDE)
                {
                    gdb = new Geodatabase(new DatabaseConnectionFile(new Uri(path, UriKind.Absolute)));
                }

                Table table = null;
                //We have to open a type specific dataset - FeatureClass or Table
                //We cannot simply use 'Table' for both
                if (dstype == esriDatasetType.esriDTFeatureClass)
                {
                    table = GetDatasetFromGeodatabase <FeatureClass>(gdb, dsname, featDatasetName);
                }
                else
                {
                    table = GetDatasetFromGeodatabase <Table>(gdb, dsname, featDatasetName);
                }
                if (table == null)
                {
                    continue;//Related dataset not found
                }
                //Get any related rows
                var qry_fld = table.GetDefinition().GetFields().FirstOrDefault(f => f.Name == relate.ForeignKey);
                if (qry_fld == null)
                {
                    continue;//We cannot find the designated foreign key
                }
                //Load relevant values
                var inspector = new Inspector();
                inspector.Load(member, objectID);

                var need_quotes = qry_fld.FieldType == FieldType.String;
                var quote       = need_quotes ? "'" : "";
                var where = $"{relate.ForeignKey} = {quote}{inspector[relate.PrimaryKey]}{quote}";
                var qf = new QueryFilter()
                {
                    WhereClause = where,
                    SubFields   = $"{table.GetDefinition().GetObjectIDField()}, {relate.ForeignKey}"
                };

                var childHRow = new HierarchyRow()
                {
                    name = dsname,
                    type = $"{inspector[relate.PrimaryKey]}"
                };

                using (var rc = table.Search(qf))
                {
                    while (rc.MoveNext())
                    {
                        using (var row = rc.Current)
                        {
                            var id   = row.GetObjectID();
                            var HRow = new HierarchyRow()
                            {
                                name = $"{id}",
                                type = relate.ForeignKey
                            };
                            childHRow.children.Add(HRow);
                        }
                    }
                }
                children.Add(childHRow);
            }
            return(children);
        }
Пример #55
0
 private void InspectorsNewInspector(Inspector inspector)
 {
     //add to list
     AddWrapper(inspector);
 }
Пример #56
0
 // Start is called before the first frame update
 void Start()
 {
     inspector = leg.GetComponent <Leg>().inspector;
 }
Пример #57
0
 internal InspWrap GetInspWrap(Inspector insp)
 {
     return _inspWrappers == null
         ? null
         : _inspWrappers.Values.DefaultIfEmpty(null).FirstOrDefault(wrap => wrap.Inspector == insp);
 }
Пример #58
0
 internal override void Inspect(Inspector Inspector)
 {
     Inspector.InspectStLoc(this);
 }
Пример #59
0
 /// <summary>
 /// Gets the entity reference for the inspector specified.
 /// </summary>
 /// <param name="inspector">
 /// The inspector.
 /// </param>
 /// <returns>
 /// The entity reference.
 /// </returns>
 internal EntityReference EntityReferenceForInspector(Inspector inspector)
 {
     return this.entityReferences.GetOrAdd(inspector.InspectedType, type => this.CreateEntityReference(inspector));
 }
Пример #60
0
 /// <summary>
 /// Execute the test.
 /// </summary>
 /// <param name="adapter">Adapter to execute against.</param>
 /// <param name="callback">Logic for the bot to use.</param>
 /// <param name="inspector">Inspector for dialog context.</param>
 /// <returns>async task.</returns>
 public abstract Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null);