// GET: /Download/       
        public string JustDownload(OsmConfig myConfigToDownload)
        {
            string dbName = ConfigurationManager.AppSettings["DatabaseConnection"];
            string datasetName = System.IO.Path.Combine(dbName, myConfigToDownload.FeatureDataSet);

            AppLogs logs = new AppLogs();

            logs.AddLog("DOWNLOADLOGS", "Start Downloading");

            try
            {
                if (SyncState.CanSyncDataset(datasetName))
                {
                    SyncDataGP(myConfigToDownload);
                }
                else
                {
                    DownloadDataGP(myConfigToDownload);
                }
                return null;
            }
            catch (Exception e)
            {
                logs.AddLog("DOWNLOADLOGS", "ERROR: Just Download raised exception " + e.Message);
                return "ERROR: Just Download raised exception " + e.Message;
            }
            finally
            {
                logs.AddLog("DOWNLOADLOGS", "Finished Downloading");
            }
        }
        private void SyncDataGP(OsmConfig myConfigToDownload)
        {
            string sGpUrl = "";

            if (Request != null)
                sGpUrl = "http://" + Request.Url.Host + "/" + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() +
                    "/rest/services/OSM_on_AGS/GPServer/Sync%20OSM%20Data%20Serverside";
            else
            {
                string smyHost = myConfigToDownload.FeatureService.Substring(0, myConfigToDownload.FeatureService.ToLower().IndexOf("/arcgis/rest"));

                sGpUrl = smyHost + "/" + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() +
                    "/rest/services/OSM_on_AGS/GPServer/Sync%20OSM%20Data%20Serverside";
            }

            ESRI.ArcGIS.Client.Tasks.Geoprocessor geoprocessorTask = new
                ESRI.ArcGIS.Client.Tasks.Geoprocessor(sGpUrl);

            List<ESRI.ArcGIS.Client.Tasks.GPParameter> parameters = new List<ESRI.ArcGIS.Client.Tasks.GPParameter>();

            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPString("Start_Time_for_Diff_Files", ""));
            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPBoolean("Load_updates_only_inside_current_AOI", true));
            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPString("Name_of_Sync_Feature_Dataset", myConfigToDownload.FeatureDataSet));

            AppLogs logs = new AppLogs();
            ESRI.ArcGIS.Client.Tasks.JobInfo info = null;

            try
            {
              info = geoprocessorTask.SubmitJob(parameters);
            }
            catch (Exception e)
            {
              logs.AddLog("DOWNLOADLOGS", "SyncDataGP Exception " + e.Message);
              if (info != null)
              {
                for (int i = 0; i < info.Messages.Count; i++)
                {
                  logs.AddLog("DOWNLOADLOGS", "Exception: SyncDataGP messages " + info.Messages[i].Description);
                }
              }
            }

            while (info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobSucceeded &&
                   info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {
              Thread.Sleep(2000);
              info = geoprocessorTask.CheckJobStatus(info.JobId);
            }

            if (info.JobStatus == ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {
              for (int i = 0; i < info.Messages.Count; i++)
              {
                logs.AddLog("DOWNLOADLOGS", "JobFailed: SyncDataGP messages " + info.Messages[i].Description);
              }
              throw new ApplicationException("JobFailed: Please view logs for details");
            }
        }
        private void RunOneSync(OsmConfig config)
        {
            try
            {
                // This Upload controller will also do a download
                Controllers.UploadController upload = new Controllers.UploadController();
                upload.Index(config.ID);
            }
            catch { }

            config.LastTimeRunned = RunnerLog.lastRun = DateTime.Now;
        }
        public ActionResult Create(OsmConfig osmconfig)
        {
            // Check if the first character is a number
            Regex regex = new Regex("[0-9]");
            string sFirstDataSetCharacter = osmconfig.FeatureDataSet.Substring(0, 1);
            if (regex.IsMatch(sFirstDataSetCharacter) == true)
            {
                ViewBag.mxdList = OSMWeb.Utils.Config.GetListFromConfig("MxdList");
                ViewBag.refreshList = OSMWeb.Utils.Config.GetListFromConfig("RefreshInterval");

                ViewBag.AlphaCheck = "DataSet name cannot begin with a number";
                return View(osmconfig);
            }

            if (osmconfig.Password == null)
                osmconfig.Password = "";
            if (osmconfig.Username == null)
                osmconfig.Username = "";

            osmconfig.LastTimeRunned = DateTime.Now;

            if (ModelState.IsValid)
            {
                osmconfig.ID = Guid.NewGuid().ToString();
                context.OsmConfigs.Add(osmconfig);
                context.SaveChanges();

                // Download the database
                return RedirectToAction("Index",
                    new RouteValueDictionary(
                        new { controller = "Download", action = "Index", DataBaseObjectID = osmconfig.ID }));

            }
            else
            {
                osmconfig.ID = Guid.NewGuid().ToString();
            }

            return View(osmconfig);
        }
        public ActionResult Edit(OsmConfig osmconfig)
        {
            if (ModelState.IsValid)
            {
                if (osmconfig.ID.Contains("test") == true)
                {
                    context.OsmConfigs.Add(osmconfig);
                    context.SaveChanges();

                    return RedirectToAction("Index",
                        new RouteValueDictionary(
                            new { controller = "Download", action = "Index", DataBaseObjectID = osmconfig.ID }));
                }
                else
                {
                    context.Entry(osmconfig).State = EntityState.Modified;
                    context.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            return View(osmconfig);
        }
        private string SetTargetDatasetParamGP(OsmConfig myConfigToDownload)
        {
            string DatabaseConnectionConfig = ConfigurationManager.AppSettings["DatabaseConnection"];

            if (DatabaseConnectionConfig.ToLower().Contains(".gdb"))
                bUseSDE = false;

            // Check the database exist
            if (System.IO.File.Exists(DatabaseConnectionConfig) == false)
            {
                if (System.IO.Directory.Exists(DatabaseConnectionConfig) == false)
                {
                    ViewBag.TitleReturn = "The download cannot be completed";
                    ViewBag.Result = "Connection to the database does not exist";
                    return null;
                }
            }

            if (DatabaseConnectionConfig.ToLower().Contains(".sde") == true)
                DatabaseConnectionConfig += "\\";

            return DatabaseConnectionConfig + myConfigToDownload.FeatureDataSet;
        }
        /// <summary>
        /// Calling the rest end points for the GP
        /// </summary>
        /// <param name="myConfigToDownload"></param>
        private void DownloadDataGP(OsmConfig myConfigToDownload)
        {
            string sPort = ":6080";
            string sGpUrl = string.Empty;
            if (Request != null)
            {
                sGpUrl = "http://" + Request.Url.Host + sPort + "/" 
                    + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() 
                    + "/rest/services/OSM_on_AGS/GPServer/Download%20OSM%20Data%20Serverside";
            }
            else
            {
                string smyHost = myConfigToDownload.FeatureService.Substring(0, myConfigToDownload.FeatureService.ToLower().IndexOf("/arcgis/rest"));
                sGpUrl = smyHost + "/" + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() +
                    "/rest/services/OSM_on_AGS/GPServer/Download%20OSM%20Data%20Serverside";
            }

            ESRI.ArcGIS.Client.Tasks.Geoprocessor geoprocessorTask = new
                ESRI.ArcGIS.Client.Tasks.Geoprocessor(sGpUrl);

            List<ESRI.ArcGIS.Client.Tasks.GPParameter> parameters = new List<ESRI.ArcGIS.Client.Tasks.GPParameter>();

            string[] myExtent = myConfigToDownload.Extent.Split(',');

            ESRI.ArcGIS.Client.Geometry.PointCollection pointCollect = new ESRI.ArcGIS.Client.Geometry.PointCollection();

            // X1 Y1
            pointCollect.Add(new
                ESRI.ArcGIS.Client.Geometry.MapPoint(WebMercator.FromWebMercatorX(Convert.ToDouble(myExtent[0])),
                                    WebMercator.FromWebMercatorY(Convert.ToDouble(myExtent[1]))));
            // X2 Y1
            pointCollect.Add(new
                ESRI.ArcGIS.Client.Geometry.MapPoint(WebMercator.FromWebMercatorX(Convert.ToDouble(myExtent[2])),
                                    WebMercator.FromWebMercatorY(Convert.ToDouble(myExtent[1]))));
            // X2 Y2
            pointCollect.Add(new
                ESRI.ArcGIS.Client.Geometry.MapPoint(WebMercator.FromWebMercatorX(Convert.ToDouble(myExtent[2])),
                                    WebMercator.FromWebMercatorY(Convert.ToDouble(myExtent[3]))));
            // X1 Y2
            pointCollect.Add(new
                ESRI.ArcGIS.Client.Geometry.MapPoint(WebMercator.FromWebMercatorX(Convert.ToDouble(myExtent[0])),
                                    WebMercator.FromWebMercatorY(Convert.ToDouble(myExtent[3]))));
            // X1 Y1
            pointCollect.Add(new
                ESRI.ArcGIS.Client.Geometry.MapPoint(WebMercator.FromWebMercatorX(Convert.ToDouble(myExtent[0])),
                                    WebMercator.FromWebMercatorY(Convert.ToDouble(myExtent[1]))));

            ESRI.ArcGIS.Client.Geometry.Polygon polygon = new ESRI.ArcGIS.Client.Geometry.Polygon();
            polygon.Rings.Add(pointCollect);
            polygon.SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(4326);

            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPFeatureRecordSetLayer("Feature_Set", polygon));
            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPString("Name_of_OSM_Dataset", myConfigToDownload.FeatureDataSet));

            AppLogs logs = new AppLogs();
            ESRI.ArcGIS.Client.Tasks.GPExecuteResults results = null;
            ESRI.ArcGIS.Client.Tasks.JobInfo info = null;
            try
            {   
                //results = geoprocessorTask.Execute(parameters);

                info = geoprocessorTask.SubmitJob(parameters);
            }
            catch (Exception e)
            {
                logs.AddLog("DOWNLOADLOGS", "Exception " + e.Message);
                if ( info != null )
                {
                    for (int i = 0; i < info.Messages.Count; i++)
                        logs.AddLog("DOWNLOADLOGS", "Exception: DownloadDataGP messages " + info.Messages[i].Description);
                }

                //logs.AddLog("DOWNLOADLOGS", "JobWaiting  " + info.Messages[info.Messages.Count-1].Description);                    
            }

            while (info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobSucceeded &&
                   info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {                
                Thread.Sleep(2000);
                info = geoprocessorTask.CheckJobStatus(info.JobId);
            }            

            if (info.JobStatus == ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {
                for (int i = 0; i < info.Messages.Count; i++)
                {
                    logs.AddLog("DOWNLOADLOGS", "JobFailed: DownloadDataGP messages " + info.Messages[i].Description);                    
                }
                throw new ApplicationException("JobFailed: Please view logs for details");
            }
        }
        /// <summary>
        /// Do upload using the ArcGIS GP
        /// </summary>
        /// <param name="sUsername"></param>
        /// <param name="sPassword"></param>
        /// <param name="sFeatureDataSet"></param>
        public void DoUploadGP(string sUsername, string sPassword, string sFeatureDataSet, OsmConfig myConfigToDownload)
        {
            string sGpUrl;

            if (Request != null)
                sGpUrl = "http://" + Request.Url.Host + ":6080/" + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() +
                    "/rest/services/OSM_on_AGS/GPServer/Upload%20OSM%20Data%20Serverside";
            else if ( myConfigToDownload != null )
            {
                string smyHost = myConfigToDownload.FeatureService.Substring(0, myConfigToDownload.FeatureService.ToLower().IndexOf("/arcgis/rest"));
                sGpUrl = smyHost + "/" + System.Configuration.ConfigurationManager.AppSettings["ArcGISInstance"].ToString() +
                    "/rest/services/OSM_on_AGS/GPServer/Upload%20OSM%20Data%20Serverside";
            }
            else
                sGpUrl = "http://localhost:6080/ArcGIS/rest/services/OSM_on_AGS/GPServer/Upload%20OSM%20Data%20Serverside";

            ESRI.ArcGIS.Client.Tasks.Geoprocessor geoprocessorTask = new
                ESRI.ArcGIS.Client.Tasks.Geoprocessor(sGpUrl);

            List<ESRI.ArcGIS.Client.Tasks.GPParameter> parameters = new List<ESRI.ArcGIS.Client.Tasks.GPParameter>();

            string sCredentials = OSMWeb.Utils.StringManipulation.EncodeTo64(sUsername + ":" + sPassword);
            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPString("OSM_login_credentials", sCredentials));
            parameters.Add(new ESRI.ArcGIS.Client.Tasks.GPString("Name_of_Upload_Feature_Dataset", sFeatureDataSet));
            parameters.Add(new
                ESRI.ArcGIS.Client.Tasks.GPString("Comment_describing_the_upload_content",
                System.Configuration.ConfigurationManager.AppSettings["UploadComment"].ToString() +
                sFeatureDataSet + " at " + DateTime.Now.ToString()));

            AppLogs logs = new AppLogs();
            ESRI.ArcGIS.Client.Tasks.JobInfo info = null;
            try
            {
                info = geoprocessorTask.SubmitJob(parameters);
            }
            catch (Exception e)
            {
                logs.AddLog("DOWNLOADLOGS", "DoUploadGP Exception " + e.Message);
                if (info != null)
                {
                    for (int i = 0; i < info.Messages.Count; i++)
                        logs.AddLog("DOWNLOADLOGS", "DoUploadGP Exception: DoUploadGP messages " + info.Messages[i].Description);
                }
            }

            while (info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobSucceeded &&
                   info.JobStatus != ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {
                Thread.Sleep(2000);
                info = geoprocessorTask.CheckJobStatus(info.JobId);
            }

            if (info.JobStatus == ESRI.ArcGIS.Client.Tasks.esriJobStatus.esriJobFailed)
            {
                for (int i = 0; i < info.Messages.Count; i++)
                {
                    logs.AddLog("DOWNLOADLOGS", "JobFailed: DoUploadGP messages " + info.Messages[i].Description);
                }
                throw new ApplicationException("DoUploadGP JobFailed: Please view logs for details");
            }
        }