Select to view content in your preferred language

How to export Survey123 data using C#

1556
2
Jump to solution
05-10-2018 08:45 AM
NicolasRoger
Frequent Contributor

I have found that there exist some python script to export Survey123 data to your computer. Is there any similar code using the C# language with the ArcGIS Runtime SDK version 100.2.1?

I am trying to follow this link: Access the ArcGIS platform—ArcGIS Runtime SDK for .NET (WPF) | ArcGIS for Developers 

But my application crash at the first line ( ArcGISPortal portal = await ArcGISPortal.CreateAsync(); )

Error code is the following:

"Une erreur s'est produite lors de l'envoi de la demande." System.Exception {System.Net.Http.HttpRequestException}

Any idea why?

EDIT: I found additionnal information about the error:

Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )

EDIT: All problems solved. Here is the complete c# code to extract and delete the data (make sure you install and reference the arcgis Runtime .Net sdk and newtonSoft.JSON):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Data;
using System.Net.Http;
using System.Threading;
using System.IO;
using System.Net;
using System.Collections.Specialized;
using Newtonsoft.Json;


namespace xFormAGO
{


    public partial class Form1 : Form
    {
        string nomUtilisateur = "yourusername";
        string motPass = "yourPassword";
        //Your service URL will be different but similar
        string ServiceUrl = @"https://services1.arcgis.com/xas33e1csd2dYTMBwrt4/ArcGIS/rest/services/service_832yf5aaa3a341fgucc03..."; //Layer 0
        string dossier = @"C:\test\";
        string fichier = "data.txt";

        public Form1()
        {
            InitializeComponent();
            WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        }

        //This button extract the data
        private async void cmdExtraction_Click(object sender, EventArgs e)
        {
            try
            {
                //Create ArcGIS Token
                var cred = await Esri.ArcGISRuntime.Security.AuthenticationManager.Current.GenerateCredentialAsync(
                                                                new Uri("https://www.arcgis.com/sharing/rest"),
                                                                nomUtilisateur,
                                                                motPass) as ArcGISTokenCredential;

                //Build POST request
                string reponseStr;
                using (var wb = new WebClient())
                {
                    //Request parameter. This one just download all data and Fields
                    var requete = new NameValueCollection();
                    requete["where"] = "1=1";
                    requete["f"] = "json";
                    requete["outFields"] = "*";
                    requete["token"] = cred.Token; //Important! Must be present

                    //Send request and wait for answer
                    var response = wb.UploadValues(ServiceUrl + "query", "POST", requete);
                    reponseStr = Encoding.UTF8.GetString(response); //Translate the answer to a JSON STRING
                }
                File.WriteAllText(dossier + fichier, reponseStr); //Export the JSON string into a text file
                Rootobject dataResults = JsonConvert.DeserializeObject<Rootobject>(reponseStr); //Build the object containing the data. This line will crash for you here. Use google to understand how to convert a JSON string to a C# object. Or see the notes at the end of this code.
                //Use this object to manipulate your data as you wish
            }
            catch (Exception exp)
            {
                throw new Exception(exp.Message);
            }
        }

        //This button delete the data
        private async void cmdSupprimer_Click(object sender, EventArgs e)
        {
            //Create ArcGIS Token
            var cred = await Esri.ArcGISRuntime.Security.AuthenticationManager.Current.GenerateCredentialAsync(
                                                            new Uri("https://www.arcgis.com/sharing/rest"),
                                                            nomUtilisateur,
                                                            motPass) as ArcGISTokenCredential;

            //POST request to delete data
            using (var wb = new WebClient())
            {
                //This request deletes everything in the layer 0
                var data = new NameValueCollection();
                data["where"] = "1=1";
                data["f"] = "json";
                data["token"] = cred.Token;

                var response2 = wb.UploadValues(ServiceUrl + "deleteFeatures", "POST", data);
                string responseInString = Encoding.UTF8.GetString(response2);
                //Check the value of responseInString to see if deletion was successful
            }

        }
    }


    //
    //Here you will past the content of "data.txt" that you received earlier!!!
    //Very important
    //
    //Using visual studio, you will do a special paste as follow:
    //-Open the data.txt file
    //-Copy all content
    //-Return back to visual studio and do a special "Paste as JSON format (Edition / special paste / paste JSON code as class)
    //You will then be able to use a similar line of code: Rootobject dataResults = JsonConvert.DeserializeObject<Rootobject>(reponseStr);‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Solution

Accepted Solutions
NicolasRoger
Frequent Contributor

Ok I found what was causing the error.

Here is how to solve it: Add this line at the beginning fo your code:

WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

That's it! I am now able to connect to ArcGIS portals.

I should be able to figure out the rest.

View solution in original post

0 Kudos
2 Replies
NicolasRoger
Frequent Contributor

Ok I found what was causing the error.

Here is how to solve it: Add this line at the beginning fo your code:

WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

That's it! I am now able to connect to ArcGIS portals.

I should be able to figure out the rest.

0 Kudos
NicolasRoger
Frequent Contributor

Here is the complete c# code to extract and delete the data (make sure you install and reference the arcgis Runtime .Net sdk and newtonSoft.JSON):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Data;
using System.Net.Http;
using System.Threading;
using System.IO;
using System.Net;
using System.Collections.Specialized;
using Newtonsoft.Json;


namespace xFormAGO
{


    public partial class Form1 : Form
    {
        string nomUtilisateur = "yourusername";
        string motPass = "yourPassword";
        //Your service URL will be different but similar
        string ServiceUrl = @"https://services1.arcgis.com/xas33e1csd2dYTMBwrt4/ArcGIS/rest/services/service_832yf5aaa3a341fgucc03..."; //Layer 0
        string dossier = @"C:\test\";
        string fichier = "data.txt";

        public Form1()
        {
            InitializeComponent();
            WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        }

        //This button extract the data
        private async void cmdExtraction_Click(object sender, EventArgs e)
        {
            try
            {
                //Create ArcGIS Token
                var cred = await Esri.ArcGISRuntime.Security.AuthenticationManager.Current.GenerateCredentialAsync(
                                                                new Uri("https://www.arcgis.com/sharing/rest"),
                                                                nomUtilisateur,
                                                                motPass) as ArcGISTokenCredential;

                //Build POST request
                string reponseStr;
                using (var wb = new WebClient())
                {
                    //Request parameter. This one just download all data and Fields
                    var requete = new NameValueCollection();
                    requete["where"] = "1=1";
                    requete["f"] = "json";
                    requete["outFields"] = "*";
                    requete["token"] = cred.Token; //Important! Must be present

                    //Send request and wait for answer
                    var response = wb.UploadValues(ServiceUrl + "query", "POST", requete);
                    reponseStr = Encoding.UTF8.GetString(response); //Translate the answer to a JSON STRING
                }
                File.WriteAllText(dossier + fichier, reponseStr); //Export the JSON string into a text file
                Rootobject dataResults = JsonConvert.DeserializeObject<Rootobject>(reponseStr); //Build the object containing the data. This line will crash for you here. Use google to understand how to convert a JSON string to a C# object. Or see the notes at the end of this code.
                //Use this object to manipulate your data as you wish
            }
            catch (Exception exp)
            {
                throw new Exception(exp.Message);
            }
        }

        //This button delete the data
        private async void cmdSupprimer_Click(object sender, EventArgs e)
        {
            //Create ArcGIS Token
            var cred = await Esri.ArcGISRuntime.Security.AuthenticationManager.Current.GenerateCredentialAsync(
                                                            new Uri("https://www.arcgis.com/sharing/rest"),
                                                            nomUtilisateur,
                                                            motPass) as ArcGISTokenCredential;

            //POST request to delete data
            using (var wb = new WebClient())
            {
                //This request deletes everything in the layer 0
                var data = new NameValueCollection();
                data["where"] = "1=1";
                data["f"] = "json";
                data["token"] = cred.Token;

                var response2 = wb.UploadValues(ServiceUrl + "deleteFeatures", "POST", data);
                string responseInString = Encoding.UTF8.GetString(response2);
                //Check the value of responseInString to see if deletion was successful
            }

        }
    }


    //
    //Here you will past the content of "data.txt" that you received earlier!!!
    //Very important
    //
    //Using visual studio, you will do a special paste as follow:
    //-Open the data.txt file
    //-Copy all content
    //-Return back to visual studio and do a special "Paste as JSON format (Edition / special paste / paste JSON code as class)
    //You will then be able to use a similar line of code: Rootobject dataResults = JsonConvert.DeserializeObject<Rootobject>(reponseStr);

I hope this help someone.