public override Score ReadScore() { // at first we need to load the binary file system // from the GPX container var fileSystem = new GpxFileSystem(); fileSystem.FileFilter = s => s == GpxFileSystem.ScoreGpif; fileSystem.Load(_data); // convert data to string var data = fileSystem.Files[0].Data; var xml = Std.ToString(data); // lets set the fileSystem to null, maybe the garbage collector will come along // and kick the fileSystem binary data before we finish parsing fileSystem.Files = null; fileSystem = null; // the score.gpif file within this filesystem stores // the score information as XML we need to parse. var parser = new GpxParser(); parser.ParseXml(xml); parser.Score.Finish(); return(parser.Score); }
public static GpxParser GetGpxParser(string gpxPath) { gpxPath = gpxPath.ToLower().Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); GpxParser parser = HttpContext.Current.Cache[gpxPath] as GpxParser; if (parser == null) { if (!File.Exists(gpxPath)) { return(null); } parser = new GpxParser(); parser.Parse(gpxPath); HttpContext.Current.Cache.Add( gpxPath, parser, new CacheDependency(new string[] { gpxPath, HttpContext.Current.Server.MapPath("Map.aspx") }), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } return(parser); }
public static void GenerateTrackCode(GpxParser parser, HttpResponse response, bool addScriptTags) { if (addScriptTags) { response.Write("<script type=\"text/javascript\">\r\n"); } response.Write("function addTracks(){\r\n"); if (parser != null) { foreach (Track trk in parser.Tracks) { response.Write(string.Format(@" track = []; track['name'] = '{0}'; track['desc'] = '{1}'; track['clickable'] = true; track['width'] = 3; track['opacity'] = 0.9; track['outline_color'] = '#000000'; track['outline_width'] = 0; track['fill_color'] = '#E60000'; track['fill_opacity'] = 0; trkSeg = []; ", trk.Name, trk.Description)); foreach (TrackSegment seg in trk.Segments) { TrackPoint[] reducedPoints = seg.ReducedPoints; for (int i = 0; i < reducedPoints.Length - 1; i++) { TrackPoint p1 = reducedPoints[i]; TrackPoint p2 = reducedPoints[i + 1]; string color = ColorProvider.GetColorString(p1.ele, parser.MinElevation, parser.MaxElevation); //devo usare InvariantCulture per avere il punto come separatore dei decimali response.Write(string.Format( "trkSeg.push({{ color:'{0}', 'p1': {{ 'lat':{1}, 'lon': {2} }}, 'p2': {{ 'lat':{3}, 'lon': {4} }} }});\r\n", color, p1.lat.ToString(System.Globalization.CultureInfo.InvariantCulture), p1.lon.ToString(System.Globalization.CultureInfo.InvariantCulture), p2.lat.ToString(System.Globalization.CultureInfo.InvariantCulture), p2.lon.ToString(System.Globalization.CultureInfo.InvariantCulture) )); } } response.Write("GV_Draw_Track(trkSeg);"); } } response.Write("}\r\n"); if (addScriptTags) { response.Write("</script>\r\n"); } }
protected void Page_Load(object sender, EventArgs e) { try { string routeName = Request.QueryString["Route"]; if (!IsPostBack) { Route r = DBHelper.GetRoute(routeName); if (r != null) { string gpxFile = PathFunctions.GetGpxPathFromRouteName(routeName); parser = Helper.GetGpxParser(gpxFile); if (parser != null) { parser.LoadPhothos(); } Title = r.Title; } } bool editMode = Request.QueryString["EditMode"] == "true"; GenerateCustomOptions(editMode); ChooseRoute.Visible = editMode; if (editMode && FileUploadGpx.HasFile) { try { GpxParser p = new GpxParser(); p.Parse(FileUploadGpx.FileContent); if (p.Tracks.Count == 0) { return; } parser = p; } catch { } } if (parser == null) { parser = GpxParser.FromSession(routeName); } else { parser.ToSession(routeName); } } finally { MapContainer.Visible = parser != null; } }
public void GenerateMarkers() { Response.Write("<script type=\"text/javascript\">\r\n"); Response.Write("function addMarkers(){\r\n"); foreach (Route r in Routes) { string url = r.GetRouteUrl(editMode); string gpxFile = PathFunctions.GetGpxPathFromRouteName(r.Name); GpxParser parser = Helper.GetGpxParser(gpxFile); if (parser == null) { continue; } //TrackPoint p = parser.Tracks[0].Segments[0].Points[0]; GenericPoint p = parser.MediumPoint; string color = r.Draft ? "red" : "blue"; string title = r.Title.Replace("'", "\\'") + (r.Draft ? " (bozza)" : ""); string name = r.Name; string description = string.Format("<iframe scrolling=\"no\" frameborder=\"no\" src=\"/RouteData.aspx?name={0}\"/>", r.Name); string icon = r.Draft ? "/Images/draft_marker.png" : ""; string imageFolder = PathFunctions.GetImagePathFromGpx(gpxFile); string imageFile = Path.Combine(imageFolder, string.IsNullOrEmpty(r.Image) ? "" : r.Image); if (!File.Exists(imageFile)) { string[] files = Directory.GetFiles(imageFolder, "*.jpg"); if (files.Length > 0) { imageFile = files[0]; } else { imageFile = ""; } } string thumbFile = imageFile.Length == 0 ? "" : PathFunctions.GetThumbFile(imageFile); string photo = thumbFile.Length == 0 ? "" : PathFunctions.GetUrlFromPath(thumbFile, false).Replace("'", "\\'"); Response.Write(string.Format( "GV_Draw_Marker({{ lat: {0}, lon: {1}, name: '{2}', desc: '{3}', color: '{4}', icon: '{5}', photo: '{6}', url: '{7}', route_name:'{8}', draw_track: true }});\r\n", p.lat.ToString(System.Globalization.CultureInfo.InvariantCulture), p.lon.ToString(System.Globalization.CultureInfo.InvariantCulture), title, description, color, icon, photo, url, name)); } Response.Write("}\r\n"); Response.Write("</script>\r\n"); }
protected void Page_Load(object sender, EventArgs e) { if (string.IsNullOrEmpty(RouteName)) { RouteName = Path.GetFileName(Page.MapPath(".")); } Route r = DBHelper.GetRoute(RouteName); if (r == null) { return; } GpxParser parser = r.Parser; string routeLenght = Math.Round(parser.Distance3D / 1000, 1).ToString(CultureInfo.InvariantCulture); string routeTotalHeight = Convert.ToInt32(parser.TotalClimb).ToString(); string routeMaxHeight = Convert.ToInt32(parser.MaxElevation).ToString(); string routeMinHeight = Convert.ToInt32(parser.MinElevation).ToString(); Page.Header.Title = r.Title; if (HideTitle) { Title.Visible = false; } else { Title.InnerText = r.Title; } MTBUser user = DBHelper.LoadUser(r.OwnerId); if (user != null) { Owner.InnerText = user.DisplayName; } Lenght.InnerText = routeLenght + " Km"; //TotalHeight.InnerText = routeTotalHeight + " m"; MaxHeight.InnerText = routeMaxHeight + " m"; MinHeight.InnerText = routeMinHeight + " m"; Cycle.InnerText = r.Cycling.ToString() + "%"; Difficulty.InnerText = r.Difficulty; Difficulty.Attributes["title"] = Helper.GetDifficultyExplanation(r.Difficulty); int votes = 0; double w = DBHelper.GetMediumRank(r, out votes); RankIndicator.Style.Add(HtmlTextWriterStyle.Width, Convert.ToInt16(w * 10) + "px"); RankIndicator.Style.Add(HtmlTextWriterStyle.Height, "20px"); RankIndicator.Style.Add(HtmlTextWriterStyle.BackgroundColor, "blue"); RankIndicator.Style.Add(HtmlTextWriterStyle.Display, "inline"); RankIndicator.Style.Add(HtmlTextWriterStyle.Position, "absolute"); RankLabel.InnerText = string.Format("Valutazione ({0} voti):", votes); RankDetailLink.NavigateUrl = "~/Routes/RouteRankDetail.aspx?RouteName=" + r.Name; RankDetailLink.Target = "RouteDetail" + r.Id; }
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { return; } if (string.IsNullOrEmpty(RouteName)) { RouteName = Path.GetFileName(Page.MapPath(".")); } string gpxFullPath = PathFunctions.GetGpxPathFromRouteName(RouteName); GpxParser parser = Helper.GetGpxParser(gpxFullPath); if (parser == null) { return; } MapLink.NavigateUrl = string.Format("~/Routes/Map.aspx?Route={0}", RouteName); ProfileImage.Src = Helper.GenerateProfileFile(gpxFullPath); int countryCode = 0; countryCode = parser.CountryCode; string zipPath = parser.ZippedFile; HyperLinkToGps.NavigateUrl = PathFunctions.GetUrlFromPath(zipPath, true); if (countryCode != 0) { MeteoFrame.Attributes["src"] = string.Format("http://www.ilmeteo.it/script/meteo.php?id=free&citta={0}", countryCode); } else { MeteoFrame.Visible = false; } FBLike.Attributes["src"] = string.Format( "http://www.facebook.com/widgets/like.php?href={0}", HttpUtility.UrlEncode(Page.Request.Url.ToString())); MTBUser user = LoginState.User; if (user == null) { Rank.SelectedIndex = -1; } else { Rank r = DBHelper.GetRank(user.Id, GetRoute().Id); Rank.SelectedIndex = r == null ? -1 : r.RankNumber - 1; } }
private void RefreshGpsLocations() { GpsLocations.Clear(); foreach (string FilePath in Directory.GetFiles(Environment.CurrentDirectory + "\\Data\\GPS", "*.csv")) { GpsLocations.AddRange(GpsCsvParser.GetLocations(FilePath)); } foreach (string FilePath in Directory.GetFiles(Environment.CurrentDirectory + "\\Data\\GPS", "*.gpx")) { GpsLocations.AddRange(GpxParser.GetLocations(FilePath)); } }
protected void ButtonDelete_Click(object sender, EventArgs e) { string routeName = RouteName.Value; try { if (string.IsNullOrEmpty(routeName)) { return; } //non posso eliminare una traccia che appartiene ad un alro utente //(se mai riesco a editarla) if (route != null && route.OwnerId != LoginState.User.Id) { return; } string path = PathFunctions.GetRoutePathFromName(routeName); TryDeleting(path); path = PathFunctions.GetWorkingPath(path); TryDeleting(path); if (route != null) { DBHelper.DeleteRoute(route); } GpxParser.RemoveFromSession(routeName); UploadedImages.RemoveFromSession(routeName); //forza il ricaricamento della pagina Response.Redirect(Request.Url.ToString(), true); } catch (Exception ex) { Log.Add("Error deleting route '{0}': '{1}'", routeName, ex.ToString()); ScriptManager.RegisterStartupScript(this, GetType(), "ErrorDeleting", string.Format("alert('Errore durante l'eliminazione: {0}.');", ex.Message), true); } }
public static async Task <Guid> RunOrchestrator( [OrchestrationTrigger] IDurableOrchestrationContext context) { (var userId, var rawGpxData) = context.GetInput <(Guid, string)>(); var parsedGpx = GpxParser.Parse(new StringReader(rawGpxData)); // todo - also upload the file to raw storage! // todo - and record the raw file location in the uploaded cache function below. var config = SettingsManager.GetCredentials(); // todo this doesn't work. probably just move these configs for Azure Fxn var cosmosWriter = new UploadHandler(config.EndPoint, config.AuthKey, config.CosmosDatabase, config.CosmosContainer, config.StaticDataCosmosContainer); var tripHandler = new TripProcessorHandler(cosmosWriter); var plusCodeRanges = TripProcessorHandler.GetPlusCodeRanges(parsedGpx); tripHandler = await context.CallActivityAsync <TripProcessorHandler>("GpxFileUpload_WarmCache", (parsedGpx, tripHandler)); // parallel tracks: upload raw while also computing overlaps. var overlapComputeParams = (parsedGpx, userId, plusCodeRanges, tripHandler); var overlappingNodesTask = context.CallActivityAsync <HashSet <UserNodeCoverage> >("GpxFileUpload_OverlappingNodes", overlapComputeParams); var uploadRawTask = context.CallActivityAsync("GpxFileUpload_UploadRawRun", (parsedGpx, userId, tripHandler)); Task.WaitAll(overlappingNodesTask, uploadRawTask); var overlappingNodes = overlappingNodesTask.Result; // upload overlapping nodes var uploadCacheTask = context.CallActivityAsync("GpxFileUpload_UploadCache", (overlappingNodes, tripHandler)); var updateUserWayCoverage = context.CallActivityAsync("GpxFileUpload_UpdateUserWayCoverage", (overlappingNodes, userId, plusCodeRanges, tripHandler)); Task.WaitAll(uploadCacheTask, updateUserWayCoverage); // upload summary await context.CallActivityAsync("GpxFileUpload_UpdateUserSummaryAsync", (userId, tripHandler)); return(userId); }
protected void ButtonSave_Click(object sender, EventArgs e) { string routeName = RouteName.Value; try { if (string.IsNullOrEmpty(routeName)) { return; } //non posso salvare una traccia che appartiene ad un alro utente //(se mai riesco a editarla) if (route != null && route.OwnerId != LoginState.User.Id) { return; } //calcolo l'immagine principale UploadedImages list = UploadedImages.FromSession(RouteName.Value); mainImage = ""; foreach (MyRadioButton btn in buttons) { if (btn.Checked) { mainImage = Path.GetFileName(btn.Image.File); break; } } if (route == null) { route = new Route(); } //assegno i dati al record route.Image = mainImage; route.Name = routeName; route.OwnerId = LoginState.User.Id; int c = 0; if (int.TryParse(TextBoxCiclyng.Text, out c)) { route.Cycling = c; } route.Title = TextBoxTitle.Text; route.Description = TextBoxDescription.Text; route.Difficulty = TextBoxDifficulty.Text; //salvo il file gpx GpxParser parser = GpxParser.FromSession(routeName); if (parser != null) { string gpxFile = PathFunctions.GetGpxPathFromRouteName(routeName); string path = Path.GetDirectoryName(gpxFile); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } parser.Save(gpxFile); } //salvo le immagini string imageFolder = PathFunctions.GetImagePathFromRouteName(routeName); if (!Directory.Exists(imageFolder)) { Directory.CreateDirectory(imageFolder); } foreach (UploadedImage ui in list) { ui.SaveTo(imageFolder); } //elimino una eventuale cache Helper.ClearImageCache(imageFolder); //forzo la generazione dei thumbnails Helper.GetImageCache(imageFolder); bool published = CheckBoxPublished.Checked; route.Draft = !published; //salvo il record DBHelper.SaveRoute(route); if (published) { //mando una mail agli utenti registrati string msg = string.Format("Ciao biker!<br/>L'utente {0} ha inserito o modificato il percorso<br/><a target=\"route\" href=\"{1}\">{2}</a><br/>Scarica il tracciato e vieni a provarlo!<br/><br/>MTB Scout", LoginState.User.DisplayName, "http://www.mtbscout.it" + route.GetRouteUrl(false), route.Title ); foreach (MTBUser u in DBHelper.Users) { if (u.SendMail) { Helper.SendMail(u.EMail, null, null, "Inserimento/modifica percorso", msg, true); } } } ScriptManager.RegisterStartupScript(this, GetType(), "MessageOK", "alert('Informazioni salvate correttamente.');", true); } catch (Exception ex) { Log.Add("Error saving route '{0}': '{1}'", routeName, ex.ToString()); ScriptManager.RegisterStartupScript(this, GetType(), "Error", string.Format("alert('Errore durante il salvataggio: {0}.');", ex.Message.Replace("'", "\\'")), true); } }
private async Task OnAddActivity() { var fileData = await CrossFilePicker.Current.PickFile(); await Task.Delay(TimeSpan.FromSeconds(1)); if (fileData == null || !fileData.FileName.EndsWith("gpx")) { return; } var result = await _dialogs.PromptAsync(new PromptConfig { Title = "Agregar actividad", Message = "Ingresa el nombre de la actividad", OkText = "Aceptar" }); var dbConnection = App.SqliteCon; var document = new XmlDocument(); var base64Encoded = Convert.ToBase64String(fileData.DataArray);; using (var stream = new MemoryStream(fileData.DataArray)) { document.Load(stream); } var recorrido = new Recorrido() { Nombre = result.Value, Fecha_hora = GpxParser.GetDateTime() }; int idRecorrido = await dbConnection.InsertRecorridoAsync(recorrido); GpxParser.SetCurrentDoc(document); var points = GpxParser.ParseDoc(idRecorrido); foreach (var punto in points) { dbConnection.InsertPunto(punto); } var json = JsonConvert.SerializeObject(new { User = Preferences.Get(Config.UserId, "mvega", Config.SharedName), Nombre = result.Value, IdTipoActividad = 1, Recorrido = base64Encoded, Fecha = GpxParser.GetDateTime(), Duracion = GpxParser.GetTotalTime(points), Kilometros = GpxParser.PointsToDistanceInKm(points), EsEvento = false }); var response = await Connection.Post(Urls.Actividades, json, 120); if (!response.Succeeded) { _dialogs.Alert("Ocurrió un error al sincronizar datos"); } _dialogs.Toast("Actividad sincronizada correctamente"); }