[C#]
ClosestFacility_GISServerAPIClass.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Location;
using ESRI.ArcGIS.NetworkAnalyst;
using System.Collections.Specialized;
namespace ClosestFacility_GISServerAPI
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class ClosestFacility_GISServerAPIClass : System.Windows.Forms.Form
{
#region Window Controls Declaration
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtServer;
private System.Windows.Forms.TextBox txtService;
private System.Windows.Forms.GroupBox fraINASolverSettings;
private System.Windows.Forms.ComboBox cboUturnPolicy;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.CheckedListBox chklstAccumulateAttributes;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckedListBox chklstRestrictions;
private System.Windows.Forms.ComboBox cboImpedance;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox chkIgnoreInvalidLocations;
private System.Windows.Forms.ComboBox cboNALayers;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.CheckBox chkReturnMap;
private System.Windows.Forms.Button cmdSolve;
private System.Windows.Forms.ComboBox cboSnapToleranceUnits;
private System.Windows.Forms.TextBox txtMaxSnapTolerance;
private System.Windows.Forms.TextBox txtSnapTolerance;
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.ComboBox cboCFRouteDirectionsLengthUnits;
private System.Windows.Forms.CheckBox chkReturnCFRoutes;
private System.Windows.Forms.CheckBox chkReturnCFRouteGeometries;
private System.Windows.Forms.CheckBox chkReturnFacilities;
private System.Windows.Forms.CheckBox chkReturnDirections;
private System.Windows.Forms.ComboBox cboCFOutputLines;
private System.Windows.Forms.ComboBox cboCFRouteDirectionsTimeAttribute;
private System.Windows.Forms.GroupBox fraINAClosestFacilitySolver;
private System.Windows.Forms.GroupBox fraINAServerClosestFacilityParams;
private System.Windows.Forms.TabControl tabCtrlOutput;
private System.Windows.Forms.TabPage tabReturnIncidentsFeatures;
private System.Windows.Forms.TabPage tabReturnBarrierFeatures;
private System.Windows.Forms.TabPage tabReturnDirections;
private System.Windows.Forms.TabPage tabReturnCFRouteFeatures;
private System.Windows.Forms.DataGrid dataGridRouteFeatures;
private System.Windows.Forms.DataGrid dataGridIncidentFeatures;
private System.Windows.Forms.DataGrid dataGridBarrierFeatures;
private System.Windows.Forms.TabPage tabReturnMap;
private System.Windows.Forms.TabPage tabReturnCFRouteGeometry;
private System.Windows.Forms.TreeView treeViewRouteGeometry;
private System.Windows.Forms.TreeView treeViewDirections;
private System.Windows.Forms.CheckBox checkReturnBarriers;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.CheckBox chkUseHierarchy;
private System.Windows.Forms.ComboBox cboIncidentsLayers;
private System.Windows.Forms.Button cmdConnect;
private CheckBox chkReturnIncidents;
private Label label26;
private ComboBox cboCFTravelDirection;
private TextBox txtCFTargetFacilityCount;
private Label label25;
private TextBox txtCFDefaultCutoff;
private Label label24;
private TabPage tabReturnFacilitiesFeatures;
private DataGrid dataGridFacilitiesFeatures;
private PictureBox pictureBox;
private ComboBox cboFacilitiesLayers;
private Label label3;
private System.Windows.Forms.GroupBox fraINAServerSolverParams;
#endregion
public ClosestFacility_GISServerAPIClass()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtServer = new System.Windows.Forms.TextBox();
this.txtService = new System.Windows.Forms.TextBox();
this.cmdSolve = new System.Windows.Forms.Button();
this.fraINASolverSettings = new System.Windows.Forms.GroupBox();
this.chkIgnoreInvalidLocations = new System.Windows.Forms.CheckBox();
this.cboUturnPolicy = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.chklstAccumulateAttributes = new System.Windows.Forms.CheckedListBox();
this.label5 = new System.Windows.Forms.Label();
this.chklstRestrictions = new System.Windows.Forms.CheckedListBox();
this.cboImpedance = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.chkUseHierarchy = new System.Windows.Forms.CheckBox();
this.fraINAServerSolverParams = new System.Windows.Forms.GroupBox();
this.chkReturnMap = new System.Windows.Forms.CheckBox();
this.cboSnapToleranceUnits = new System.Windows.Forms.ComboBox();
this.cboNALayers = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.txtMaxSnapTolerance = new System.Windows.Forms.TextBox();
this.txtSnapTolerance = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.fraINAClosestFacilitySolver = new System.Windows.Forms.GroupBox();
this.label26 = new System.Windows.Forms.Label();
this.cboCFTravelDirection = new System.Windows.Forms.ComboBox();
this.txtCFTargetFacilityCount = new System.Windows.Forms.TextBox();
this.label25 = new System.Windows.Forms.Label();
this.txtCFDefaultCutoff = new System.Windows.Forms.TextBox();
this.label24 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.cboCFOutputLines = new System.Windows.Forms.ComboBox();
this.fraINAServerClosestFacilityParams = new System.Windows.Forms.GroupBox();
this.cboFacilitiesLayers = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.chkReturnIncidents = new System.Windows.Forms.CheckBox();
this.cboIncidentsLayers = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.checkReturnBarriers = new System.Windows.Forms.CheckBox();
this.cboCFRouteDirectionsTimeAttribute = new System.Windows.Forms.ComboBox();
this.label21 = new System.Windows.Forms.Label();
this.cboCFRouteDirectionsLengthUnits = new System.Windows.Forms.ComboBox();
this.label22 = new System.Windows.Forms.Label();
this.chkReturnCFRoutes = new System.Windows.Forms.CheckBox();
this.chkReturnCFRouteGeometries = new System.Windows.Forms.CheckBox();
this.chkReturnFacilities = new System.Windows.Forms.CheckBox();
this.chkReturnDirections = new System.Windows.Forms.CheckBox();
this.cmdConnect = new System.Windows.Forms.Button();
this.tabCtrlOutput = new System.Windows.Forms.TabControl();
this.tabReturnMap = new System.Windows.Forms.TabPage();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.tabReturnDirections = new System.Windows.Forms.TabPage();
this.treeViewDirections = new System.Windows.Forms.TreeView();
this.tabReturnCFRouteFeatures = new System.Windows.Forms.TabPage();
this.dataGridRouteFeatures = new System.Windows.Forms.DataGrid();
this.tabReturnBarrierFeatures = new System.Windows.Forms.TabPage();
this.dataGridBarrierFeatures = new System.Windows.Forms.DataGrid();
this.tabReturnIncidentsFeatures = new System.Windows.Forms.TabPage();
this.dataGridIncidentFeatures = new System.Windows.Forms.DataGrid();
this.tabReturnFacilitiesFeatures = new System.Windows.Forms.TabPage();
this.dataGridFacilitiesFeatures = new System.Windows.Forms.DataGrid();
this.tabReturnCFRouteGeometry = new System.Windows.Forms.TabPage();
this.treeViewRouteGeometry = new System.Windows.Forms.TreeView();
this.fraINASolverSettings.SuspendLayout();
this.fraINAServerSolverParams.SuspendLayout();
this.fraINAClosestFacilitySolver.SuspendLayout();
this.fraINAServerClosestFacilityParams.SuspendLayout();
this.tabCtrlOutput.SuspendLayout();
this.tabReturnMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.tabReturnDirections.SuspendLayout();
this.tabReturnCFRouteFeatures.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridRouteFeatures)).BeginInit();
this.tabReturnBarrierFeatures.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridBarrierFeatures)).BeginInit();
this.tabReturnIncidentsFeatures.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridIncidentFeatures)).BeginInit();
this.tabReturnFacilitiesFeatures.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridFacilitiesFeatures)).BeginInit();
this.tabReturnCFRouteGeometry.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(120, 16);
this.label1.TabIndex = 0;
this.label1.Text = "ArcGIS Server";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 16);
this.label2.TabIndex = 1;
this.label2.Text = "Map Server Object";
//
// txtServer
//
this.txtServer.Location = new System.Drawing.Point(128, 16);
this.txtServer.Name = "txtServer";
this.txtServer.Size = new System.Drawing.Size(192, 20);
this.txtServer.TabIndex = 0;
this.txtServer.Text = "<Enter ArcGIS Server Name>";
//
// txtService
//
this.txtService.Location = new System.Drawing.Point(128, 40);
this.txtService.Name = "txtService";
this.txtService.Size = new System.Drawing.Size(192, 20);
this.txtService.TabIndex = 1;
this.txtService.Text = "<Enter ArcGIS Map Server Object>";
//
// cmdSolve
//
this.cmdSolve.Enabled = false;
this.cmdSolve.Location = new System.Drawing.Point(232, 568);
this.cmdSolve.Name = "cmdSolve";
this.cmdSolve.Size = new System.Drawing.Size(200, 32);
this.cmdSolve.TabIndex = 29;
this.cmdSolve.Text = "Solve";
this.cmdSolve.Click += new System.EventHandler(this.cmdSolve_Click);
//
// fraINASolverSettings
//
this.fraINASolverSettings.Controls.Add(this.chkIgnoreInvalidLocations);
this.fraINASolverSettings.Controls.Add(this.cboUturnPolicy);
this.fraINASolverSettings.Controls.Add(this.label11);
this.fraINASolverSettings.Controls.Add(this.label7);
this.fraINASolverSettings.Controls.Add(this.chklstAccumulateAttributes);
this.fraINASolverSettings.Controls.Add(this.label5);
this.fraINASolverSettings.Controls.Add(this.chklstRestrictions);
this.fraINASolverSettings.Controls.Add(this.cboImpedance);
this.fraINASolverSettings.Controls.Add(this.label4);
this.fraINASolverSettings.Controls.Add(this.chkUseHierarchy);
this.fraINASolverSettings.Enabled = false;
this.fraINASolverSettings.Location = new System.Drawing.Point(8, 176);
this.fraINASolverSettings.Name = "fraINASolverSettings";
this.fraINASolverSettings.Size = new System.Drawing.Size(424, 192);
this.fraINASolverSettings.TabIndex = 70;
this.fraINASolverSettings.TabStop = false;
this.fraINASolverSettings.Text = "INASolverSettings";
//
// chkIgnoreInvalidLocations
//
this.chkIgnoreInvalidLocations.Location = new System.Drawing.Point(16, 80);
this.chkIgnoreInvalidLocations.Name = "chkIgnoreInvalidLocations";
this.chkIgnoreInvalidLocations.Size = new System.Drawing.Size(144, 21);
this.chkIgnoreInvalidLocations.TabIndex = 10;
this.chkIgnoreInvalidLocations.Text = "Ignore Invalid Locations";
//
// cboUturnPolicy
//
this.cboUturnPolicy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboUturnPolicy.Location = new System.Drawing.Point(128, 48);
this.cboUturnPolicy.Name = "cboUturnPolicy";
this.cboUturnPolicy.Size = new System.Drawing.Size(280, 21);
this.cboUturnPolicy.TabIndex = 9;
//
// label11
//
this.label11.Location = new System.Drawing.Point(16, 56);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(88, 16);
this.label11.TabIndex = 73;
this.label11.Text = "Allow U-Turns";
//
// label7
//
this.label7.Location = new System.Drawing.Point(216, 104);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(120, 16);
this.label7.TabIndex = 72;
this.label7.Text = "Accumulate Attributes";
//
// chklstAccumulateAttributes
//
this.chklstAccumulateAttributes.CheckOnClick = true;
this.chklstAccumulateAttributes.Location = new System.Drawing.Point(216, 120);
this.chklstAccumulateAttributes.Name = "chklstAccumulateAttributes";
this.chklstAccumulateAttributes.ScrollAlwaysVisible = true;
this.chklstAccumulateAttributes.Size = new System.Drawing.Size(192, 64);
this.chklstAccumulateAttributes.TabIndex = 13;
//
// label5
//
this.label5.Location = new System.Drawing.Point(16, 104);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(72, 16);
this.label5.TabIndex = 70;
this.label5.Text = "Restrictions";
//
// chklstRestrictions
//
this.chklstRestrictions.CheckOnClick = true;
this.chklstRestrictions.Location = new System.Drawing.Point(16, 120);
this.chklstRestrictions.Name = "chklstRestrictions";
this.chklstRestrictions.ScrollAlwaysVisible = true;
this.chklstRestrictions.Size = new System.Drawing.Size(192, 64);
this.chklstRestrictions.TabIndex = 12;
//
// cboImpedance
//
this.cboImpedance.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboImpedance.Location = new System.Drawing.Point(128, 24);
this.cboImpedance.Name = "cboImpedance";
this.cboImpedance.Size = new System.Drawing.Size(280, 21);
this.cboImpedance.TabIndex = 8;
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 24);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 16);
this.label4.TabIndex = 67;
this.label4.Text = "Impedance";
//
// chkUseHierarchy
//
this.chkUseHierarchy.Checked = true;
this.chkUseHierarchy.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkUseHierarchy.Location = new System.Drawing.Point(216, 80);
this.chkUseHierarchy.Name = "chkUseHierarchy";
this.chkUseHierarchy.Size = new System.Drawing.Size(96, 21);
this.chkUseHierarchy.TabIndex = 11;
this.chkUseHierarchy.Text = "Use Hierarchy";
//
// fraINAServerSolverParams
//
this.fraINAServerSolverParams.Controls.Add(this.chkReturnMap);
this.fraINAServerSolverParams.Controls.Add(this.cboSnapToleranceUnits);
this.fraINAServerSolverParams.Controls.Add(this.cboNALayers);
this.fraINAServerSolverParams.Controls.Add(this.label10);
this.fraINAServerSolverParams.Controls.Add(this.label8);
this.fraINAServerSolverParams.Controls.Add(this.txtMaxSnapTolerance);
this.fraINAServerSolverParams.Controls.Add(this.txtSnapTolerance);
this.fraINAServerSolverParams.Controls.Add(this.label9);
this.fraINAServerSolverParams.Enabled = false;
this.fraINAServerSolverParams.Location = new System.Drawing.Point(8, 72);
this.fraINAServerSolverParams.Name = "fraINAServerSolverParams";
this.fraINAServerSolverParams.Size = new System.Drawing.Size(424, 96);
this.fraINAServerSolverParams.TabIndex = 71;
this.fraINAServerSolverParams.TabStop = false;
this.fraINAServerSolverParams.Text = "INAServerSolverParams";
//
// chkReturnMap
//
this.chkReturnMap.Checked = true;
this.chkReturnMap.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnMap.Location = new System.Drawing.Point(8, 72);
this.chkReturnMap.Name = "chkReturnMap";
this.chkReturnMap.Size = new System.Drawing.Size(96, 16);
this.chkReturnMap.TabIndex = 7;
this.chkReturnMap.Text = "Return Map";
//
// cboSnapToleranceUnits
//
this.cboSnapToleranceUnits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboSnapToleranceUnits.Location = new System.Drawing.Point(240, 48);
this.cboSnapToleranceUnits.Name = "cboSnapToleranceUnits";
this.cboSnapToleranceUnits.Size = new System.Drawing.Size(168, 21);
this.cboSnapToleranceUnits.TabIndex = 6;
//
// cboNALayers
//
this.cboNALayers.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboNALayers.Location = new System.Drawing.Point(128, 24);
this.cboNALayers.Name = "cboNALayers";
this.cboNALayers.Size = new System.Drawing.Size(280, 21);
this.cboNALayers.TabIndex = 3;
this.cboNALayers.SelectedIndexChanged += new System.EventHandler(this.cboNALayers_SelectedIndexChanged);
//
// label10
//
this.label10.Location = new System.Drawing.Point(168, 56);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(16, 16);
this.label10.TabIndex = 72;
this.label10.Text = "to";
//
// label8
//
this.label8.Location = new System.Drawing.Point(8, 24);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(128, 16);
this.label8.TabIndex = 71;
this.label8.Text = "NALayer Name";
//
// txtMaxSnapTolerance
//
this.txtMaxSnapTolerance.Location = new System.Drawing.Point(192, 48);
this.txtMaxSnapTolerance.Name = "txtMaxSnapTolerance";
this.txtMaxSnapTolerance.Size = new System.Drawing.Size(40, 20);
this.txtMaxSnapTolerance.TabIndex = 5;
this.txtMaxSnapTolerance.Text = "50";
//
// txtSnapTolerance
//
this.txtSnapTolerance.Location = new System.Drawing.Point(128, 48);
this.txtSnapTolerance.Name = "txtSnapTolerance";
this.txtSnapTolerance.Size = new System.Drawing.Size(32, 20);
this.txtSnapTolerance.TabIndex = 4;
this.txtSnapTolerance.Text = "2";
//
// label9
//
this.label9.Location = new System.Drawing.Point(8, 48);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(104, 16);
this.label9.TabIndex = 68;
this.label9.Text = "Search Tolerance";
//
// fraINAClosestFacilitySolver
//
this.fraINAClosestFacilitySolver.Controls.Add(this.label26);
this.fraINAClosestFacilitySolver.Controls.Add(this.cboCFTravelDirection);
this.fraINAClosestFacilitySolver.Controls.Add(this.txtCFTargetFacilityCount);
this.fraINAClosestFacilitySolver.Controls.Add(this.label25);
this.fraINAClosestFacilitySolver.Controls.Add(this.txtCFDefaultCutoff);
this.fraINAClosestFacilitySolver.Controls.Add(this.label24);
this.fraINAClosestFacilitySolver.Controls.Add(this.label20);
this.fraINAClosestFacilitySolver.Controls.Add(this.cboCFOutputLines);
this.fraINAClosestFacilitySolver.Enabled = false;
this.fraINAClosestFacilitySolver.Location = new System.Drawing.Point(232, 376);
this.fraINAClosestFacilitySolver.Name = "fraINAClosestFacilitySolver";
this.fraINAClosestFacilitySolver.Size = new System.Drawing.Size(200, 184);
this.fraINAClosestFacilitySolver.TabIndex = 76;
this.fraINAClosestFacilitySolver.TabStop = false;
this.fraINAClosestFacilitySolver.Text = "INAClosestFacilitySolver";
//
// label26
//
this.label26.Location = new System.Drawing.Point(5, 78);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(120, 16);
this.label26.TabIndex = 94;
this.label26.Text = "Direction of Travel";
//
// cboCFTravelDirection
//
this.cboCFTravelDirection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboCFTravelDirection.Location = new System.Drawing.Point(8, 97);
this.cboCFTravelDirection.Name = "cboCFTravelDirection";
this.cboCFTravelDirection.Size = new System.Drawing.Size(186, 21);
this.cboCFTravelDirection.TabIndex = 93;
//
// txtCFTargetFacilityCount
//
this.txtCFTargetFacilityCount.Location = new System.Drawing.Point(109, 49);
this.txtCFTargetFacilityCount.Name = "txtCFTargetFacilityCount";
this.txtCFTargetFacilityCount.Size = new System.Drawing.Size(85, 20);
this.txtCFTargetFacilityCount.TabIndex = 92;
//
// label25
//
this.label25.Location = new System.Drawing.Point(5, 51);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(88, 16);
this.label25.TabIndex = 91;
this.label25.Text = "Num Facilities";
//
// txtCFDefaultCutoff
//
this.txtCFDefaultCutoff.Location = new System.Drawing.Point(109, 21);
this.txtCFDefaultCutoff.Name = "txtCFDefaultCutoff";
this.txtCFDefaultCutoff.Size = new System.Drawing.Size(85, 20);
this.txtCFDefaultCutoff.TabIndex = 90;
//
// label24
//
this.label24.Location = new System.Drawing.Point(5, 24);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(88, 16);
this.label24.TabIndex = 89;
this.label24.Text = "Default Cutoff";
//
// label20
//
this.label20.Location = new System.Drawing.Point(6, 122);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(40, 16);
this.label20.TabIndex = 53;
this.label20.Text = "Shape";
//
// cboCFOutputLines
//
this.cboCFOutputLines.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboCFOutputLines.ItemHeight = 13;
this.cboCFOutputLines.Location = new System.Drawing.Point(8, 141);
this.cboCFOutputLines.Name = "cboCFOutputLines";
this.cboCFOutputLines.Size = new System.Drawing.Size(184, 21);
this.cboCFOutputLines.TabIndex = 28;
//
// fraINAServerClosestFacilityParams
//
this.fraINAServerClosestFacilityParams.Controls.Add(this.cboFacilitiesLayers);
this.fraINAServerClosestFacilityParams.Controls.Add(this.label3);
this.fraINAServerClosestFacilityParams.Controls.Add(this.chkReturnIncidents);
this.fraINAServerClosestFacilityParams.Controls.Add(this.cboIncidentsLayers);
this.fraINAServerClosestFacilityParams.Controls.Add(this.label6);
this.fraINAServerClosestFacilityParams.Controls.Add(this.checkReturnBarriers);
this.fraINAServerClosestFacilityParams.Controls.Add(this.cboCFRouteDirectionsTimeAttribute);
this.fraINAServerClosestFacilityParams.Controls.Add(this.label21);
this.fraINAServerClosestFacilityParams.Controls.Add(this.cboCFRouteDirectionsLengthUnits);
this.fraINAServerClosestFacilityParams.Controls.Add(this.label22);
this.fraINAServerClosestFacilityParams.Controls.Add(this.chkReturnCFRoutes);
this.fraINAServerClosestFacilityParams.Controls.Add(this.chkReturnCFRouteGeometries);
this.fraINAServerClosestFacilityParams.Controls.Add(this.chkReturnFacilities);
this.fraINAServerClosestFacilityParams.Controls.Add(this.chkReturnDirections);
this.fraINAServerClosestFacilityParams.Enabled = false;
this.fraINAServerClosestFacilityParams.Location = new System.Drawing.Point(8, 376);
this.fraINAServerClosestFacilityParams.Name = "fraINAServerClosestFacilityParams";
this.fraINAServerClosestFacilityParams.Size = new System.Drawing.Size(216, 224);
this.fraINAServerClosestFacilityParams.TabIndex = 75;
this.fraINAServerClosestFacilityParams.TabStop = false;
this.fraINAServerClosestFacilityParams.Text = "INAServerClosestFacilityParams";
//
// cboFacilitiesLayers
//
this.cboFacilitiesLayers.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboFacilitiesLayers.Location = new System.Drawing.Point(80, 41);
this.cboFacilitiesLayers.Name = "cboFacilitiesLayers";
this.cboFacilitiesLayers.Size = new System.Drawing.Size(128, 21);
this.cboFacilitiesLayers.TabIndex = 84;
//
// label3
//
this.label3.Location = new System.Drawing.Point(6, 44);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(82, 18);
this.label3.TabIndex = 83;
this.label3.Text = "Input Facilities";
//
// chkReturnIncidents
//
this.chkReturnIncidents.Checked = true;
this.chkReturnIncidents.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnIncidents.Location = new System.Drawing.Point(16, 118);
this.chkReturnIncidents.Name = "chkReturnIncidents";
this.chkReturnIncidents.Size = new System.Drawing.Size(120, 16);
this.chkReturnIncidents.TabIndex = 82;
this.chkReturnIncidents.Text = "Return Incidents";
//
// cboIncidentsLayers
//
this.cboIncidentsLayers.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboIncidentsLayers.Location = new System.Drawing.Point(80, 17);
this.cboIncidentsLayers.Name = "cboIncidentsLayers";
this.cboIncidentsLayers.Size = new System.Drawing.Size(128, 21);
this.cboIncidentsLayers.TabIndex = 14;
//
// label6
//
this.label6.Location = new System.Drawing.Point(6, 20);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(82, 18);
this.label6.TabIndex = 81;
this.label6.Text = "Input Incidents";
//
// checkReturnBarriers
//
this.checkReturnBarriers.Checked = true;
this.checkReturnBarriers.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkReturnBarriers.Location = new System.Drawing.Point(16, 101);
this.checkReturnBarriers.Name = "checkReturnBarriers";
this.checkReturnBarriers.Size = new System.Drawing.Size(136, 16);
this.checkReturnBarriers.TabIndex = 17;
this.checkReturnBarriers.Text = "Returns Barriers";
//
// cboCFRouteDirectionsTimeAttribute
//
this.cboCFRouteDirectionsTimeAttribute.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboCFRouteDirectionsTimeAttribute.ItemHeight = 13;
this.cboCFRouteDirectionsTimeAttribute.Location = new System.Drawing.Point(56, 198);
this.cboCFRouteDirectionsTimeAttribute.Name = "cboCFRouteDirectionsTimeAttribute";
this.cboCFRouteDirectionsTimeAttribute.Size = new System.Drawing.Size(152, 21);
this.cboCFRouteDirectionsTimeAttribute.TabIndex = 21;
//
// label21
//
this.label21.Location = new System.Drawing.Point(8, 206);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(48, 16);
this.label21.TabIndex = 52;
this.label21.Text = "Dir Time";
//
// cboCFRouteDirectionsLengthUnits
//
this.cboCFRouteDirectionsLengthUnits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboCFRouteDirectionsLengthUnits.ItemHeight = 13;
this.cboCFRouteDirectionsLengthUnits.Location = new System.Drawing.Point(56, 174);
this.cboCFRouteDirectionsLengthUnits.Name = "cboCFRouteDirectionsLengthUnits";
this.cboCFRouteDirectionsLengthUnits.Size = new System.Drawing.Size(152, 21);
this.cboCFRouteDirectionsLengthUnits.TabIndex = 20;
//
// label22
//
this.label22.Location = new System.Drawing.Point(8, 182);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(56, 16);
this.label22.TabIndex = 50;
this.label22.Text = "Dir Units";
//
// chkReturnCFRoutes
//
this.chkReturnCFRoutes.Checked = true;
this.chkReturnCFRoutes.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnCFRoutes.Location = new System.Drawing.Point(16, 84);
this.chkReturnCFRoutes.Name = "chkReturnCFRoutes";
this.chkReturnCFRoutes.Size = new System.Drawing.Size(152, 16);
this.chkReturnCFRoutes.TabIndex = 16;
this.chkReturnCFRoutes.Text = "Return CFRoutes";
//
// chkReturnCFRouteGeometries
//
this.chkReturnCFRouteGeometries.Checked = true;
this.chkReturnCFRouteGeometries.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnCFRouteGeometries.Location = new System.Drawing.Point(16, 65);
this.chkReturnCFRouteGeometries.Name = "chkReturnCFRouteGeometries";
this.chkReturnCFRouteGeometries.Size = new System.Drawing.Size(192, 18);
this.chkReturnCFRouteGeometries.TabIndex = 15;
this.chkReturnCFRouteGeometries.Text = "Return CFRoute Geometries";
//
// chkReturnFacilities
//
this.chkReturnFacilities.Checked = true;
this.chkReturnFacilities.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnFacilities.Location = new System.Drawing.Point(16, 135);
this.chkReturnFacilities.Name = "chkReturnFacilities";
this.chkReturnFacilities.Size = new System.Drawing.Size(120, 16);
this.chkReturnFacilities.TabIndex = 18;
this.chkReturnFacilities.Text = "Return Facilities";
//
// chkReturnDirections
//
this.chkReturnDirections.Checked = true;
this.chkReturnDirections.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkReturnDirections.Location = new System.Drawing.Point(16, 152);
this.chkReturnDirections.Name = "chkReturnDirections";
this.chkReturnDirections.Size = new System.Drawing.Size(160, 16);
this.chkReturnDirections.TabIndex = 19;
this.chkReturnDirections.Text = "Generate Directions";
//
// cmdConnect
//
this.cmdConnect.Location = new System.Drawing.Point(328, 16);
this.cmdConnect.Name = "cmdConnect";
this.cmdConnect.Size = new System.Drawing.Size(96, 40);
this.cmdConnect.TabIndex = 2;
this.cmdConnect.Text = "Connect";
this.cmdConnect.Click += new System.EventHandler(this.cmdConnect_Click);
//
// tabCtrlOutput
//
this.tabCtrlOutput.Controls.Add(this.tabReturnMap);
this.tabCtrlOutput.Controls.Add(this.tabReturnDirections);
this.tabCtrlOutput.Controls.Add(this.tabReturnCFRouteFeatures);
this.tabCtrlOutput.Controls.Add(this.tabReturnBarrierFeatures);
this.tabCtrlOutput.Controls.Add(this.tabReturnIncidentsFeatures);
this.tabCtrlOutput.Controls.Add(this.tabReturnFacilitiesFeatures);
this.tabCtrlOutput.Controls.Add(this.tabReturnCFRouteGeometry);
this.tabCtrlOutput.Enabled = false;
this.tabCtrlOutput.Location = new System.Drawing.Point(440, 80);
this.tabCtrlOutput.Name = "tabCtrlOutput";
this.tabCtrlOutput.SelectedIndex = 0;
this.tabCtrlOutput.Size = new System.Drawing.Size(472, 496);
this.tabCtrlOutput.TabIndex = 30;
//
// tabReturnMap
//
this.tabReturnMap.Controls.Add(this.pictureBox);
this.tabReturnMap.Location = new System.Drawing.Point(4, 22);
this.tabReturnMap.Name = "tabReturnMap";
this.tabReturnMap.Size = new System.Drawing.Size(464, 470);
this.tabReturnMap.TabIndex = 0;
this.tabReturnMap.Text = "Map";
this.tabReturnMap.UseVisualStyleBackColor = true;
//
// pictureBox
//
this.pictureBox.BackColor = System.Drawing.Color.White;
this.pictureBox.Location = new System.Drawing.Point(3, 3);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(458, 464);
this.pictureBox.TabIndex = 21;
this.pictureBox.TabStop = false;
//
// tabReturnDirections
//
this.tabReturnDirections.Controls.Add(this.treeViewDirections);
this.tabReturnDirections.Location = new System.Drawing.Point(4, 22);
this.tabReturnDirections.Name = "tabReturnDirections";
this.tabReturnDirections.Size = new System.Drawing.Size(464, 470);
this.tabReturnDirections.TabIndex = 1;
this.tabReturnDirections.Text = "Directions";
this.tabReturnDirections.UseVisualStyleBackColor = true;
//
// treeViewDirections
//
this.treeViewDirections.Location = new System.Drawing.Point(8, 8);
this.treeViewDirections.Name = "treeViewDirections";
this.treeViewDirections.Size = new System.Drawing.Size(448, 456);
this.treeViewDirections.TabIndex = 69;
//
// tabReturnCFRouteFeatures
//
this.tabReturnCFRouteFeatures.Controls.Add(this.dataGridRouteFeatures);
this.tabReturnCFRouteFeatures.Location = new System.Drawing.Point(4, 22);
this.tabReturnCFRouteFeatures.Name = "tabReturnCFRouteFeatures";
this.tabReturnCFRouteFeatures.Size = new System.Drawing.Size(464, 470);
this.tabReturnCFRouteFeatures.TabIndex = 4;
this.tabReturnCFRouteFeatures.Text = "CFRoute Features";
this.tabReturnCFRouteFeatures.UseVisualStyleBackColor = true;
//
// dataGridRouteFeatures
//
this.dataGridRouteFeatures.DataMember = "";
this.dataGridRouteFeatures.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridRouteFeatures.Location = new System.Drawing.Point(8, 8);
this.dataGridRouteFeatures.Name = "dataGridRouteFeatures";
this.dataGridRouteFeatures.Size = new System.Drawing.Size(448, 456);
this.dataGridRouteFeatures.TabIndex = 0;
//
// tabReturnBarrierFeatures
//
this.tabReturnBarrierFeatures.Controls.Add(this.dataGridBarrierFeatures);
this.tabReturnBarrierFeatures.Location = new System.Drawing.Point(4, 22);
this.tabReturnBarrierFeatures.Name = "tabReturnBarrierFeatures";
this.tabReturnBarrierFeatures.Size = new System.Drawing.Size(464, 470);
this.tabReturnBarrierFeatures.TabIndex = 3;
this.tabReturnBarrierFeatures.Text = "Barrier Features";
this.tabReturnBarrierFeatures.UseVisualStyleBackColor = true;
//
// dataGridBarrierFeatures
//
this.dataGridBarrierFeatures.DataMember = "";
this.dataGridBarrierFeatures.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridBarrierFeatures.Location = new System.Drawing.Point(8, 8);
this.dataGridBarrierFeatures.Name = "dataGridBarrierFeatures";
this.dataGridBarrierFeatures.Size = new System.Drawing.Size(448, 456);
this.dataGridBarrierFeatures.TabIndex = 0;
//
// tabReturnIncidentsFeatures
//
this.tabReturnIncidentsFeatures.Controls.Add(this.dataGridIncidentFeatures);
this.tabReturnIncidentsFeatures.Location = new System.Drawing.Point(4, 22);
this.tabReturnIncidentsFeatures.Name = "tabReturnIncidentsFeatures";
this.tabReturnIncidentsFeatures.Size = new System.Drawing.Size(464, 470);
this.tabReturnIncidentsFeatures.TabIndex = 2;
this.tabReturnIncidentsFeatures.Text = "Incident Features";
this.tabReturnIncidentsFeatures.UseVisualStyleBackColor = true;
//
// dataGridIncidentFeatures
//
this.dataGridIncidentFeatures.DataMember = "";
this.dataGridIncidentFeatures.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridIncidentFeatures.Location = new System.Drawing.Point(8, 8);
this.dataGridIncidentFeatures.Name = "dataGridIncidentFeatures";
this.dataGridIncidentFeatures.Size = new System.Drawing.Size(448, 456);
this.dataGridIncidentFeatures.TabIndex = 0;
//
// tabReturnFacilitiesFeatures
//
this.tabReturnFacilitiesFeatures.Controls.Add(this.dataGridFacilitiesFeatures);
this.tabReturnFacilitiesFeatures.Location = new System.Drawing.Point(4, 22);
this.tabReturnFacilitiesFeatures.Name = "tabReturnFacilitiesFeatures";
this.tabReturnFacilitiesFeatures.Size = new System.Drawing.Size(464, 470);
this.tabReturnFacilitiesFeatures.TabIndex = 6;
this.tabReturnFacilitiesFeatures.Text = "Facilities Features";
this.tabReturnFacilitiesFeatures.UseVisualStyleBackColor = true;
//
// dataGridFacilitiesFeatures
//
this.dataGridFacilitiesFeatures.DataMember = "";
this.dataGridFacilitiesFeatures.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridFacilitiesFeatures.Location = new System.Drawing.Point(5, 6);
this.dataGridFacilitiesFeatures.Name = "dataGridFacilitiesFeatures";
this.dataGridFacilitiesFeatures.Size = new System.Drawing.Size(458, 460);
this.dataGridFacilitiesFeatures.TabIndex = 0;
//
// tabReturnCFRouteGeometry
//
this.tabReturnCFRouteGeometry.Controls.Add(this.treeViewRouteGeometry);
this.tabReturnCFRouteGeometry.Location = new System.Drawing.Point(4, 22);
this.tabReturnCFRouteGeometry.Name = "tabReturnCFRouteGeometry";
this.tabReturnCFRouteGeometry.Size = new System.Drawing.Size(464, 470);
this.tabReturnCFRouteGeometry.TabIndex = 5;
this.tabReturnCFRouteGeometry.Text = "CFRoute Geometry";
this.tabReturnCFRouteGeometry.UseVisualStyleBackColor = true;
//
// treeViewRouteGeometry
//
this.treeViewRouteGeometry.Location = new System.Drawing.Point(8, 8);
this.treeViewRouteGeometry.Name = "treeViewRouteGeometry";
this.treeViewRouteGeometry.Size = new System.Drawing.Size(448, 456);
this.treeViewRouteGeometry.TabIndex = 1;
//
// ClosestFacility_GISServerAPIClass
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(936, 606);
this.Controls.Add(this.tabCtrlOutput);
this.Controls.Add(this.fraINAClosestFacilitySolver);
this.Controls.Add(this.fraINAServerClosestFacilityParams);
this.Controls.Add(this.fraINAServerSolverParams);
this.Controls.Add(this.fraINASolverSettings);
this.Controls.Add(this.txtService);
this.Controls.Add(this.txtServer);
this.Controls.Add(this.cmdSolve);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.cmdConnect);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "ClosestFacility_GISServerAPIClass";
this.Text = "NAServer - Closest Facility GIS Server API Sample";
this.Load += new System.EventHandler(this.Form1_Load);
this.fraINASolverSettings.ResumeLayout(false);
this.fraINAServerSolverParams.ResumeLayout(false);
this.fraINAServerSolverParams.PerformLayout();
this.fraINAClosestFacilitySolver.ResumeLayout(false);
this.fraINAClosestFacilitySolver.PerformLayout();
this.fraINAServerClosestFacilityParams.ResumeLayout(false);
this.tabCtrlOutput.ResumeLayout(false);
this.tabReturnMap.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.tabReturnDirections.ResumeLayout(false);
this.tabReturnCFRouteFeatures.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridRouteFeatures)).EndInit();
this.tabReturnBarrierFeatures.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridBarrierFeatures)).EndInit();
this.tabReturnIncidentsFeatures.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridIncidentFeatures)).EndInit();
this.tabReturnFacilitiesFeatures.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridFacilitiesFeatures)).EndInit();
this.tabReturnCFRouteGeometry.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Engine))
{
if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop))
{
System.Console.WriteLine("This application could not load the correct version of ArcGIS.");
return;
}
}
LicenseInitializer aoLicenseInitializer = new LicenseInitializer();
//ESRI License Initializer generated code.
if (!aoLicenseInitializer.InitializeApplication(
new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeArcView, esriLicenseProductCode.esriLicenseProductCodeArcEditor, esriLicenseProductCode.esriLicenseProductCodeArcInfo },
new esriLicenseExtensionCode[] { }))
{
System.Console.WriteLine(aoLicenseInitializer.LicenseMessage());
System.Console.WriteLine("This application could not initialize with the correct ArcGIS license and will shutdown.");
aoLicenseInitializer.ShutdownApplication();
return;
}
Application.Run(new ClosestFacility_GISServerAPIClass());
//ESRI License Initializer generated code.
//Do not make any call to ArcObjects after ShutDownApplication()
aoLicenseInitializer.ShutdownApplication();
}
/// <summary>
/// This function
/// - sets the server and solver parameters
/// - populates the Incidents/facilities NALocations
/// - solve the problem to find the closest facilities to incidents
/// - gets and displays the server results (map, directions, etc.)
private void cmdSolve_Click(object sender, System.EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
IServerContext serverContext = null;
try
{
// Get ServerContext and NAServer
serverContext = GetMapServerContext();
INAServer naServer = GetNAServer(serverContext);
// Get SolverParams
INAServerSolverParams solverParams = naServer.GetSolverParameters(cboNALayers.Text) as INAServerSolverParams;
// Set Solver params
SetINASolverSettings(solverParams as INASolverSettings);
SetSolverSpecificInterface(solverParams);
SetServerSolverParams(solverParams as INAServerSolverParams, serverContext);
// Load Locations
LoadLocations(solverParams, serverContext);
//Solve the Closest Facility problem
INAServerSolverResults solverResults = null;
solverResults = naServer.Solve(solverParams);
//Get NAServer results in the tab controls
OutputResults(solverParams, solverResults);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "An error has occurred");
}
finally
{
// Release the ServerContext
if (serverContext != null)
serverContext.ReleaseContext();
}
this.Cursor = Cursors.Default;
}
/// <summary>
/// This function
/// - connects to the ArcGIS Server and MapServer
/// - sets all controls for the first closest facility network analysis layer
/// </summary>
private void cmdConnect_Click(object sender, System.EventArgs e)
{
GetNetworkAnalysisLayers();
}
/// <summary>
/// This function gets the MapServer context reference being created on the ArcGIS Server
/// </summary>
private IServerContext GetMapServerContext()
{
try
{
IGISServerConnection gisServerCon = null;
IServerObjectManager som = null;
//Connect to ArcGIS Server
gisServerCon = new GISServerConnectionClass();
gisServerCon.Connect(txtServer.Text);
//Get the MapServer Object
som = gisServerCon.ServerObjectManager;
return som.CreateServerContext(txtService.Text, "MapServer");
}
catch (Exception exception)
{
throw (new Exception("Error when connecting to the ArcGIS Server/MapServer Object" + "\nMessage: " + exception.Message));
}
}
/// <summary>
/// This function gets NAServer object extension from the MapServer context
/// </summary>
private INAServer GetNAServer(IServerContext serverContext)
{
try
{
if (serverContext == null)
throw (new Exception("Error when getting the Network Analyst Server Object" + "\n Message: The MapServer Context is null."));
// Get the NAServer
IMapServer mapServer = serverContext.ServerObject as IMapServer;
IServerObjectExtensionManager soex = mapServer as IServerObjectExtensionManager;
IServerObjectExtension sext = soex.FindExtensionByTypeName("NAServer");
return sext as INAServer;
}
catch (Exception exception)
{
throw (new Exception("Error when getting to the Network Analyst Server Object" + "\nMessage: " + exception.Message));
}
}
/// <summary>
/// This function
/// - gets all closest facility network analysis layers
/// - selects the first closest facility network analysis layer
/// - sets all controls for this closest facility network analysis layer
private void GetNetworkAnalysisLayers()
{
this.Cursor = Cursors.WaitCursor;
IServerContext serverContext = null;
try
{
// Get ServerContext and NAServer
serverContext = GetMapServerContext();
INAServer naServer = GetNAServer(serverContext);
// Enable Frame
fraINAServerSolverParams.Enabled = true;
//Get ClosestFacility NA layer names
cboNALayers.Items.Clear();
string[] naLayers = naServer.GetNALayerNames(esriNAServerLayerType.esriNAServerClosestFacilityLayer);
for (int i = 0; i < naLayers.Length; i++)
{
cboNALayers.Items.Add(naLayers[i]);
}
// Select the first NA Layer name
if (cboNALayers.Items.Count > 0)
cboNALayers.SelectedIndex = 0;
else
MessageBox.Show("There is no Network Analyst layer associated with this MapServer object!", "NAServer - Closest Facility Sample", System.Windows.Forms.MessageBoxButtons.OK);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "An error has occurred");
}
finally
{
// Release the ServerContext
if (serverContext != null)
serverContext.ReleaseContext();
this.Cursor = Cursors.Default;
}
}
/// <summary>
/// This function sets all controls for the selected closest facility network analysis layer
/// </summary>
private void cboNALayers_SelectedIndexChanged(object sender, System.EventArgs e)
{
string naLayerName = cboNALayers.Text;
// Enable Solve Button
cmdSolve.Enabled = (naLayerName.Length == 0);
if (naLayerName.Length == 0)
return;
this.Cursor = Cursors.WaitCursor;
IServerContext serverContext = null;
try
{
// Get ServerContext and NAServer
serverContext = GetMapServerContext();
INAServer naServer = GetNAServer(serverContext);
INAServerSolverParams solverParams = naServer.GetSolverParameters(naLayerName);
INAServerNetworkDescription networkDescription = naServer.GetNetworkDescription(naLayerName);
// Setup Default Properties
GetINASolverSettings(networkDescription, solverParams as INASolverSettings2);
GetSolverSpecificInterface(solverParams);
GetServerSolverParams(networkDescription, solverParams as INAServerSolverParams);
// Get all Point feature Layers form the ServerContext
GetInputLocationsLayers(serverContext);
// Make frames Enable
MakeFramesEnabled(solverParams);
// Hide Tabs
HideTabs();
cmdSolve.Enabled = true;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "An error has occurred");
}
finally
{
// Release the ServerContext
if (serverContext != null)
serverContext.ReleaseContext();
this.Cursor = Cursors.Default;
}
}
/// <summary>
/// Get general NASolverSettings properties (Cost Attributes, Restrictions Attributes. etc.) and set controls
/// </summary>
private void GetINASolverSettings(INAServerNetworkDescription networkDescription, INASolverSettings2 solverSettings)
{
int ImpedanceIndex = 0;
//Get Attributes
cboImpedance.Items.Clear();
chklstAccumulateAttributes.Items.Clear();
chklstRestrictions.Items.Clear();
cboUturnPolicy.SelectedIndex = -1;
INAServerNetworkAttribute[] attributes = networkDescription.NetworkAttributes;
IStringArray accumulateAttributeNames = solverSettings.AccumulateAttributeNames;
IStringArray restrictionAttributeNames = solverSettings.RestrictionAttributeNames;
for (int i = 0; i < attributes.Length; i++)
{
INAServerNetworkAttribute networkAttribute = attributes[i];
string networkAttributeName = networkAttribute.Name;
if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
{
chklstAccumulateAttributes.Items.Add(networkAttributeName, IsStringInStringArray(networkAttributeName, accumulateAttributeNames));
int index = cboImpedance.Items.Add(networkAttribute.Name + " (" + networkAttribute.Units.ToString().Substring(7) + ")");
if (networkAttributeName == solverSettings.ImpedanceAttributeName)
ImpedanceIndex = index;
}
if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTRestriction)
{
chklstRestrictions.Items.Add(networkAttribute.Name, IsStringInStringArray(networkAttributeName, restrictionAttributeNames));
}
}
if (cboImpedance.Items.Count > 0)
cboImpedance.SelectedIndex = ImpedanceIndex;
chkUseHierarchy.Checked = solverSettings.UseHierarchy;
chkUseHierarchy.Enabled = solverSettings.HierarchyAttributeName.Length > 0;
chkIgnoreInvalidLocations.Checked = solverSettings.IgnoreInvalidLocations;
cboUturnPolicy.SelectedIndex = System.Convert.ToInt32(solverSettings.RestrictUTurns);
}
private bool IsStringInStringArray(string inputString, IStringArray stringArray)
{
int numInArray = stringArray.Count;
for (int i = 0; i < numInArray; i++)
{
if (inputString.Equals(stringArray.get_Element(i)))
return true;
}
return false;
}
/// <summary>
/// Get specific ClosestFacility solver properties (CutOff, Number of Facilities to Find, etc.) and set controls
/// </summary>
private void GetSolverSpecificInterface(INAServerSolverParams solverParams)
{
INAClosestFacilitySolver ClosestFacilitySolver = solverParams as INAClosestFacilitySolver;
if (ClosestFacilitySolver != null)
{
// Check if DefaultCutOff has been set
if (ClosestFacilitySolver.DefaultCutoff == null)
txtCFDefaultCutoff.Text = "";
else
txtCFDefaultCutoff.Text = ClosestFacilitySolver.DefaultCutoff.ToString();
txtCFTargetFacilityCount.Text = ClosestFacilitySolver.DefaultTargetFacilityCount.ToString();
cboCFTravelDirection.SelectedIndex = Convert.ToInt32(ClosestFacilitySolver.TravelDirection);
cboCFOutputLines.SelectedIndex = Convert.ToInt32(ClosestFacilitySolver.OutputLines);
}
}
/// <summary>
/// Get all point feature layers from the ServerContext
/// Add them in the "Input Incidents" and "Input Facilities" drop down lists
/// </summary>
private void GetInputLocationsLayers(IServerContext serverContext)
{
IMapServer mapServer = serverContext.ServerObject as IMapServer;
IMapServerObjects mapServerObjects = mapServer as IMapServerObjects;
IMap map = mapServerObjects.get_Map(mapServer.DefaultMapName);
cboIncidentsLayers.Items.Clear();
cboFacilitiesLayers.Items.Clear();
IEnumLayer layers = map.get_Layers(null, true);
layers.Reset();
ILayer layer;
while ((layer = layers.Next()) != null)
{
IFeatureLayer featureLayer = layer as IFeatureLayer;
if (
featureLayer != null
&& !(featureLayer.FeatureClass is INAClass)
&& featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint
)
{
cboIncidentsLayers.Items.Add(featureLayer.Name);
cboFacilitiesLayers.Items.Add(featureLayer.Name);
};
}
// Add <None> at the end in case the user does not want to load incident Location from a Feature Layer
cboIncidentsLayers.Items.Add("<None>");
cboFacilitiesLayers.Items.Add("<None>");
cboIncidentsLayers.SelectedIndex = 0;
cboFacilitiesLayers.SelectedIndex = 1;
}
/// <summary>
/// Get ServerSolverParams properties (SnapTolerance) and set controls
/// </summary>
private void GetServerSolverParams(INAServerNetworkDescription networkDescription, INAServerSolverParams solverParams)
{
chkReturnMap.Checked = true;
txtSnapTolerance.Text = solverParams.SnapTolerance.ToString();
txtMaxSnapTolerance.Text = solverParams.MaxSnapTolerance.ToString();
cboSnapToleranceUnits.SelectedIndex = Convert.ToInt32(solverParams.SnapToleranceUnits);
//Set Closest Facility Defaults
chkReturnCFRouteGeometries.Checked = false;
chkReturnCFRoutes.Checked = true;
chkReturnFacilities.Checked = true;
chkReturnIncidents.Checked = true;
chkReturnDirections.Checked = true;
checkReturnBarriers.Checked = true;
//Set Directions Defaults
cboCFRouteDirectionsTimeAttribute.Items.Clear();
INAServerNetworkAttribute[] attributes = networkDescription.NetworkAttributes;
for (int i = 0; i < attributes.Length; i++)
{
INAServerNetworkAttribute networkAttribute = attributes[i];
if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
{
if (String.Compare(networkAttribute.Units.ToString(), "esriNAUMinutes") == 0)
{
cboCFRouteDirectionsTimeAttribute.Items.Add(networkAttribute.Name);
}
}
}
// Set the default direction settings
INAServerClosestFacilityParams ClosestFacilityParams = solverParams as INAServerClosestFacilityParams;
if (ClosestFacilityParams != null)
{
cboCFRouteDirectionsLengthUnits.Text = ClosestFacilityParams.DirectionsLengthUnits.ToString().Substring(7);
//Select the first time attribute
if (cboCFRouteDirectionsTimeAttribute.Items.Count > 0)
cboCFRouteDirectionsTimeAttribute.Text = ClosestFacilityParams.DirectionsTimeAttributeName;
}
}
/// <summary>
/// Set general solver settings (Impedance, Restrictions, Accumulates, etc.)
/// </summary>
private void SetINASolverSettings(INASolverSettings solverSettings)
{
solverSettings.ImpedanceAttributeName = ExtractImpedanceName(cboImpedance.Text);
IStringArray restrictionAttributes = solverSettings.RestrictionAttributeNames;
restrictionAttributes.RemoveAll();
for (int i = 0; i < chklstRestrictions.CheckedItems.Count; i++)
restrictionAttributes.Add(chklstRestrictions.Items[chklstRestrictions.CheckedIndices[i]].ToString());
solverSettings.RestrictionAttributeNames = restrictionAttributes;
IStringArray accumulateAttributes = solverSettings.AccumulateAttributeNames;
accumulateAttributes.RemoveAll();
for (int i = 0; i < chklstAccumulateAttributes.CheckedItems.Count; i++)
accumulateAttributes.Add(chklstAccumulateAttributes.Items[chklstAccumulateAttributes.CheckedIndices[i]].ToString());
solverSettings.AccumulateAttributeNames = accumulateAttributes;
solverSettings.RestrictUTurns = (esriNetworkForwardStarBacktrack)cboUturnPolicy.SelectedIndex;
solverSettings.IgnoreInvalidLocations = chkIgnoreInvalidLocations.Checked;
solverSettings.UseHierarchy = chkUseHierarchy.Checked;
}
/// <summary>
/// Set specific solver settings (DefaultCutoff, DefaultTargetFacilityCount, etc.)
/// </summary>
private void SetSolverSpecificInterface(INAServerSolverParams solverParams)
{
INAClosestFacilitySolver cfSolver = solverParams as INAClosestFacilitySolver;
if (cfSolver != null)
{
if (txtCFDefaultCutoff.Text.Length == 0)
cfSolver.DefaultCutoff = null;
else
cfSolver.DefaultCutoff = Convert.ToDouble(txtCFDefaultCutoff.Text);
cfSolver.DefaultTargetFacilityCount = Convert.ToInt32(txtCFTargetFacilityCount.Text);
cfSolver.TravelDirection = (esriNATravelDirection)cboCFTravelDirection.SelectedIndex;
cfSolver.OutputLines = (esriNAOutputLineType)cboCFOutputLines.SelectedIndex;
}
}
/// <summary>
/// Set server solver parameters (ReturnMap, SnapTolerance, etc.)
/// </summary>
private void SetServerSolverParams(INAServerSolverParams solverParams, IServerContext serverContext)
{
solverParams.ReturnMap = chkReturnMap.Checked;
solverParams.SnapTolerance = Convert.ToDouble(txtSnapTolerance.Text);
solverParams.MaxSnapTolerance = Convert.ToDouble(txtMaxSnapTolerance.Text);
solverParams.SnapToleranceUnits = (esriUnits)cboSnapToleranceUnits.SelectedIndex;
solverParams.ImageDescription.Display.Width = pictureBox.Width;
solverParams.ImageDescription.Display.Height = pictureBox.Height;
// This code shows how to specify the output spatial reference in order to get the map
// in a different spatial reference than the Network Dataset
//IESRISpatialReferenceGEN sr = serverContext.CreateObject("esriGeometry.GeographicCoordinateSystem") as IESRISpatialReferenceGEN;
//int read;
//sr.ImportFromESRISpatialReference("GEOGCS[GCS_North_American_1983,DATUM[D_North_American_1983,SPHEROID[GRS_1980,6378137.0,298.257222101]],PRIMEM[Greenwich,0.0],UNIT[Degree,0.0174532925199433]]", out read);
//solverParams.OutputSpatialReference = sr as ISpatialReference;
INAServerClosestFacilityParams closestfacilityParams = solverParams as INAServerClosestFacilityParams;
if (closestfacilityParams != null)
{
closestfacilityParams.ReturnCFRouteGeometries = chkReturnCFRouteGeometries.Checked;
closestfacilityParams.ReturnCFRoutes = chkReturnCFRoutes.Checked;
closestfacilityParams.ReturnIncidents = chkReturnIncidents.Checked;
closestfacilityParams.ReturnFacilities = chkReturnFacilities.Checked;
closestfacilityParams.ReturnBarriers = checkReturnBarriers.Checked;
closestfacilityParams.ReturnDirections = chkReturnDirections.Checked;
closestfacilityParams.DirectionsLengthUnits = GetstringToesriUnits(cboCFRouteDirectionsLengthUnits.Text);
closestfacilityParams.DirectionsTimeAttributeName = cboCFRouteDirectionsTimeAttribute.Text;
}
}
/// <summary>
/// Make frames Enabled
/// </summary>
private void MakeFramesEnabled(INAServerSolverParams solverParams)
{
fraINAClosestFacilitySolver.Enabled = ((solverParams as INAServerClosestFacilityParams) != null);
fraINAServerClosestFacilityParams.Enabled = ((solverParams as INAServerClosestFacilityParams) != null);
fraINASolverSettings.Enabled = ((solverParams as INAServerClosestFacilityParams) != null);
}
/// <summary>
/// Load form
/// </summary>
private void Form1_Load(object sender, System.EventArgs e)
{
cboUturnPolicy.Items.Add("Nowhere");
cboUturnPolicy.Items.Add("Everywhere");
cboUturnPolicy.Items.Add("Only at Dead Ends");
cboSnapToleranceUnits.Items.Add("Unknown Units");
cboSnapToleranceUnits.Items.Add("Inches");
cboSnapToleranceUnits.Items.Add("Points");
cboSnapToleranceUnits.Items.Add("Feet");
cboSnapToleranceUnits.Items.Add("Yards");
cboSnapToleranceUnits.Items.Add("Miles");
cboSnapToleranceUnits.Items.Add("Nautical Miles");
cboSnapToleranceUnits.Items.Add("Millimeters");
cboSnapToleranceUnits.Items.Add("Centimeters");
cboSnapToleranceUnits.Items.Add("Meters");
cboSnapToleranceUnits.Items.Add("Kilometers");
cboSnapToleranceUnits.Items.Add("DecimalDegrees");
cboSnapToleranceUnits.Items.Add("Decimeters");
// Closest Facility
cboCFOutputLines.Items.Add("None");
cboCFOutputLines.Items.Add("Straight Line");
cboCFOutputLines.Items.Add("True Shape");
cboCFOutputLines.Items.Add("True Shape With Ms");
cboCFTravelDirection.Items.Add("From Facility");
cboCFTravelDirection.Items.Add("To Facility");
cboCFRouteDirectionsLengthUnits.Items.Add("Feet");
cboCFRouteDirectionsLengthUnits.Items.Add("Yards");
cboCFRouteDirectionsLengthUnits.Items.Add("Miles");
cboCFRouteDirectionsLengthUnits.Items.Add("Meters");
cboCFRouteDirectionsLengthUnits.Items.Add("Kilometers");
if (txtServer.Text != "" && txtServer.Text != "<Enter ArcGIS Server Name>"
&& txtService.Text != "" && txtService.Text != "<Enter ArcGIS Map Server Object>")
GetNetworkAnalysisLayers();
}
/// <summary>
/// This function shows how to populate incident or facilities locations using two different options:
/// 1) From Record Set using a Point Feature Class - Uncommented
/// 2) From an Array of PropertySets - Commented out
/// Uncomment the option, you would like to use
/// </summary>
private void LoadLocations(INAServerSolverParams solverParams, IServerContext serverContext)
{
// Begin Option 1
IRecordSet recSet = null;
INAServerClosestFacilityParams closestfacilityParams = solverParams as INAServerClosestFacilityParams;
// Get Input incident Feature Class from the MapServer
// Do not create Incidents if <NONE> is selected
if (cboIncidentsLayers.Text.ToUpper() != "<NONE>")
{
recSet = GetRecordSetFromFeatureLayer(serverContext, cboIncidentsLayers.Text);
INAServerRecordSet incidentsRecSet = serverContext.CreateObject("esriNetworkAnalyst.NAServerRecordSet") as INAServerRecordSet;
incidentsRecSet.RecordSet = recSet;
closestfacilityParams.Incidents = incidentsRecSet;
}
// Get Input facility Feature Class from the MapServer
// Do not create Facilities if <NONE> is selected
if (cboFacilitiesLayers.Text.ToUpper() != "<NONE>")
{
recSet = GetRecordSetFromFeatureLayer(serverContext, cboFacilitiesLayers.Text);
INAServerRecordSet facilitiesRecSet = serverContext.CreateObject("esriNetworkAnalyst.NAServerRecordSet") as INAServerRecordSet;
facilitiesRecSet.RecordSet = recSet;
closestfacilityParams.Facilities = facilitiesRecSet;
}
// End Option 1
// Begin Option 2
/*
IPropertySetArray propSets = serverContext.CreateObject("esriSystem.PropertySetArray") as IPropertySetArray;
// Set one incident
propSets.Add(CreateLocationPropertySet(serverContext, "Incident 1", -122.49024904900, 37.74811940430, null));
// Create NAServerPropertySets
INAServerPropertySets incidentsPropSets = serverContext.CreateObject("esriNetworkAnalyst.NAServerPropertySets") as INAServerPropertySets;
incidentsPropSets.PropertySets = propSets;
// Pass the incident PropertySets
INAServerClosestFacilityParams closestfacilityParams = solverParams as INAServerClosestFacilityParams;
closestfacilityParams.Incidents = incidentsPropSets;
* */
// End Option 2
}
/// <summary>
/// This function returns a IRecordSet corresponding to the Layername passed in
/// </summary>
private IRecordSet GetRecordSetFromFeatureLayer(IServerContext serverContext, string LayerName)
{
//Get the feature class to load in
IMapServer mapServer = serverContext.ServerObject as IMapServer;
IMapServerObjects mapServerObjects = mapServer as IMapServerObjects;
IMap map = mapServerObjects.get_Map(mapServer.DefaultMapName);
IFeatureClass featureClass = null;
IEnumLayer layers = map.get_Layers(null, true);
layers.Reset();
ILayer layer;
while ((layer = layers.Next()) != null)
if (layer.Name.ToUpper() == LayerName.ToUpper())
{
IFeatureLayer featureLayer = layer as IFeatureLayer;
featureClass = featureLayer.FeatureClass;
break;
}
if (featureClass == null)
throw (new Exception("Could not find the input layer name " + LayerName));
IRecordSet recSet = null;
recSet = serverContext.CreateObject("esriGeodatabase.RecordSet") as IRecordSet;
IQueryFilter queryFilter = serverContext.CreateObject("esriGeodatabase.QueryFilter") as IQueryFilter;
queryFilter.SubFields = "*";
IRecordSetInit recSetInit = recSet as IRecordSetInit;
recSetInit.SetSourceTable(featureClass as ITable, queryFilter);
return recSet;
}
/// <summary>
/// Output Results Messages, Map, CFRoute Geometries, Directions
/// </summary>
private void OutputResults(INAServerSolverParams solverParams, INAServerSolverResults solverResults)
{
string messagesSolverResults = "";
// Output Solve messages
IGPMessages gpMessages = solverResults.SolveMessages;
if (gpMessages != null)
{
for (int i = 0; i < gpMessages.Count; i++)
{
IGPMessage gpMessage = gpMessages.GetMessage(i);
messagesSolverResults += "\n" + gpMessage.Description;
}
}
// Uncomment the following section to output the total impedance of each route in a MessageBox
//INAServerClosestFacilityResults closestFacilitySolverResults = solverResults as INAServerClosestFacilityResults;
//if (closestFacilitySolverResults != null)
//{
// for (int i = 0; i < closestFacilitySolverResults.TotalImpedances.GetLength(0); i++)
// {
// messagesSolverResults += "\nTotal Impedance for Route[" + (i + 1) + "] = ";
// messagesSolverResults += closestFacilitySolverResults.TotalImpedances[i].ToString("f");
// messagesSolverResults += " " + ExtractImpedanceUnits(cboImpedance.Text).ToLower();
// }
//}
// Show a message box displaying both solver messages and total_impedance per route
if (messagesSolverResults.Length > 0)
MessageBox.Show(messagesSolverResults, "NAServer Closest Facility Results");
//Output Map
pictureBox.Image = null;
if (solverParams.ReturnMap)
{
IMapImage mapImage = solverResults.MapImage;
if ((mapImage != null) && (mapImage.MimeData != null))
pictureBox.Image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(mapImage.MimeData));
}
pictureBox.Refresh();
// Output closest facility results (directions, CFRoutes geometries and more)
if (((solverParams as INAServerClosestFacilityParams) != null) && ((solverResults as INAServerClosestFacilityResults) != null))
OutputClosestFacilityResults(solverParams as INAServerClosestFacilityParams, solverResults as INAServerClosestFacilityResults);
}
/// <summary>
/// Output closest facility results according to the ServerClosestFacilityParams options
/// </summary>
private void OutputClosestFacilityResults(INAServerClosestFacilityParams solverParams, INAServerClosestFacilityResults solverResults)
{
// Return Directions if generated
if (solverParams.ReturnDirections)
{
AddTabAndControl(this.tabReturnDirections, this.treeViewDirections);
OutputDirections(solverResults.Directions);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnDirections);
// Return CFRoute Geometries if generated
if (solverParams.ReturnCFRouteGeometries)
{
AddTabAndControl(this.tabReturnCFRouteGeometry, this.treeViewRouteGeometry);
OutputPolylines(solverResults.CFRouteGeometries);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnCFRouteGeometry);
// Return CFRoute Features as RecordSet
if (solverParams.ReturnCFRoutes)
{
AddTabAndControl(this.tabReturnCFRouteFeatures, this.dataGridRouteFeatures);
OutputRecSetToDataGrid(solverResults.CFRoutes, dataGridRouteFeatures);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnCFRouteFeatures);
// Return Incident Features as RecordSet
if (solverParams.ReturnIncidents)
{
AddTabAndControl(this.tabReturnIncidentsFeatures, this.dataGridIncidentFeatures);
OutputRecSetToDataGrid(solverResults.Incidents, dataGridIncidentFeatures);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnIncidentsFeatures);
// Return Facility Features as RecordSet
if (solverParams.ReturnFacilities)
{
AddTabAndControl(this.tabReturnFacilitiesFeatures, this.dataGridFacilitiesFeatures);
OutputRecSetToDataGrid(solverResults.Facilities, dataGridFacilitiesFeatures);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnFacilitiesFeatures);
// Return Barrier Features as RecordSet
if (solverParams.ReturnBarriers)
{
AddTabAndControl(this.tabReturnBarrierFeatures, this.dataGridBarrierFeatures);
OutputRecSetToDataGrid(solverResults.Barriers, dataGridBarrierFeatures);
}
else
this.tabCtrlOutput.TabPages.Remove(this.tabReturnBarrierFeatures);
// Make TabControlOutput enable
tabCtrlOutput.Enabled = true;
}
/// <summary>
/// Output Route Geometries (Polylines) in a TreeView control
/// </summary>
private void OutputPolylines(IPolyline[] polylines)
{
// Suppress repainting the TreeView until all the objects have been created.
treeViewRouteGeometry.BeginUpdate();
// Clear the TreeView each time the method is called.
treeViewRouteGeometry.Nodes.Clear();
for (int i = 0; i < polylines.Length; i++)
{
TreeNode newNode = new TreeNode("Polyline Length for CFRoute [" + (i + 1) + "] = " + polylines[i].Length.ToString());
treeViewRouteGeometry.Nodes.Add(newNode);
IPointCollection pointCollection = polylines[i] as IPointCollection;
for (int j = 0; j < pointCollection.PointCount - 1; j++)
{
IPoint point = pointCollection.get_Point(j);
treeViewRouteGeometry.Nodes[i].Nodes.Add(new TreeNode("Point [" + (j + 1) + "]: " + point.X + "," + point.Y));
}
}
// Check if Route Geometry has been generated
if (polylines.Length == 0)
{
TreeNode newNode = new TreeNode("CFRoute Geometry not generated");
treeViewRouteGeometry.Nodes.Add(newNode);
}
// Begin repainting the TreeView.
treeViewRouteGeometry.ExpandAll();
treeViewRouteGeometry.EndUpdate();
}
/// <summary>
/// Output Directions if a TreeView control
/// </summary>
private void OutputDirections(INAStreetDirections[] serverDirections)
{
// Suppress repainting the TreeView until all the objects have been created.
treeViewDirections.BeginUpdate();
// Clear the TreeView each time the method is called.
treeViewDirections.Nodes.Clear();
for (int i = 0; i < serverDirections.Length; i++)
{
// get Directions from the ith route
INAStreetDirections directions;
directions = serverDirections[i];
// get Summary (Total Distance and Time)
INAStreetDirection direction = directions.Summary;
string totallength = null, totaltime = null;
for (int k = 0; k < direction.StringCount; k++)
{
if (direction.get_StringType(k) == esriDirectionsStringType.esriDSTLength)
totallength = direction.get_String(k);
if (direction.get_StringType(k) == esriDirectionsStringType.esriDSTTime)
totaltime = direction.get_String(k);
}
// Add a Top a Node with the Route number and Total Distance and Total Time
TreeNode newNode = new TreeNode("Directions for CFRoute [" + (i + 1) + "] - Total Distance: " + totallength + " Total Time: " + totaltime);
treeViewDirections.Nodes.Add(newNode);
// Then add a node for each step-by-step directions
for (int directionIndex = 0; directionIndex < directions.DirectionCount; directionIndex++)
{
direction = directions.get_Direction(directionIndex);
for (int stringIndex = 0; stringIndex < direction.StringCount; stringIndex++)
{
if (direction.get_StringType(stringIndex) == esriDirectionsStringType.esriDSTGeneral ||
direction.get_StringType(stringIndex) == esriDirectionsStringType.esriDSTDepart ||
direction.get_StringType(stringIndex) == esriDirectionsStringType.esriDSTArrive)
treeViewDirections.Nodes[i].Nodes.Add(new TreeNode(direction.get_String(stringIndex)));
}
}
}
// Check if Directions have been generated
if (serverDirections.Length == 0)
{
TreeNode newNode = new TreeNode("Directions not generated");
treeViewDirections.Nodes.Add(newNode);
}
// Begin repainting the TreeView.
treeViewDirections.ExpandAll();
treeViewDirections.EndUpdate();
}
/// <summary>
/// Generic function to output RecordSet (Incidents, Facilities, Barriers, or Routes) in a DataDrid Control
/// </summary>
private void OutputRecSetToDataGrid(IRecordSet recSet, System.Windows.Forms.DataGrid OutDataGrid)
{
IFields fields = recSet.Fields;
DataSet dataSet = new DataSet("dataSet");
DataTable dataTable = new DataTable("Results");
dataSet.Tables.Add(dataTable);
// Get Field Names
DataColumn dataColumn = null;
for (int f = 0; f < fields.FieldCount; f++)
{
dataColumn = new DataColumn(fields.get_Field(f).Name.ToString());
dataTable.Columns.Add(dataColumn);
}
// Populate DataGrid rows by RecordSet
DataRow newDataRow;
ICursor cur = recSet.get_Cursor(false);
IRow row = cur.NextRow();
if (row != null)
{
while (row != null)
{
newDataRow = dataTable.NewRow();
for (int l = 0; l < row.Fields.FieldCount; l++)
{
newDataRow[l] = row.get_Value(l).ToString();
}
dataTable.Rows.Add(newDataRow);
row = cur.NextRow();
}
}
OutDataGrid.SetDataBinding(dataSet, "Results");
OutDataGrid.Visible = true;
}
/// <summary>
/// Create a property set for NALocation
/// </summary>
private IPropertySet CreateLocationPropertySet(IServerContext serverContext, string name, object X, object Y, ISpatialReference sr)
{
IPropertySet propSet = serverContext.CreateObject("esriSystem.PropertySet") as IPropertySet;
propSet.SetProperty("Name", name);
propSet.SetProperty("X", X);
propSet.SetProperty("Y", Y);
propSet.SetProperty("SpatialReference", sr);
return propSet;
}
/// <summary>
/// Helper function to convert a string unit (e.g Miles) to an esriNetworkAnalystUnits (e.g esriNAUMiles)
/// </summary>
private esriNetworkAttributeUnits GetstringToesriUnits(string stresriUnits)
{
switch (stresriUnits.ToLower())
{
case "inches": return esriNetworkAttributeUnits.esriNAUInches;
case "feet": return esriNetworkAttributeUnits.esriNAUFeet;
case "yards": return esriNetworkAttributeUnits.esriNAUYards;
case "miles": return esriNetworkAttributeUnits.esriNAUMiles;
case "nautical miles": return esriNetworkAttributeUnits.esriNAUNauticalMiles;
case "millimeters": return esriNetworkAttributeUnits.esriNAUMillimeters;
case "centimeters": return esriNetworkAttributeUnits.esriNAUCentimeters;
case "meters": return esriNetworkAttributeUnits.esriNAUMeters;
case "kilometers": return esriNetworkAttributeUnits.esriNAUKilometers;
case "decimal degrees": return esriNetworkAttributeUnits.esriNAUDecimalDegrees;
case "decimeters": return esriNetworkAttributeUnits.esriNAUDecimeters;
case "seconds": return esriNetworkAttributeUnits.esriNAUSeconds;
case "minutes": return esriNetworkAttributeUnits.esriNAUMinutes;
case "hours": return esriNetworkAttributeUnits.esriNAUHours;
case "days": return esriNetworkAttributeUnits.esriNAUDays;
case "unknown": return esriNetworkAttributeUnits.esriNAUUnknown;
default: return esriNetworkAttributeUnits.esriNAUUnknown;
}
}
/// <summary>
/// Helper function to extract the impedance name in a string like "impedancename (impedanceunits)"
/// </summary>
private string ExtractImpedanceName(string impedanceUnits)
{
int firstIndex = impedanceUnits.LastIndexOf(" ");
int lastIndex = impedanceUnits.Length;
return impedanceUnits.Remove(firstIndex, (lastIndex - firstIndex));
}
/// <summary>
/// Helper function to extract the impedance unit in a string like "impedancename (impedanceunits)"
/// </summary>
private string ExtractImpedanceUnits(string impedanceUnits)
{
int firstIndex = impedanceUnits.LastIndexOf("(") + 1;
int lastIndex = impedanceUnits.LastIndexOf(")");
return impedanceUnits.Substring(firstIndex, (lastIndex - firstIndex));
}
/// <summary>
/// Hide tabs
/// </summary>
private void HideTabs()
{
// remove tabs initially - There are added when the result is returned.
this.tabCtrlOutput.TabPages.Remove(this.tabReturnDirections);
this.tabCtrlOutput.TabPages.Remove(this.tabReturnCFRouteGeometry);
this.tabCtrlOutput.TabPages.Remove(this.tabReturnCFRouteFeatures);
this.tabCtrlOutput.TabPages.Remove(this.tabReturnFacilitiesFeatures);
this.tabCtrlOutput.TabPages.Remove(this.tabReturnIncidentsFeatures);
this.tabCtrlOutput.TabPages.Remove(this.tabReturnBarrierFeatures);
}
/// <summary>
//// Add a tab page and a tab control
/// </summary>
private void AddTabAndControl(TabPage tabPage, System.Windows.Forms.Control controlToAdd)
{
if (!tabCtrlOutput.TabPages.Contains(tabPage))
{
tabCtrlOutput.TabPages.Add(tabPage);
tabPage.Controls.Add(controlToAdd);
}
}
}
}
[Visual Basic .NET]
ClosestFacility_GISServerAPIClass.vb
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.OleDb
Imports System.Xml
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.Server
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Location
Imports ESRI.ArcGIS.NetworkAnalyst
Imports System.Collections.Specialized
Public Class ClosestFacility_GISServerAPIClass
''' <summary>
''' This function
''' - connects to the ArcGIS Server and MapServer
''' - sets all controls for the first closest facility network analysis layer
''' </summary>
Private Sub cmdConnect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
GetNetworkAnalysisLayers()
End Sub
''' <summary>
''' This function
''' - gets all closest facility network analysis layers
''' - selects the first closest facility network analysis layer
''' - sets all controls for this closest facility network analysis layer
''' </summary>
Private Sub GetNetworkAnalysisLayers()
Me.Cursor = Cursors.WaitCursor
Dim serverContext As IServerContext = Nothing
Try
' Get ServerContext and NAServer
serverContext = GetMapServerContext()
Dim naServer As INAServer = GetNAServer(serverContext)
' Enable Frame
fraINAServerSolverParams.Enabled = True
'Get closest facility NA layer names
cboNALayers.Items.Clear()
Dim naLayers() As String = naServer.GetNALayerNames(esriNAServerLayerType.esriNAServerClosestFacilityLayer)
For i As Integer = 0 To naLayers.Length - 1
cboNALayers.Items.Add(naLayers(i))
Next i
' Select the first NA Layer name
If cboNALayers.Items.Count > 0 Then
cboNALayers.SelectedIndex = 0
Else
MessageBox.Show("There is no Network Analyst layer associated with this MapServer object!", "NAServer - Closest Facility Sample", System.Windows.Forms.MessageBoxButtons.OK)
End If
Catch exception As Exception
MessageBox.Show(exception.Message, "An error has occurred")
Finally
' Release the ServerContext
If Not serverContext Is Nothing Then
serverContext.ReleaseContext()
End If
Me.Cursor = Cursors.Default
End Try
End Sub
''' <summary>
''' This function gets the MapServer context reference being created on the ArcGIS Server
''' </summary>
Private Function GetMapServerContext() As IServerContext
Try
Dim gisServerCon As IGISServerConnection = Nothing
Dim som As IServerObjectManager = Nothing
'Connect to ArcGIS Server
gisServerCon = New GISServerConnectionClass()
gisServerCon.Connect(txtServer.Text)
'Get the MapServer Object
som = gisServerCon.ServerObjectManager
Return som.CreateServerContext(txtService.Text, "MapServer")
Catch exception As Exception
Throw (New Exception("Error when connecting to the ArcGIS Server/MapServer Object" + "\nMessage: " + exception.Message))
End Try
End Function
''' <summary>
''' This function gets NAServer object extension from the MapServer context
''' </summary>
Private Function GetNAServer(ByVal serverContext As IServerContext) As INAServer
Try
If serverContext Is Nothing Then
Throw (New Exception("Error when getting the Network Analyst Server Object" + "\n Message: The MapServer Context is Nothing."))
End If
' Get the NAServer
Dim mapServer As IMapServer = serverContext.ServerObject
Dim soex As IServerObjectExtensionManager = mapServer
Dim sext As IServerObjectExtension = soex.FindExtensionByTypeName("NAServer")
Dim naServer As INAServer = sext
Return naServer
Catch exception As Exception
Throw (New Exception("Error when getting to the Network Analyst Server Object" + "\nMessage: " + exception.Message))
End Try
End Function
''' <summary>
''' This function sets all controls for the selected closest facility network analysis layer
''' </summary>
Private Sub cboNALayers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboNALayers.SelectedIndexChanged
Dim naLayerName As String = cboNALayers.Text
' Enable Solve Button
'cmdSolve.Enabled = (naLayerName.Length = 0)
If naLayerName.Length = 0 Then
Return
End If
Me.Cursor = Cursors.WaitCursor
Dim serverContext As IServerContext = Nothing
Try
' Get ServerContext and NAServer
serverContext = GetMapServerContext()
Dim naServer As INAServer = GetNAServer(serverContext)
Dim solverParams As INAServerSolverParams = naServer.GetSolverParameters(naLayerName)
Dim networkDescription As INAServerNetworkDescription = naServer.GetNetworkDescription(naLayerName)
' Setup Default Properties
GetINASolverSettings(networkDescription, solverParams)
GetSolverSpecificInterface(solverParams)
GetServerSolverParams(networkDescription, solverParams)
' Get all Point feature Layers form the ServerContext
GetInputLocationsLayers(serverContext)
' Make frames Enable
MakeFramesEnabled(solverParams)
' Hide Tabs
HideTabs()
cmdSolve.Enabled = True
Catch exception As Exception
MessageBox.Show(exception.Message, "An error has occurred")
Finally
' Release the ServerContext
If Not serverContext Is Nothing Then
serverContext.ReleaseContext()
End If
Me.Cursor = Cursors.Default
End Try
End Sub
''' <summary>
''' Get ServerSolverParams properties (SnapTolerance) and set controls
''' </summary>
Private Sub GetServerSolverParams(ByVal networkDescription As INAServerNetworkDescription, ByVal solverParams As INAServerSolverParams)
chkReturnMap.Checked = True
txtSnapTolerance.Text = solverParams.SnapTolerance.ToString()
txtMaxSnapTolerance.Text = solverParams.MaxSnapTolerance.ToString()
cboSnapToleranceUnits.SelectedIndex = Convert.ToInt32(solverParams.SnapToleranceUnits)
'Set Closest Facility Defaults
chkReturnCFRouteGeometries.Checked = False
chkReturnCFRoutes.Checked = True
chkReturnFacilities.Checked = True
chkReturnIncidents.Checked = True
chkReturnDirections.Checked = True
checkReturnBarriers.Checked = True
'Set Directions Defaults
cboCFRouteDirectionsTimeAttribute.Items.Clear()
Dim attributes() As INAServerNetworkAttribute = networkDescription.NetworkAttributes
For i As Integer = 0 To attributes.Length - 1
Dim networkAttribute As INAServerNetworkAttribute = attributes(i)
If networkAttribute.UsageType = esriNetworkAttributeUsageType.esriNAUTCost Then
If String.Compare(networkAttribute.Units.ToString(), "esriNAUMinutes") = 0 Then
cboCFRouteDirectionsTimeAttribute.Items.Add(networkAttribute.Name)
End If
End If
Next
' Set the default direction settings
Dim ClosestFacilityParams As INAServerClosestFacilityParams = solverParams
If Not ClosestFacilityParams Is Nothing Then
cboCFRouteDirectionsLengthUnits.Text = ClosestFacilityParams.DirectionsLengthUnits.ToString().Substring(7)
'Select the first time attribute
If cboCFRouteDirectionsTimeAttribute.Items.Count > 0 Then
cboCFRouteDirectionsTimeAttribute.Text = ClosestFacilityParams.DirectionsTimeAttributeName
End If
End If
End Sub
''' <summary>
''' Get general NASolverSettings properties (Cost Attributes, Restrictions Attributes. etc.) and set controls
''' </summary>
Private Sub GetINASolverSettings(ByVal networkDescription As INAServerNetworkDescription, ByVal solverSettings As INASolverSettings2)
Dim impedanceIndex As Integer = 0
'Get Attributes
cboImpedance.Items.Clear()
chklstAccumulateAttributes.Items.Clear()
chklstRestrictions.Items.Clear()
cboUturnPolicy.SelectedIndex = -1
Dim attributes() As INAServerNetworkAttribute = networkDescription.NetworkAttributes
Dim accumulateAttributeNames As IStringArray = solverSettings.AccumulateAttributeNames
Dim restrictionAttributeNames As IStringArray = solverSettings.RestrictionAttributeNames
For i As Integer = 0 To attributes.Length - 1
Dim networkAttribute As INAServerNetworkAttribute = attributes(i)
Dim networkAttributeName As String = networkAttribute.Name
If networkAttribute.UsageType = esriNetworkAttributeUsageType.esriNAUTCost Then
chklstAccumulateAttributes.Items.Add(networkAttribute.Name, IsStringInStringArray(networkAttributeName, accumulateAttributeNames))
Dim index As Integer = cboImpedance.Items.Add(networkAttribute.Name + " (" + networkAttribute.Units.ToString().Substring(7) + ")")
If networkAttributeName = solverSettings.ImpedanceAttributeName Then
impedanceIndex = index
End If
End If
If networkAttribute.UsageType = esriNetworkAttributeUsageType.esriNAUTRestriction Then
chklstRestrictions.Items.Add(networkAttribute.Name, IsStringInStringArray(networkAttributeName, restrictionAttributeNames))
End If
Next
If cboImpedance.Items.Count > 0 Then
cboImpedance.SelectedIndex = impedanceIndex
End If
chkUseHierarchy.Checked = solverSettings.UseHierarchy
chkUseHierarchy.Enabled = solverSettings.HierarchyAttributeName.Length > 0
chkIgnoreInvalidLocations.Checked = solverSettings.IgnoreInvalidLocations
cboUturnPolicy.SelectedIndex = System.Convert.ToInt32(solverSettings.RestrictUTurns)
End Sub
Private Function IsStringInStringArray(ByVal inputString As String, ByVal stringArray As IStringArray) As Boolean
Dim numInArray As Integer = stringArray.Count
For i As Integer = 0 To numInArray - 1
If inputString.Equals(stringArray.Element(i)) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Get specific ClosestFacility solver properties (CutOff, Number of Facilities to Find, etc.) and set controls
''' </summary>
Private Sub GetSolverSpecificInterface(ByVal solverParams As INAServerSolverParams)
Dim ClosestFacilitySolver As INAClosestFacilitySolver = solverParams
If Not ClosestFacilitySolver Is Nothing Then
' Check if DefaultCutOff has been set
If ClosestFacilitySolver.DefaultCutoff Is Nothing Then
txtCFDefaultCutoff.Text = ""
Else
txtCFDefaultCutoff.Text = ClosestFacilitySolver.DefaultCutoff.ToString()
End If
txtCFTargetFacilityCount.Text = ClosestFacilitySolver.DefaultTargetFacilityCount.ToString()
cboCFTravelDirection.SelectedIndex = Convert.ToInt32(ClosestFacilitySolver.TravelDirection)
cboCFOutputLines.SelectedIndex = Convert.ToInt32(ClosestFacilitySolver.OutputLines)
End If
End Sub
''' <summary>
''' Set general solver settings (Impedance, Restrictions, Accumulates, etc.)
''' </summary>
Private Sub SetINASolverSettings(ByVal solverSettings As INASolverSettings)
solverSettings.ImpedanceAttributeName = ExtractImpedanceName(cboImpedance.Text)
Dim restrictionAttributes As IStringArray = solverSettings.RestrictionAttributeNames
restrictionAttributes.RemoveAll()
Dim i As Integer
For i = 0 To chklstRestrictions.CheckedItems.Count - 1
restrictionAttributes.Add(chklstRestrictions.Items(chklstRestrictions.CheckedIndices(i)).ToString())
Next i
solverSettings.RestrictionAttributeNames = restrictionAttributes
Dim accumulateAttributes As IStringArray = solverSettings.AccumulateAttributeNames
accumulateAttributes.RemoveAll()
For i = 0 To chklstAccumulateAttributes.CheckedItems.Count - 1
accumulateAttributes.Add(chklstAccumulateAttributes.Items(chklstAccumulateAttributes.CheckedIndices(i)).ToString())
Next i
solverSettings.AccumulateAttributeNames = accumulateAttributes
solverSettings.RestrictUTurns = CType(cboUturnPolicy.SelectedIndex, esriNetworkForwardStarBacktrack)
solverSettings.IgnoreInvalidLocations = chkIgnoreInvalidLocations.Checked
solverSettings.UseHierarchy = chkUseHierarchy.Checked
End Sub
''' <summary>
''' Set server solver parameters (ReturnMap, SnapTolerance, etc.)
''' </summary>
Private Sub SetServerSolverParams(ByVal solverParams As INAServerSolverParams, ByVal serverContext As IServerContext)
solverParams.ReturnMap = chkReturnMap.Checked
solverParams.SnapTolerance = Convert.ToDouble(txtSnapTolerance.Text)
solverParams.MaxSnapTolerance = Convert.ToDouble(txtMaxSnapTolerance.Text)
solverParams.SnapToleranceUnits = CType(cboSnapToleranceUnits.SelectedIndex, esriUnits)
solverParams.ImageDescription.Display.Width = pictureBox.Width
solverParams.ImageDescription.Display.Height = pictureBox.Height
' This code shows how to specify the output spatial reference in order to get the map
' in a different spatial reference than the Network Dataset
'IESRISpatialReferenceGEN sr = serverContext.CreateObject("esriGeometry.GeographicCoordinateSystem")
'dim read as Integer
'sr.ImportFromESRISpatialReference("GEOGCS[GCS_North_American_1983,DATUM[D_North_American_1983,SPHEROID[GRS_1980,6378137.0,298.257222101]],PRIMEM[Greenwich,0.0],UNIT[Degree,0.0174532925199433]]", out read)
'solverParams.OutputSpatialReference = sr
Dim closestfacilityParams As INAServerClosestFacilityParams = solverParams
If Not closestfacilityParams Is Nothing Then
closestfacilityParams.ReturnCFRouteGeometries = chkReturnCFRouteGeometries.Checked
closestfacilityParams.ReturnCFRoutes = chkReturnCFRoutes.Checked
closestfacilityParams.ReturnIncidents = chkReturnIncidents.Checked
closestfacilityParams.ReturnFacilities = chkReturnFacilities.Checked
closestfacilityParams.ReturnBarriers = checkReturnBarriers.Checked
closestfacilityParams.ReturnDirections = chkReturnDirections.Checked
closestfacilityParams.DirectionsLengthUnits = GetstringToesriUnits(cboCFRouteDirectionsLengthUnits.Text)
closestfacilityParams.DirectionsTimeAttributeName = cboCFRouteDirectionsTimeAttribute.Text
End If
End Sub
''' <summary>
''' Set specific solver settings (DefaultCutoff, DefaultTargetFacilityCount, etc.)
''' </summary>
Private Sub SetSolverSpecificInterface(ByVal solverParams As INAServerSolverParams)
Dim cfSolver As INAClosestFacilitySolver = solverParams
If Not cfSolver Is Nothing Then
If txtCFDefaultCutoff.Text.Length = 0 Then
cfSolver.DefaultCutoff = Nothing
Else
cfSolver.DefaultCutoff = Convert.ToDouble(txtCFDefaultCutoff.Text)
End If
cfSolver.DefaultTargetFacilityCount = Convert.ToInt32(txtCFTargetFacilityCount.Text)
cfSolver.TravelDirection = CType(cboCFTravelDirection.SelectedIndex, esriNATravelDirection)
cfSolver.OutputLines = CType(cboCFOutputLines.SelectedIndex, esriNAOutputLineType)
End If
End Sub
''' <summary>
''' Get all point feature layers from the ServerContext
''' Add them in the "Input Incidents" and "Input Facilities" drop down lists
''' </summary>
Private Sub GetInputLocationsLayers(ByVal serverContext As IServerContext)
Dim mapServer As IMapServer = serverContext.ServerObject
Dim mapServerObjects As IMapServerObjects = mapServer
Dim map As IMap = mapServerObjects.Map(mapServer.DefaultMapName)
cboIncidentsLayers.Items.Clear()
cboFacilitiesLayers.Items.Clear()
Dim layers As IEnumLayer = map.Layers(Nothing, True)
layers.Reset()
Dim layer As ILayer = layers.Next()
While layer IsNot Nothing
If TypeOf layer Is IFeatureLayer Then
Dim FeatureLayer As IFeatureLayer = layer
If _
Not (TypeOf FeatureLayer.FeatureClass Is INAClass) _
And FeatureLayer.FeatureClass.ShapeType = esriGeometryType.esriGeometryPoint _
Then
cboIncidentsLayers.Items.Add(FeatureLayer.Name)
cboFacilitiesLayers.Items.Add(FeatureLayer.Name)
End If
End If
layer = layers.Next()
End While
' Add <None> at the end in case the user does not want to load incident Location from a Feature Layer
cboIncidentsLayers.Items.Add("<None>")
cboFacilitiesLayers.Items.Add("<None>")
cboIncidentsLayers.SelectedIndex = 0
cboFacilitiesLayers.SelectedIndex = 1
End Sub
''' <summary>
''' Helper function to convert a string unit (e.g Miles) to an esriNetworkAnalystUnits (e.g esriNAUMiles)
''' </summary>
Private Function GetstringToesriUnits(ByVal stresriUnits As String) As esriNetworkAttributeUnits
Select Case stresriUnits.ToLower()
Case "inches"
Return esriNetworkAttributeUnits.esriNAUInches
Case "feet"
Return esriNetworkAttributeUnits.esriNAUFeet
Case "yards"
Return esriNetworkAttributeUnits.esriNAUYards
Case "miles"
Return esriNetworkAttributeUnits.esriNAUMiles
Case "nautical miles"
Return esriNetworkAttributeUnits.esriNAUNauticalMiles
Case "millimeters"
Return esriNetworkAttributeUnits.esriNAUMillimeters
Case "centimeters"
Return esriNetworkAttributeUnits.esriNAUCentimeters
Case "meters"
Return esriNetworkAttributeUnits.esriNAUMeters
Case "kilometers"
Return esriNetworkAttributeUnits.esriNAUKilometers
Case "decimal degrees"
Return esriNetworkAttributeUnits.esriNAUDecimalDegrees
Case "decimeters"
Return esriNetworkAttributeUnits.esriNAUDecimeters
Case "seconds"
Return esriNetworkAttributeUnits.esriNAUSeconds
Case "minutes"
Return esriNetworkAttributeUnits.esriNAUMinutes
Case "hours"
Return esriNetworkAttributeUnits.esriNAUHours
Case "days"
Return esriNetworkAttributeUnits.esriNAUDays
Case "unknown"
Return esriNetworkAttributeUnits.esriNAUUnknown
Case Else
Return esriNetworkAttributeUnits.esriNAUUnknown
End Select
End Function
''' <summary>
''' Helper function to extract the impedance name in a string like "impedancename (impedanceunits)"
''' </summary>
Private Function ExtractImpedanceName(ByVal ImpedanceUnits As String) As String
Dim firstIndex As Integer = ImpedanceUnits.LastIndexOf(" ")
Dim lastIndex As Integer = ImpedanceUnits.Length
Return ImpedanceUnits.Remove(firstIndex, (lastIndex - firstIndex))
End Function
''' <summary>
''' Helper function to extract the impedance unit in a string like "impedancename (impedanceunits)"
''' </summary>
Private Function ExtractImpedanceUnits(ByVal ImpedanceUnits As String) As String
Dim firstIndex As Integer = ImpedanceUnits.LastIndexOf("(") + 1
Dim lastIndex As Integer = ImpedanceUnits.LastIndexOf(")")
Return ImpedanceUnits.Substring(firstIndex, (lastIndex - firstIndex))
End Function
''' <summary>
''' Make frames Enabled
''' </summary>
Private Sub MakeFramesEnabled(ByVal solverParams As INAServerSolverParams)
Me.fraINAClosestFacilitySolver.Enabled = (Not solverParams Is Nothing)
Me.fraINAServerClosestFacilityParams.Enabled = (Not solverParams Is Nothing)
fraINASolverSettings.Enabled = (Not solverParams Is Nothing)
End Sub
''' <summary>
''' Hide tabs
''' </summary>
Private Sub HideTabs()
' remove tabs initially - There are added when the result is returned.
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnDirections)
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnFacilitiesFeatures)
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnIncidentsFeatures)
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnBarrierFeatures)
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnCFRouteGeometry)
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnCFRouteFeatures)
End Sub
''' <summary>
''' Load form
''' </summary>
Private Sub Route_GISServerAPIClass_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cboUturnPolicy.Items.Add("Nowhere")
cboUturnPolicy.Items.Add("Everywhere")
cboUturnPolicy.Items.Add("Only at Dead Ends")
cboSnapToleranceUnits.Items.Add("Unknown Units")
cboSnapToleranceUnits.Items.Add("Inches")
cboSnapToleranceUnits.Items.Add("Points")
cboSnapToleranceUnits.Items.Add("Feet")
cboSnapToleranceUnits.Items.Add("Yards")
cboSnapToleranceUnits.Items.Add("Miles")
cboSnapToleranceUnits.Items.Add("Nautical Miles")
cboSnapToleranceUnits.Items.Add("Millimeters")
cboSnapToleranceUnits.Items.Add("Centimeters")
cboSnapToleranceUnits.Items.Add("Meters")
cboSnapToleranceUnits.Items.Add("Kilometers")
cboSnapToleranceUnits.Items.Add("DecimalDegrees")
cboSnapToleranceUnits.Items.Add("Decimeters")
' Closest Facility
cboCFOutputLines.Items.Add("None")
cboCFOutputLines.Items.Add("Straight Line")
cboCFOutputLines.Items.Add("True Shape")
cboCFOutputLines.Items.Add("True Shape With Ms")
cboCFTravelDirection.Items.Add("From Facility")
cboCFTravelDirection.Items.Add("To Facility")
cboCFRouteDirectionsLengthUnits.Items.Add("Feet")
cboCFRouteDirectionsLengthUnits.Items.Add("Yards")
cboCFRouteDirectionsLengthUnits.Items.Add("Miles")
cboCFRouteDirectionsLengthUnits.Items.Add("Meters")
cboCFRouteDirectionsLengthUnits.Items.Add("Kilometers")
If (txtServer.Text <> "" And txtServer.Text <> "<Enter ArcGIS Server Name>" _
And txtService.Text <> "" And txtService.Text <> "<Enter ArcGIS Map Server Object>") Then
GetNetworkAnalysisLayers()
End If
End Sub
''' <summary>
''' This function shows how to populate incident or facilities locations using two different options:
''' 1) From Record Set using a Point Feature Class - Uncommented
''' 2) From an Array of PropertySets - Commented out
''' Uncomment the option, you would like to use
''' </summary>
Private Sub LoadLocations(ByVal solverParams As INAServerSolverParams, ByVal serverContext As IServerContext)
' Begin Option 1
Dim recSet As IRecordSet = Nothing
Dim closestfacilityParams As INAServerClosestFacilityParams = solverParams
' Get Input incident Feature Class from the MapServer
' Do not create Incidents if <NONE> is selected
If cboIncidentsLayers.Text.ToUpper() <> "<NONE>" Then
recSet = GetRecordSetFromFeatureLayer(serverContext, cboIncidentsLayers.Text)
Dim incidentsRecSet As INAServerRecordSet = serverContext.CreateObject("esriNetworkAnalyst.NAServerRecordSet")
incidentsRecSet.RecordSet = recSet
closestfacilityParams.Incidents = incidentsRecSet
End If
' Get Input facility Feature Class from the MapServer
' Do not create Facilities if <NONE> is selected
If cboFacilitiesLayers.Text.ToUpper() <> "<NONE>" Then
recSet = GetRecordSetFromFeatureLayer(serverContext, cboFacilitiesLayers.Text)
Dim facilitiesRecSet As INAServerRecordSet = serverContext.CreateObject("esriNetworkAnalyst.NAServerRecordSet")
facilitiesRecSet.RecordSet = recSet
closestfacilityParams.Facilities = facilitiesRecSet
End If
' End Option 1
'' Begin Option 2
'Dim propSets As IPropertySetArray = serverContext.CreateObject("esriSystem.PropertySetArray")
'' Set one incident
'propSets.Add(CreateLocationPropertySet(serverContext, "Incident 1", -122.490249049, 37.7481194043, Nothing))
'' Create NAServerPropertySets
'Dim incidentsPropSets As INAServerPropertySets = serverContext.CreateObject("esriNetworkAnalyst.NAServerPropertySets")
'incidentsPropSets.PropertySets = propSets
'' Pass the incident PropertySets
'Dim closestfacilityParams As INAServerClosestFacilityParams = solverParams
'closestfacilityParams.Incidents = incidentsPropSets
'' End Option 2
End Sub
''' <summary>
''' This function returns a IRecordSet corresponding to the Layername passed in
''' </summary>
Private Function GetRecordSetFromFeatureLayer(ByVal serverContext As IServerContext, ByVal LayerName As String) As IRecordSet
'Get the feature class to load in
Dim mapServer As IMapServer = serverContext.ServerObject
Dim mapServerObjects As IMapServerObjects = mapServer
Dim map As IMap = mapServerObjects.Map(mapServer.DefaultMapName)
Dim featureClass As IFeatureClass = Nothing
Dim layers As IEnumLayer = map.Layers(Nothing, True)
layers.Reset()
Dim layer As ILayer = layers.Next()
While layer IsNot Nothing
If layer.Name.ToUpper() = LayerName.ToUpper() Then
Dim featureLayer As IFeatureLayer = layer
featureClass = featureLayer.FeatureClass
Exit While
End If
layer = layers.Next()
End While
If featureClass Is Nothing Then
Throw (New Exception("Could not find the input layer name " + LayerName))
End If
Dim recSet As IRecordSet = Nothing
recSet = serverContext.CreateObject("esriGeodatabase.RecordSet")
Dim queryFilter As IQueryFilter = serverContext.CreateObject("esriGeodatabase.QueryFilter")
queryFilter.SubFields = "*"
Dim recSetInit As IRecordSetInit = recSet
recSetInit.SetSourceTable(featureClass, queryFilter)
Return recSet
End Function
''' <summary>
''' Output Results Messages, Map, Route Geometries, Directions
''' </summary>
Private Sub OutputResults(ByVal solverParams As INAServerSolverParams, ByVal solverResults As INAServerSolverResults)
Dim messagesSolverResults As String = ""
' Output Solve messages
Dim gpMessages As IGPMessages = solverResults.SolveMessages
If (Not gpMessages Is Nothing) Then
For i As Integer = 0 To gpMessages.Count - 1
Dim gpMessage As IGPMessage = gpMessages.GetMessage(i)
messagesSolverResults += vbCr + gpMessage.Description
Next i
End If
' Uncomment the following section to output the total impedance of each route in a MessageBox
'Dim closestFacilitySolverResults As INAServerClosestFacilityResults = solverResults
'If Not closestFacilitySolverResults Is Nothing Then
' For i As Integer = 0 To closestFacilitySolverResults.TotalImpedances.GetLength(0) - 1
' messagesSolverResults += vbCr + "Total Impedance for CFRoute[" + System.Convert.ToString(i + 1) + "] = "
' messagesSolverResults += closestFacilitySolverResults.TotalImpedances(i).ToString("f")
' messagesSolverResults += " " + ExtractImpedanceUnits(cboImpedance.Text).ToLower()
' Next
'End If
' Show a message box displaying both solver messages and total_impedance per route
If (messagesSolverResults.Length() > 0) Then
MessageBox.Show(messagesSolverResults, "NAServer Closest Facility Results")
End If
'Output Map
pictureBox.Image = Nothing
If (solverParams.ReturnMap) Then
Dim mapImage As IMapImage = solverResults.MapImage
If ((Not mapImage Is Nothing) And (Not mapImage.MimeData Is Nothing)) Then
pictureBox.Image = System.Drawing.Image.FromStream(New System.IO.MemoryStream(mapImage.MimeData))
End If
pictureBox.Refresh()
End If
' Output closest facility results (directions, CFRoutes geometries and more)
If ((Not solverParams Is Nothing) And (Not solverResults Is Nothing)) Then
OutputClosestFacilityResults(solverParams, solverResults)
End If
End Sub
''' <summary>
''' Output closest facility results according to the ServerClosestFacilityParams options
''' </summary>
Private Sub OutputClosestFacilityResults(ByVal solverParams As INAServerClosestFacilityParams, ByVal solverResults As INAServerClosestFacilityResults)
' Return Directions if generated
If solverParams.ReturnDirections Then
AddTabAndControl(Me.tabReturnDirections, Me.treeViewDirections)
OutputDirections(solverResults.Directions)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnDirections)
End If
' Return CFRoute Geometries if generated
If solverParams.ReturnCFRouteGeometries Then
AddTabAndControl(Me.tabReturnCFRouteGeometry, Me.treeViewRouteGeometry)
OutputPolylines(solverResults.CFRouteGeometries)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnCFRouteGeometry)
End If
' Return CFRoute Features as RecordSet
If solverParams.ReturnCFRoutes Then
AddTabAndControl(Me.tabReturnCFRouteFeatures, Me.dataGridRouteFeatures)
OutputRecSetToDataGrid(solverResults.CFRoutes, dataGridRouteFeatures)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnCFRouteFeatures)
End If
' Return Incident Features as RecordSet
If solverParams.ReturnIncidents Then
AddTabAndControl(Me.tabReturnIncidentsFeatures, Me.dataGridIncidentFeatures)
OutputRecSetToDataGrid(solverResults.Incidents, dataGridIncidentFeatures)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnIncidentsFeatures)
End If
' Return Facility Features as RecordSet
If solverParams.ReturnFacilities Then
AddTabAndControl(Me.tabReturnFacilitiesFeatures, Me.dataGridFacilitiesFeatures)
OutputRecSetToDataGrid(solverResults.Facilities, dataGridFacilitiesFeatures)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnFacilitiesFeatures)
End If
' Return Barrier Features as RecordSet
If (solverParams.ReturnBarriers) Then
AddTabAndControl(Me.tabReturnBarrierFeatures, Me.dataGridBarrierFeatures)
OutputRecSetToDataGrid(solverResults.Barriers, dataGridBarrierFeatures)
Else
Me.tabCtrlOutput.TabPages.Remove(Me.tabReturnBarrierFeatures)
End If
' Make TabControlOutput enable
tabCtrlOutput.Enabled = True
End Sub
''' <summary>
''' Add a tab page and a tab control
''' </summary>
Private Sub AddTabAndControl(ByVal tabPage As TabPage, ByVal controlToAdd As System.Windows.Forms.Control)
If Not tabCtrlOutput.TabPages.Contains(tabPage) Then
tabCtrlOutput.TabPages.Add(tabPage)
tabPage.Controls.Add(controlToAdd)
End If
End Sub
''' <summary>
''' Output Directions if a TreeView control
''' </summary>
Private Sub OutputDirections(ByVal serverDirections() As INAStreetDirections)
' Suppress repainting the TreeView until all the objects have been created.
treeViewDirections.BeginUpdate()
' Clear the TreeView each time the method is called.
treeViewDirections.Nodes.Clear()
For i As Integer = 0 To serverDirections.Length - 1
' get Directions from the ith route
Dim directions As INAStreetDirections
directions = serverDirections(i)
' get Summary (Total Distance and Time)
Dim direction As INAStreetDirection = directions.Summary
Dim totallength As String = Nothing, totaltime As String = Nothing
For k As Integer = 0 To direction.StringCount - 1
If direction.StringType(k) = esriDirectionsStringType.esriDSTLength Then
totallength = direction.String(k)
End If
If direction.StringType(k) = esriDirectionsStringType.esriDSTTime Then
totaltime = direction.String(k)
End If
Next k
' Add a Top a Node with the Route number and Total Distance and Total Time
Dim NewNode As TreeNode = New TreeNode("Directions for CFRoute [" + System.Convert.ToString(i + 1) + "] - Total Distance: " + totallength + " Total Time: " + totaltime)
treeViewDirections.Nodes.Add(NewNode)
' Then add a node for each step-by-step directions
For directionIndex As Integer = 0 To directions.DirectionCount - 1
direction = directions.Direction(directionIndex)
For stringIndex As Integer = 0 To direction.StringCount - 1
If (direction.StringType(stringIndex) = esriDirectionsStringType.esriDSTGeneral Or _
direction.StringType(stringIndex) = esriDirectionsStringType.esriDSTDepart Or _
direction.StringType(stringIndex) = esriDirectionsStringType.esriDSTArrive) Then
treeViewDirections.Nodes(i).Nodes.Add(New TreeNode(direction.String(stringIndex)))
End If
Next stringIndex
Next directionIndex
Next i
' Check if Directions have been generated
If serverDirections.Length = 0 Then
Dim NewNode As TreeNode = New TreeNode("Directions not generated")
treeViewDirections.Nodes.Add(NewNode)
End If
' Begin repainting the TreeView.
treeViewDirections.ExpandAll()
treeViewDirections.EndUpdate()
End Sub
''' <summary>
''' Generic function to output RecordSet (Facilities, Incidents, Barriers, or CFRoutes) in a DataDrid Control
''' </summary>
Private Sub OutputRecSetToDataGrid(ByVal recSet As IRecordSet, ByVal OutDataGrid As System.Windows.Forms.DataGrid)
Dim fields As IFields = recSet.Fields
Dim dataSet As DataSet = New DataSet("dataSet")
Dim dataTable As DataTable = New DataTable("Results")
dataSet.Tables.Add(dataTable)
' Get Field Names
Dim dataColumn As DataColumn = Nothing
For f As Integer = 0 To fields.FieldCount - 1
dataColumn = New DataColumn(fields.Field(f).Name.ToString())
dataTable.Columns.Add(dataColumn)
Next f
' Populate DataGrid rows by RecordSet
Dim newDataRow As DataRow
Dim cur As ICursor = recSet.Cursor(False)
Dim row As IRow = cur.NextRow()
If Not row Is Nothing Then
While Not row Is Nothing
newDataRow = dataTable.NewRow()
For l As Integer = 0 To row.Fields.FieldCount - 1
newDataRow(l) = row.Value(l).ToString()
Next l
dataTable.Rows.Add(newDataRow)
row = cur.NextRow()
End While
End If
OutDataGrid.SetDataBinding(dataSet, "Results")
OutDataGrid.Visible = True
End Sub
''' <summary>
''' Output Route Geometries (Polylines) in a TreeView control
''' </summary>
Private Sub OutputPolylines(ByVal polylines() As IPolyline)
' Suppress repainting the TreeView until all the objects have been created.
treeViewRouteGeometry.BeginUpdate()
' Clear the TreeView each time the method is called.
treeViewRouteGeometry.Nodes.Clear()
For i As Integer = 0 To polylines.Length - 1
Dim NewNode As TreeNode = New TreeNode("Polyline Length for CFRoute [" + System.Convert.ToString(i + 1) + "] = " + polylines(i).Length.ToString())
treeViewRouteGeometry.Nodes.Add(NewNode)
Dim pointCollection As IPointCollection = polylines(i)
For j As Integer = 0 To pointCollection.PointCount - 1 - 1
Dim point As IPoint = pointCollection.Point(j)
treeViewRouteGeometry.Nodes(i).Nodes.Add(New TreeNode("Point [" + System.Convert.ToString(j + 1) + "]: " + point.X.ToString() + "," + point.Y.ToString()))
Next j
Next i
' Check if Route Geometry has been generated
If polylines.Length = 0 Then
Dim NewNode As TreeNode = New TreeNode("CFRoute Geometry not generated")
treeViewRouteGeometry.Nodes.Add(NewNode)
End If
' Begin repainting the TreeView.
treeViewRouteGeometry.ExpandAll()
treeViewRouteGeometry.EndUpdate()
End Sub
''' <summary>
''' Create a property set for NALocation
''' </summary>
Private Function CreateLocationPropertySet(ByVal serverContext As IServerContext, ByVal name As String, ByVal X As Object, ByVal Y As Object, ByVal sr As ISpatialReference) As IPropertySet
Dim propSet As IPropertySet = serverContext.CreateObject("esriSystem.PropertySet")
propSet.SetProperty("Name", name)
propSet.SetProperty("X", X)
propSet.SetProperty("Y", Y)
propSet.SetProperty("SpatialReference", sr)
Return propSet
End Function
''' <summary>
''' This function
''' - sets the server and solver parameters
''' - populates the Incidents/facilities NALocations
''' - solve the problem to find the closest facilities to incidents
''' - gets and displays the server results (map, directions, etc.)
''' </summary>
Private Sub cmdSolve_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSolve.Click
Me.Cursor = Cursors.WaitCursor
Dim serverContext As IServerContext = Nothing
Try
' Get ServerContext and NAServer
serverContext = GetMapServerContext()
Dim naServer As INAServer = GetNAServer(serverContext)
' Get SolverParams
Dim solverParams As INAServerSolverParams = naServer.GetSolverParameters(cboNALayers.Text)
' Set Solver params
SetINASolverSettings(solverParams)
SetSolverSpecificInterface(solverParams)
SetServerSolverParams(solverParams, serverContext)
' Load Locations
LoadLocations(solverParams, serverContext)
'Solve the Closest Facility problem
Dim solverResults As INAServerSolverResults = Nothing
solverResults = naServer.Solve(solverParams)
'Get NAServer results in the tab controls
OutputResults(solverParams, solverResults)
Catch exception As Exception
MessageBox.Show(exception.Message, "An error has occurred")
Finally
' Release the ServerContext
If Not serverContext Is Nothing Then
serverContext.ReleaseContext()
End If
End Try
Me.Cursor = Cursors.Default
End Sub
End Class