/// <summary>
 /// Display Feature Service default symbol
 /// </summary>
 /// <param name="obj"></param>
 private void ShowSymbol(FeatureLayerAttributes obj)
 {
     if (obj != null)
       {
     if (obj.drawingInfo != null)
     {
       if (obj.drawingInfo.renderer.symbol != null)
       {
     if (obj.drawingInfo.renderer.symbol.imageData != null)
     {
       //within the JSON response is the serialized image data, use the provided helper function to deserialize it
       System.Drawing.Image image = RequestAndResponseHandler.DeserializeImage(obj.drawingInfo.renderer.symbol.imageData);
       pictureBox1.Image = image;
     }
     else
       pictureBox1.Image = null;
       }
       else
     pictureBox1.Image = null;
     }
     else
       pictureBox1.Image = null;
       }
 }
        /// <summary>
        /// Organization feature services, all of them (NB: for all Organization user accounts!)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Connect_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
              string formattedRequest = string.Empty;
              string jsonResponse = string.Empty;

              listBox1.Items.Clear();

              //get the root directory of the service
              string rootURL = txtFeatureServices.Text;

              //check to see if we have an instantiated dictionary to store the attributes
              if (_featureServiceAttributesDataDictionary == null)
              {
            _featureServiceAttributesDataDictionary = new Dictionary<string, FeatureLayerAttributes>();
            _featureServiceRequestAndResponse = new Dictionary<string, string>();
              }
              else
              {
            _featureServiceAttributesDataDictionary.Clear();
            _featureServiceRequestAndResponse.Clear();
              }

              //query for ServiceLayers
              ServiceCatalog serviceCatalogDataContract = RequestAndResponseHandler.GetServiceCatalog(rootURL, _token, out formattedRequest, out jsonResponse);

              //Users on a trial period will be using services1 server, on failure resend to services server in case they have a full account.
              if (serviceCatalogDataContract.services == null)
              {
            rootURL = rootURL.Replace("services1", "services");
            serviceCatalogDataContract = RequestAndResponseHandler.GetServiceCatalog(rootURL, _token, out formattedRequest, out jsonResponse);

            if (serviceCatalogDataContract.services == null)
            {
              this.Cursor = Cursors.Default;
              return;
            }

            txtFeatureServices.Text = rootURL;
              }

              //display the call and response to the user
              ShowRequestResponseStrings(formattedRequest, jsonResponse);

              bool executedOnce = false;
              string serviceURL = string.Empty;
              string serviceRequest = string.Empty;
              string serviceResponse = string.Empty;

              foreach (Service service in serviceCatalogDataContract.services)
              {
            //I am only interested in FeatureServices THAT HAVE BEEN SHARED so only get the attributes for this kind of layer
            if (service.type == "FeatureServer")
            {
              //create the entire url string for the layer so we can make the query for attributes
              serviceURL = string.Format("{0}{1}/{2}/0/", rootURL, service.name,service.type);

              //Feature Layer Attributes
              FeatureLayerAttributes featLayerAttributes = RequestAndResponseHandler.GetFeatureServiceAttributes(serviceURL, _token, out serviceRequest, out serviceResponse);

              //store the request and response so that we can display it to the user when they click each feature service in the list
              _featureServiceRequestAndResponse.Add(service.name, serviceRequest + "$" + serviceResponse);

              //store the attributes
              _featureServiceAttributesDataDictionary.Add(service.name, featLayerAttributes);

              if (executedOnce == false)
              {
            _featureLayerAttributes = featLayerAttributes;

            //display the default symbol
            ShowSymbol(featLayerAttributes);

            if (featLayerAttributes == null)
            {
              this.Cursor = Cursors.Default;
              return;
            }

            //populate the Field Names
            if(featLayerAttributes.fields != null)
              PopulateFieldsList(featLayerAttributes.fields);

            //show feature service extent
            if(featLayerAttributes.extent != null)
              PopulateExtentValues(featLayerAttributes.extent);

            lblSelectedFS.Text = "FS: " + featLayerAttributes.name;
              }

              //lets get the data for the feature service
              //Todo
              string url = string.Format("http://services1.arcgis.com/{0}/arcgis/rest/services/{1}/FeatureServer?f=pjson", _organizationID, service.name);

              _featureServiceInfo = RequestAndResponseHandler.GetDataContractInfo(url, DataContractsEnum.FeatureServiceInfo, out jsonResponse) as FeatureServiceInfo;

              //lets store the name of the featureLayer into the listbox
              ListViewItem item = new ListViewItem();
              item.Text = service.name;
              item.Tag = _featureServiceInfo;
              listBox1.Items.Add(item);

              if (executedOnce == false)
              {
            txtSupportedFunctions.Text = _featureServiceInfo.capabilities;
            executedOnce = true;
              }
            }
              }
              listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
              EnableControls(true);
              this.Cursor = Cursors.Default;
        }
        /// <summary>
        /// NB: This code creates a point feature service if nothing has been selected in the "My Feature Services Info -> Items combobox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddDefinitionToLayer_Click(object sender, EventArgs e)
        {
            Item item = null;
              Extent extent = null;
              Symbol symbol = null;
              Renderer renderer = null;
              DrawingInfo drawingInfo = null;
              object[] fields = null;
              Template template = null;
              EditorTrackingInfo editorTrackingInfo = null;
              AdminLayerInfoAttribute adminLayerInfo = null;
              DefinitionLayer layer = null;
              string formattedRequest = string.Empty;
              string jsonResponse = string.Empty;

              FeatureLayerAttributes featLayerAttributes = null;

              this.Cursor = Cursors.WaitCursor;

              //NB: From the Items combobox if you have a feature service selected, this is the attribute table structure that will be used for the
              //creation of the new service. Otherwise create a new featureLayerAttributes class as set up in this code.
              //
              if (chkbxUseSelectedFS.Checked)
              {
            string[] concatenatedText = cboItems.Text.Split(':');
            string split = concatenatedText[1].Replace(" ID", "");
            if (_myOrganizationalContent.TryGetValue(cboItems.Text, out item))
              if(item != null)
            if(item.url != null)
              featLayerAttributes = RequestAndResponseHandler.GetFeatureServiceAttributes(item.url, _token, out formattedRequest, out jsonResponse);

            try
            {
              if (featLayerAttributes == null)
            _featureServiceAttributesDataDictionary.TryGetValue(split.Trim(), out _featureLayerAttributes);
            }
            catch { }
              }

              if (featLayerAttributes == null)
            if (_featureLayerAttributes != null)
              featLayerAttributes = _featureLayerAttributes;
            else
              featLayerAttributes = new FeatureLayerAttributes();

              //ensure that we have all that we need for a successful feature layer attributes push
              //
              if(featLayerAttributes.extent != null)
            extent = featLayerAttributes.extent;
              else
              {
            //write in your default extent values here:
            extent = new Extent()
            {
              xmin = -14999999.999999743,
              ymin = 1859754.5323447795,
              xmax = -6199999.999999896,
              ymax = 7841397.327701188,
              spatialReference = new SpatialReference() { wkid = 102100,  latestWkid = 3857 },
            };
              }

              if (featLayerAttributes.drawingInfo != null)
            drawingInfo = featLayerAttributes.drawingInfo;
              else
              {
            symbol = new PointSymbol()
            {
              type = "esriPMS",
              url = "RedSphere.png",
              imageData = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQBQYWludC5ORVQgdjMuNS4xTuc4+QAAB3VJREFUeF7tmPlTlEcexnve94U5mANQbgQSbgiHXHINlxpRIBpRI6wHorLERUmIisKCQWM8cqigESVQS1Kx1piNi4mW2YpbcZONrilE140RCTcy3DDAcL/zbJP8CYPDL+9Ufau7uqb7eZ7P+/a8PS8hwkcgIBAQCAgEBAICAYGAQEAgIBAQCAgEBAICAYGAQEAgIBAQCDx/AoowKXFMUhD3lQrioZaQRVRS+fxl51eBTZUTdZ41U1Rox13/0JF9csGJ05Qv4jSz/YPWohtvLmSKN5iTGGqTm1+rc6weICOBRbZs1UVnrv87T1PUeovxyNsUP9P6n5cpHtCxu24cbrmwKLdj+osWiqrVKhI0xzbmZ7m1SpJ+1pFpvE2DPvGTomOxAoNLLKGLscZYvB10cbYYjrJCb7A5mrxleOBqim+cWJRakZY0JfnD/LieI9V1MrKtwokbrAtU4Vm0A3TJnphJD4B+RxD0u0LA7w7FTE4oprOCMbklEGNrfdGf4IqnQTb4wc0MFTYibZqM7JgjO8ZdJkpMln/sKu16pHZGb7IfptIWg389DPp9kcChWODoMuDdBOhL1JgpisbUvghM7AqFbtNiaFP80RLnhbuBdqi0N+1dbUpWGde9gWpuhFi95yL7sS7BA93JAb+Fn8mh4QujgPeTgb9kAZf3Apd2A+fXQ38yHjOHozB1IAJjOSEY2RSIwVUv4dd4X9wJccGHNrJ7CYQ4GGjLeNNfM+dyvgpzQstKf3pbB2A6m97uBRE0/Ergcxr8hyqg7hrwn0vAtRIKIRX6Y2pMl0RhIj8co9nBGFrvh55l3ngU7YObng7IVnFvGS+BYUpmHziY/Ls2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Qtu+BWjdY4n2nZboTbfCmKcCnRyDO/YmyLPnDlHvjDH8G6zhS9/wlEnYR7X00fWrFYuWdVI0ZpuhcbcczW/R2qdAcz6t/bRov4mONeaaoYl+p22rHF0bVNAmKtBvweIXGxNcfFH8eNlC4m6wMWMusEnKpn5hyo48pj9gLe4SNG9QoGGLAk8z5XiaJUd99u8122/IpBA2K9BGg2vWWKAvRYVeLzEa7E1R422m2+MsSTem97nSYnfKyN6/mzATv7AUgqcMrUnmaFlLX3ysM0fj+t/b5lQLtK22QEfyAmiSLKFZpUJ7kBRPXKW4HqCYynWVHKSG2LkyZex1uO1mZM9lKem9Tx9jjY5iNEYo0bKMhn7ZAu0r6H5PpLXCAq0rKJClSjSGynE/QIkrQYqBPe6S2X+AJsY2Ped6iWZk6RlL0c2r5szofRsO9R5S1IfQLRCpQL1aifoYFerpsbkuTImaUJXuXIDiH6/Ys8vm3Mg8L2i20YqsO7fItKLcSXyn0kXccclVqv3MS6at9JU/Ox+ouns+SF6Z4cSupz7l8+z1ucs7LF1AQjOdxfGZzmx8Iu1TRcfnrioICAQEAgIBgYBAQCAgEBAICAQEAgIBgYBAQCAgEBAICAQEAv8H44b/6ZiGvGAAAAAASUVORK5CYII=",
              contentType = "image/png",
              color = null,
              width = 15,
              height = 15,
              angle = 0,
              xoffset = 0,
              yoffset = 0
            };

            renderer = new PointRenderer()
            {
              type = "simple",
              symbol = symbol,
              label = "",
              description = ""
            };

            drawingInfo = new DrawingInfo()
            {
              renderer = renderer,
              labelingInfo = null
            };
              }

              if (featLayerAttributes.fields != null)
            fields = featLayerAttributes.fields;
              else
              {
            Field field = new Field()
            {
              name = "Longitude",
              type = "esriFieldTypeDouble",
              alias = "Longitude",
              sqlType = "sqlTypeFloat",
              nullable = true,
              editable = true,
              domain = null,
              defaultValue = null
            };

            Field field2 = new Field()
            {
              name = "Latitude",
              type = "esriFieldTypeDouble",
              alias = "Latitude",
              sqlType = "sqlTypeFloat",
              nullable = true,
              editable = true,
              domain = null,
              defaultValue = null
            };

            FieldString field3 = new FieldString()
            {
              name = "Name",
              type = "esriFieldTypeString",
              alias = "Name",
              sqlType = "sqlTypeNVarchar",
              length = 256,
              nullable = true,
              editable = true,
              domain = null,
              defaultValue = null
            };

            FieldString field4 = new FieldString()
            {
              name = "Address",
              type = "esriFieldTypeString",
              alias = "Address",
              sqlType = "sqlTypeNVarchar",
              length = 256,
              nullable = true,
              editable = true,
              domain = null,
              defaultValue = null
            };

            //DO NOT CHANGE PROPERTIES BELOW
            Field fieldFID = new Field()
            {
              name = "FID",
              type = "esriFieldTypeInteger",
              alias = "FID",
              sqlType = "sqlTypeInteger",
              nullable = false,
              editable = false,
              domain = null,
              defaultValue = null
            };

            //object array so that we can contain different types within.
            //Field type double for example does not contain a length parameter. Hence we need different field type
            //representation. Unexpected properties for data types will cause a failure on the server end.
            fields = new object[5] { field, field2, field3, field4, fieldFID };
              }

              if (featLayerAttributes.templates != null)
               template = featLayerAttributes.templates[0];
              else
              {
            template = new Template()
            {
              name = "New Feature",
              description = "",
              drawingTool = "esriFeatureEditToolPoint",
              prototype = new Prototype()
              {
            attributes = new Attributes()
              }
            };
              }

              editorTrackingInfo = new EditorTrackingInfo()
              {
            enableEditorTracking = false,
            enableOwnershipAccessControl = false,
            allowOthersToUpdate = true,
            allowOthersToDelete = true
              };

              adminLayerInfo = new AdminLayerInfoAttribute()
              {
            geometryField = new GeometryField()
            {
              name = "Shape",
              srid = 102100
            }
              };

              layer = new DefinitionLayer()
              {
            currentVersion  = featLayerAttributes != null ? featLayerAttributes.currentVersion : 10.11,
            id = 0,
            name = featLayerAttributes != null ? featLayerAttributes.name != null ? featLayerAttributes.name : txtFeatureServiceName.Text : txtFeatureServiceName.Text,
            type = featLayerAttributes != null ? featLayerAttributes.type != null ? featLayerAttributes.type : "Feature Layer" : "Feature Layer",
            displayField  = featLayerAttributes != null ? featLayerAttributes.displayField != null ? featLayerAttributes.displayField : "" : "",
            description = "",
            copyrightText  = featLayerAttributes != null ? featLayerAttributes.copyrightText != null ? featLayerAttributes.copyrightText : "" : "",
            defaultVisibility  = featLayerAttributes != null ? featLayerAttributes.defaultVisibility != null ? featLayerAttributes.defaultVisibility : true : true,
            relationships  = featLayerAttributes != null ? featLayerAttributes.relationShips != null ? featLayerAttributes.relationShips : new object[]{} : new object[] { },
            isDataVersioned  = featLayerAttributes != null ? featLayerAttributes.isDataVersioned : false,
            supportsRollbackOnFailureParameter = true,
            supportsAdvancedQueries = true,
            geometryType = featLayerAttributes != null ? featLayerAttributes.geometryType != null ? featLayerAttributes.geometryType : "esriGeometryPoint" : "esriGeometryPoint",
            minScale = featLayerAttributes != null ? featLayerAttributes.minScale : 0,
            maxScale  = featLayerAttributes != null ? featLayerAttributes.maxScale : 0,
            extent = extent,
            drawingInfo = _javaScriptSerializer.Serialize(drawingInfo),
            allowGeometryUpdates  = featLayerAttributes != null ? featLayerAttributes.allowGeometryUpdates != null ? featLayerAttributes.allowGeometryUpdates : true : true,
            hasAttachments  = featLayerAttributes != null ? featLayerAttributes.hasAttachments : false,
            htmlPopupType  = featLayerAttributes != null ? featLayerAttributes.htmlPopupType != null ? featLayerAttributes.htmlPopupType : "esriServerHTMLPopupTypeNone" : "esriServerHTMLPopupTypeNone",
            hasM  = featLayerAttributes != null ? featLayerAttributes.hasM : false,
            hasZ  = featLayerAttributes != null ? featLayerAttributes.hasZ : false,
            objectIdField  = featLayerAttributes != null ? featLayerAttributes.objectIdField != null ? featLayerAttributes.objectIdField : "FID" : "FID",
            globalIdField  = featLayerAttributes != null ? featLayerAttributes.globalIdField != null ? featLayerAttributes.globalIdField : "" : "",
            typeIdField = featLayerAttributes != null ? featLayerAttributes.typeIdField != null ? featLayerAttributes.typeIdField : "" : "",
            fields = fields,
            types = featLayerAttributes != null ? featLayerAttributes.types != null ? featLayerAttributes.types : new object[0] : new object[0],
            templates = new Template[1] { template },
            supportedQueryFormats  = featLayerAttributes != null ? featLayerAttributes.supportedQueryFormats != null ? featLayerAttributes.supportedQueryFormats: "JSON" : "JSON",
            hasStaticData  = featLayerAttributes != null ? featLayerAttributes.hasStaticData : false,
            maxRecordCount  = 2000,//featLayerAttributes != null ? featLayerAttributes.maxRecordCount != null ? featLayerAttributes.maxRecordCount : 200000 : 200000,
            capabilities = featLayerAttributes != null ? featLayerAttributes.capabilities != null ? featLayerAttributes.capabilities : "Query,Editing,Create,Update,Delete" : "Query,Editing,Create,Update,Delete",
            //editorTrackingInfo = editorTrackingInfo,
            adminLayerInfo = adminLayerInfo
              };

              DefinitionLayer[] layers = new DefinitionLayer[1] { layer };

              AddDefinition definition = new AddDefinition()
              {
            layers = layers
              };

              string serviceEndPoint = "http://services1.arcgis.com/"; //NB: Trial Account endpoint!!!!
              string serviceEndPoint2 = "http://services.arcgis.com/";

              string requestURL = string.Format("{0}{1}/arcgis/admin/services/{2}.FeatureServer/AddToDefinition", serviceEndPoint, _organizationID, _featureServiceCreationResponse.Name);

              bool b = RequestAndResponseHandler.AddToFeatureServiceDefinition(requestURL, definition, _token, txtOrgURL.Text, out formattedRequest, out jsonResponse);

              if (!b)
              {
            requestURL = string.Format("{0}{1}/arcgis/admin/services/{2}.FeatureServer/AddToDefinition", serviceEndPoint2, _organizationID, _featureServiceCreationResponse.Name);
            b = RequestAndResponseHandler.AddToFeatureServiceDefinition(requestURL, definition, _token, txtOrgURL.Text, out formattedRequest, out jsonResponse);
              }

              ShowRequestResponseStrings(formattedRequest, jsonResponse);

              lblSuccess.Text = b == true ? "true" : "false";

              this.Cursor = Cursors.Default;
        }