private void DeleteImage() { UploadedImages.DeleteById(GetImageId()); RadioModes.SelectedValue = "new"; LoadExternalNameDropdown(); UpdateUi(); }
public static void ServeImage(string externalName) { var request = HttpContext.Current.Request; var lastModDate = UploadedImages.GetImageChangeTimeByExternalName(externalName); if (lastModDate == null) { Utility.Signal404(); return; } lastModDate = new DateTime(lastModDate.Value.Ticks, DateTimeKind.Utc); // First check if the image has been modified var ifModifiedSinceHeader = request.Headers["If-Modified-Since"]; var isModified = true; // assume modified unless we prove otherwise if (!IsNullOrWhiteSpace(ifModifiedSinceHeader) && DateTime.TryParse(ifModifiedSinceHeader, null, DateTimeStyles.AdjustToUniversal, out var ifModifiedSince)) { isModified = false; // change our assumption // If mod date is greater, we need to check for insignificant (< 1 sec) // difference, because of lossy date conversions. if (lastModDate > ifModifiedSince) { isModified = lastModDate - ifModifiedSince > TimeSpan.FromSeconds(1); } } ServeImageContent(externalName, lastModDate.Value, isModified); }
protected void Page_Load(object sender, EventArgs e) { string routeName = Request.QueryString["Route"]; UploadedImages list = UploadedImages.FromSession(routeName); string temporaryFolder = PathFunctions.GetTempPath(); for (int i = 0; i < Request.Files.Count; i++) { try { HttpPostedFile file = Request.Files[i]; //creo un nuovo file in session string filePath = Path.Combine(temporaryFolder, string.Format("{0}-{1}.jpg", (list.Count + 1).ToString("000"), routeName)); UploadedImage ui = new UploadedImage(filePath, file.InputStream); if (string.IsNullOrEmpty(ui.Description)) { ui.Description = Path.GetFileNameWithoutExtension(file.FileName); } list.Add(ui); } catch { //file non valido, mancato upload! } } }
protected override bool Update(object newValue) { if (Column != "ImageChanged" && Column != "ImageUpdated" && Column != "ImageId" && Column != "DeleteImage") { UploadedImages.UpdateColumn(UploadedImages.GetColumn(Column), newValue, ThisPage.GetImageId()); } return(true); }
protected override string GetCurrentValue() { switch (Column) { case "ImageChanged": case "ImageUpdated": case "DeleteImage": return("False"); case "ImageId": return(ThisPage.ControlUploadImageImageId.Text); default: return(ToDisplay(UploadedImages.GetColumn(UploadedImages.GetColumn(Column), ThisPage.GetImageId()))); } }
private void LoadExternalNameDropdown() { var first = new List <SimpleListItem> { new SimpleListItem { Text = "<select the external name of an image to update>", Value = "0" } }; var items = UploadedImages.GetAllKeysData() .Select(r => new SimpleListItem { Text = r.ExternalName, Value = r.Id.ToString() }); Utility.PopulateFromList(SelectExternalName, first.Union(items)); }
//Upload file protected void upload_onclick(object sender, EventArgs e) { if (Page.IsValid) { HttpFileCollection hfc = Request.Files; for (int i = 0; i < hfc.Count; i++) { HttpPostedFile file = hfc[i]; AltariaImage temp_ai = new AltariaImage(new Bitmap(file.InputStream), file.FileName); ai.Add(temp_ai); //add uploaded file to session Session.Add(file.FileName, temp_ai); } UploadedImages.DataSource = ai; step2.Visible = true; UploadedImages.DataBind(); } }
private static void ServeImageContent(string externalName, DateTime lastModDate, bool isModified) { var response = HttpContext.Current.Response; var maxAge = new TimeSpan(0, 0, 0); // force a server query always var expiration = DateTime.UtcNow + maxAge; if (!isModified) { response.StatusCode = 304; response.StatusDescription = "Not Modified"; } response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetETag('"' + lastModDate.Ticks.ToString(CultureInfo.InvariantCulture) + '"'); response.Cache.SetLastModified(lastModDate); response.Cache.SetMaxAge(maxAge); response.Cache.SetExpires(expiration); response.Cache.SetSlidingExpiration(false); response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); if (isModified) // serve actual image { var blob = UploadedImages.GetImageByExternalName(externalName); if (blob == null) { Utility.Signal404(); } else { // we get the content type from the actual image var contentType = GetContentType(blob); response.ContentType = contentType; response.BinaryWrite(blob); } } else // tell browser to use cached version { response.AddHeader("Content-Length", "0"); } response.End(); }
private void SetupSampleImage() { var id = GetImageId(); if (id == 0) { PreviewImage.Visible = false; return; } PreviewImage.Visible = true; var blob = UploadedImages.GetImage(id); using (var memoryStream = new MemoryStream(blob, 0, blob.Length)) { var image = System.Drawing.Image.FromStream(memoryStream); PreviewSize.InnerText = $"{image.Width}x{image.Height}"; } SampleImage.Src = UrlManager.GetSiteUri($"/image/{ControlUploadImageExternalName.Text}{ControlUploadImageImageType.Text}").ToString(); }
private bool UploadAction(string filePath) { var uploadParams = new ImageUploadParams { File = new FileDescription(filePath), Colors = true, Backup = true, AccessMode = "public", UseFilename = true }; var result = _cloudinary.Upload(uploadParams); if (result.Error != null) { FailedUploads.Enqueue(filePath); _logger.LogWarning($"Upload failed for {filePath} at {DateTime.Now.ToLongDateString()}"); return(false); } UploadedImages.Add(filePath); PhotosUrls.Add(result.SecureUri.AbsoluteUri); _logger.LogInformation($"Image with id: {result.PublicId} was uploaded at {DateTime.Now.ToLongDateString()} with accesible url: {result.SecureUri.AbsoluteUri}"); return(true); }
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); } }
private void BuildImageControls() { string tableId = "TableImages"; Control c = UpdatePanelImages.ContentTemplateContainer.FindControl(tableId); if (c != null) { UpdatePanelImages.ContentTemplateContainer.Controls.Remove(c); } UploadedImages list = UploadedImages.FromSession(RouteName.Value); Table table = new Table(); table.ID = tableId; table.Style[HtmlTextWriterStyle.Position] = "relative"; table.Style[HtmlTextWriterStyle.MarginLeft] = "auto"; table.Style[HtmlTextWriterStyle.MarginRight] = "auto"; table.Style[HtmlTextWriterStyle.TextAlign] = "center"; UpdatePanelImages.ContentTemplateContainer.Controls.Add(table); TableRow row = null; int col = 0; for (int i = 0; i < list.Count; i++) { UploadedImage ui = list.GetAt(i); if (ui.IsDeleted) { continue; } if (col == 0) { row = new TableRow(); table.Rows.Add(row); } TableCell cell = new TableCell(); row.Cells.Add(cell); cell.CssClass = "ImageCell"; cell.Width = Unit.Percentage(33.33333); Panel container = new Panel(); container.Style[HtmlTextWriterStyle.Display] = "inline-block"; cell.Controls.Add(container); string fileName = Path.GetFileName(ui.File); if (string.IsNullOrEmpty(mainImage)) { mainImage = fileName; } MyImageButton ib = new MyImageButton(ui); ib.ID = "IB_" + fileName; ib.ImageUrl = "~/Images/Recycle.png"; ib.ToolTip = "Elimina immagine"; ib.Click += new ImageClickEventHandler(ib_Click); ib.CssClass = "DeleteImage"; ib.CausesValidation = false; ib.Attributes["onmouseout"] = "normalDeleteImage(this);"; ib.Attributes["onmouseover"] = "hoverDeleteImage(this);"; container.Controls.Add(ib); UpdatePanel panel = new UpdatePanel(); panel.ChildrenAsTriggers = true; panel.UpdateMode = UpdatePanelUpdateMode.Conditional; container.Controls.Add(panel); System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image(); img.ImageUrl = string.Format("~/RouteImage.axd?Route={0}&Image={1}", RouteName.Value, HttpUtility.UrlEncode(ui.File)); img.Style[HtmlTextWriterStyle.PaddingLeft] = img.Style[HtmlTextWriterStyle.PaddingRight] = "20px"; img.Style[HtmlTextWriterStyle.PaddingTop] = "20px"; panel.ContentTemplateContainer.Controls.Add(img); TextBox tb = new TextBox(); tb.Style[HtmlTextWriterStyle.Display] = "block"; tb.Width = Unit.Pixel(200); tb.ID = "I_" + Path.GetFileName(ui.File); tb.Text = ui.Description; tb.CausesValidation = true; descriptionMap[tb] = ui; tb.TextChanged += new EventHandler(tb_TextChanged); tb.AutoPostBack = true; tb.Style[HtmlTextWriterStyle.MarginLeft] = tb.Style[HtmlTextWriterStyle.MarginRight] = "auto"; panel.ContentTemplateContainer.Controls.Add(tb); RequiredFieldValidator val = new RequiredFieldValidator(); val.ID = "V_" + tb.ID; val.ControlToValidate = tb.ID; val.ErrorMessage = "Descrizione immagine obbligatoria!"; val.SetFocusOnError = true; val.Display = ValidatorDisplay.Dynamic; panel.ContentTemplateContainer.Controls.Add(val); MyRadioButton rb = new MyRadioButton(ui); buttons.Add(rb); rb.Style[HtmlTextWriterStyle.Display] = "block"; rb.Width = Unit.Pixel(200); rb.ID = "CB_" + fileName; rb.Text = "Immagine principale"; rb.Style[HtmlTextWriterStyle.MarginLeft] = rb.Style[HtmlTextWriterStyle.MarginRight] = "auto"; rb.Checked = fileName == mainImage; rb.CausesValidation = false; rb.EnableViewState = true; container.Controls.Add(rb); if (++col == 3) { col = 0; } } }
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); } }