/// <summary> /// The stream of the thumbnail file - computed once and cached in ThumbnailData /// </summary> public byte[] ThumbnailBytes() { if (m_ThumbBytes != null) { return(m_ThumbBytes); } using (Stream s = GetInputStream()) { string szTempFile = null; try { using (System.Drawing.Image image = MFBImageInfo.DrawingCompatibleImageFromStream(s, out szTempFile)) { Info inf = MFBImageInfo.InfoFromImage(image); using (Bitmap bmp = MFBImageInfo.BitmapFromImage(inf.Image, MFBImageInfo.ThumbnailHeight, MFBImageInfo.ThumbnailWidth)) { using (MemoryStream sOut = new MemoryStream()) { bmp.Save(sOut, ImageFormat.Jpeg); m_ThumbBytes = sOut.ToArray(); } } } } finally { if (!String.IsNullOrEmpty(szTempFile) && File.Exists(szTempFile)) { File.Delete(szTempFile); } } } return(m_ThumbBytes); }
public void RemoveImage(MFBImageInfo mfbii) { List <MFBImageInfo> lst = new List <MFBImageInfo>(rgMfbii); lst.RemoveAll(mfbii2 => mfbii2.PrimaryKey.CompareOrdinal(mfbii.PrimaryKey) == 0); rgMfbii = lst.ToArray(); }
/// <summary> /// Returns the bytes of the posted file, converted if needed from HEIC. /// </summary> public byte[] CompatibleContentData() { if (TempFileName == null) { return(null); } using (FileStream fs = File.OpenRead(TempFileName)) { // Check for HEIC try { using (System.Drawing.Image img = System.Drawing.Image.FromStream(fs)) { // If we got here then the content is Drawing Compatible - i.e., not HEIC; just return contentdata fs.Seek(0, SeekOrigin.Begin); byte[] rgb = new byte[fs.Length]; fs.Read(rgb, 0, rgb.Length); return(rgb); } } catch (Exception ex) when(ex is ArgumentException) { return(MFBImageInfo.ConvertStreamToJPG(fs)); } } }
/// <summary> /// Retrieves the bytes from a data: URL /// </summary> /// <param name="szLink">The data: URL</param> /// <returns>The bytes of the PNG.</returns> public static byte[] FromDataLinkURL(string szLink) { if (String.IsNullOrEmpty(szLink)) { return(Array.Empty <byte>()); } string szSigB64 = szLink.Substring(ScribbleImage.DataURLPrefix.Length); byte[] rgbSignature = Convert.FromBase64CharArray(szSigB64.ToCharArray(), 0, szSigB64.Length); if (rgbSignature.Length > 10000) // this may not be compressed (e.g., from Android) - compress it. { using (Stream st = new MemoryStream(rgbSignature)) { using (Stream stDst = new MemoryStream()) { // This is a PNG, so no need to handle temp files/conversion. using (System.Drawing.Image image = MFBImageInfo.DrawingCompatibleImageFromStream(st)) { image.Save(stDst, System.Drawing.Imaging.ImageFormat.Png); rgbSignature = new byte[stDst.Length]; stDst.Position = 0; stDst.Read(rgbSignature, 0, (int)stDst.Length); } } } } return(rgbSignature); }
protected void ImagesRowDataBound(object sender, GridViewRowEventArgs e) { if (e != null && e.Row.RowType == DataControlRowType.DataRow) { Dictionary <string, List <MFBImageInfo> > dictRows = QueryResults; string szKey = (string)e.Row.DataItem; Controls_mfbImageList mfbil = (Controls_mfbImageList)e.Row.FindControl("mfbImageList1"); HyperLink lnk = (HyperLink)e.Row.FindControl("lnkID"); List <MFBImageInfo> lst = (dictRows.ContainsKey(szKey) ? dictRows[szKey] : null); if (lst == null || lst.Count == 0) { return; } MFBImageInfo mfbii0 = lst[0]; if (CurrentSource == MFBImageInfo.ImageClass.Flight) { ((LinkButton)e.Row.FindControl("lnkGetAircraft")).CommandArgument = szKey; ((Panel)e.Row.FindControl("pnlResolveAircraft")).Visible = true; } lnk.Text = szKey; lnk.NavigateUrl = (String.IsNullOrEmpty(m_szLinkTemplate) ? String.Empty : String.Format(CultureInfo.InvariantCulture, m_szLinkTemplate, szKey)); mfbil.ImageClass = CurrentSource; mfbil.Key = szKey; mfbil.Images = new ImageList(CurrentSource, szKey, lst.ToArray()); mfbil.Refresh(false); } }
private static void AddThumbnailToZip(MFBImageInfo mfbii, ZipArchive zip, string szFolder) { if (mfbii is null) { throw new ArgumentNullException(nameof(mfbii)); } if (zip is null) { throw new ArgumentNullException(nameof(zip)); } if (szFolder is null) { throw new ArgumentNullException(nameof(szFolder)); } string imgPath = System.Web.Hosting.HostingEnvironment.MapPath(mfbii.PathThumbnail); if (!File.Exists(imgPath)) { mfbii.DeleteFromDB(); // clean up an orphan return; } // No need to add an S3PDF to the zip file; it's just a placeholder file on the disk, and it can // potentially have a duplicate name with another PDF as well. if (mfbii.ImageType != MFBImageInfo.ImageFileType.S3PDF) { zip.CreateEntryFromFile(imgPath, szFolder + "\\" + mfbii.ThumbnailFile); } }
protected void RefreshForm() { // now add any sample aircraft pictures if (SuppressImages) { return; } int[] rgAircraft = Model.SampleAircraft(); Image img = (Image)modelView.FindControl("imgThumbSample"); img.ImageUrl = ResolveUrl("~/images/noimage.png"); // default value. Set it here instead of ascx because infinite scroll loses the location context. foreach (int acID in rgAircraft) { ImageList il = new ImageList(MFBImageInfo.ImageClass.Aircraft, acID.ToString(CultureInfo.InvariantCulture)); il.Refresh(); if (il.ImageArray.Count > 0) { MFBImageInfo mfbii = il.ImageArray[0]; ((HyperLink)modelView.FindControl("lnkImage")).NavigateUrl = mfbii.URLFullImage; img.ImageUrl = mfbii.URLThumbnail; img.AlternateText = img.ToolTip = string.Empty; break; } } }
/// <summary> /// Returns a set of MFBImageInfo objects that represent the images for this base/key pair. Results are cached. /// </summary> /// <param name="fIncludeDocs">Include PDF files?</param> /// <param name="fIncludeVids">Include videos? (true by default)</param> /// <param name="szDefault">True for a "Default" image to put at the front</param> /// <returns>Array of MFBImageInfo objects</returns> public void Refresh(bool fIncludeDocs = false, string szDefault = null, bool fIncludeVids = true) { DirectoryInfo dir = new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath(VirtPath)); List <MFBImageInfo> lstMfbii = new List <MFBImageInfo>(); if (dir != null && dir.Exists) { AddFilesToList(dir, String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}*{1}", MFBImageInfo.ThumbnailPrefix, FileExtensions.JPG), lstMfbii); if (fIncludeVids) { AddFilesToList(dir, String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}*{1}", MFBImageInfo.ThumbnailPrefixVideo, FileExtensions.JPG), lstMfbii); } if (fIncludeDocs) { AddFilesToList(dir, String.Format(System.Globalization.CultureInfo.InvariantCulture, "*{0}", FileExtensions.PDF), lstMfbii); AddFilesToList(dir, String.Format(System.Globalization.CultureInfo.InvariantCulture, "*{0}", FileExtensions.S3PDF), lstMfbii); } } dir = null; lstMfbii.Sort(); if (!String.IsNullOrEmpty(szDefault)) { MFBImageInfo mfbii = null; if ((mfbii = lstMfbii.Find(img => img.ThumbnailFile.CompareOrdinalIgnoreCase(szDefault) == 0)) != null) { lstMfbii.Remove(mfbii); lstMfbii.Insert(0, mfbii); } } rgMfbii = lstMfbii.ToArray(); }
/// <summary> /// ADMIN Migrates the full image file to S3, returns the number of bytes moved. /// </summary> /// <param name="mfbii">The image to move</param> /// <returns>The # of bytes moved, if any, -1 for failure</returns> public int ADMINMigrateToS3(MFBImageInfo mfbii) { int cBytes = 0; if (mfbii == null || !AWSConfiguration.UseS3) { return(-1); } string szPathFull = mfbii.PhysicalPathFull; if (mfbii.IsLocal) { if (mfbii.ImageType == MFBImageInfo.ImageFileType.JPEG) { mfbii.Update(); // write the meta-data to both thumbnail & full file } FileInfo fi = new FileInfo(szPathFull); cBytes += (Int32)fi.Length; MoveImageToS3(true, mfbii); return(cBytes); } return(-1); }
protected void Page_Load(object sender, EventArgs e) { string szClass = util.GetStringParam(Request, "r"); string szKey = util.GetStringParam(Request, "k"); string szThumb = util.GetStringParam(Request, "t"); MFBImageInfo.ImageClass ic = MFBImageInfo.ImageClass.Unknown; if (Enum.TryParse <MFBImageInfo.ImageClass>(szClass, out MFBImageInfo.ImageClass result)) { ic = result; } this.Title = szThumb; if (ic != MFBImageInfo.ImageClass.Unknown && !String.IsNullOrEmpty(szKey) && !String.IsNullOrEmpty(szThumb) && !szThumb.Contains("?")) // Googlebot seems to be adding "?resize=300,300 { MFBImageInfo mfbii = new MFBImageInfo(ic, szKey, szThumb); if (mfbii == null) { throw new MyFlightbookException("mfbii null in ViewPic"); } if (Request == null) { throw new MyFlightbookException("Null request in ViewPic"); } string ua = String.IsNullOrEmpty(Request.UserAgent) ? string.Empty : Request.UserAgent.ToUpperInvariant(); if (mfbii.ImageType == MFBImageInfo.ImageFileType.S3VideoMP4 && !ua.Contains("IPHONE") && !ua.Contains("IPAD")) { // For android devices, need to put it into actual HTML for it to play in-line in the browser. mfbEditableImage1.MFBImageInfo = mfbii; } else { try { Response.Redirect(mfbii.ResolveFullImage()); } catch (ArgumentException ex) { throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, "Argument Exception in ViewPic key={0}\r\nthumb={1}\r\n", szKey, szThumb), ex); } catch (System.Web.HttpUnhandledException ex) { throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, "Argument Exception in ViewPic key={0}\r\nthumb={1}\r\n", szKey, szThumb), ex); } catch (NullReferenceException ex) { throw new MyFlightbookException("Null reference on resolve full image (but where?) ", ex); } } } else { Response.Clear(); Response.StatusCode = 404; Response.End(); } }
protected override MFBImageInfo UploadForUser(string szUser, HttpPostedFile pf, string szComment) { string szTail = Request.Form["txtAircraft"]; int idAircraft = Aircraft.idAircraftUnknown; bool fUseID = util.GetIntParam(Request, "id", 0) != 0; if (String.IsNullOrEmpty(szTail)) { throw new MyFlightbookException(Resources.WebService.errBadTailNumber); } if (fUseID) { if (!int.TryParse(szTail, out idAircraft) || idAircraft == Aircraft.idAircraftUnknown) { throw new MyFlightbookException(Resources.WebService.errBadTailNumber); } } else if (szTail.Length > Aircraft.maxTailLength || szTail.Length < 3) { throw new MyFlightbookException(Resources.WebService.errBadTailNumber); } // Check if authorized for videos if (MFBImageInfo.ImageTypeFromFile(pf) == MFBImageInfo.ImageFileType.S3VideoMP4 && !EarnedGrauity.UserQualifies(szUser, Gratuity.GratuityTypes.Videos)) { throw new MyFlightbookException(Branding.ReBrand(Resources.LocalizedText.errNotAuthorizedVideos)); } UserAircraft ua = new UserAircraft(szUser); ua.InvalidateCache(); // in case the aircraft was added but cache is not refreshed. Aircraft[] rgac = ua.GetAircraftForUser(); Aircraft ac = null; if (fUseID) { ac = new Aircraft(idAircraft); } else { string szTailNormal = Aircraft.NormalizeTail(szTail); // Look for the aircraft in the list of the user's aircraft (that way you get the right version if it's a multi-version aircraft and no ID was specified // Hack for backwards compatibility with mobile apps and anonymous aircraft // Look to see if the tailnumber matches the anonymous tail ac = Array.Find <Aircraft>(rgac, uac => (String.Compare(Aircraft.NormalizeTail(szTailNormal), Aircraft.NormalizeTail(uac.TailNumber), StringComparison.CurrentCultureIgnoreCase) == 0 || String.Compare(szTail, uac.HackDisplayTailnumber, StringComparison.CurrentCultureIgnoreCase) == 0)); } if (ac == null || !ua.CheckAircraftForUser(ac)) { throw new MyFlightbookException(Resources.WebService.errNotYourAirplane); } mfbImageAircraft.Key = ac.AircraftID.ToString(System.Globalization.CultureInfo.InvariantCulture); return(new MFBImageInfo(MFBImageInfo.ImageClass.Aircraft, mfbImageAircraft.Key, pf, szComment, null)); }
private BasicMedEvent() { EventDate = DateTime.Now; EventType = BasicMedEventType.Unknown; User = Description = LastError = string.Empty; ID = -1; Images = new MFBImageInfo[0]; }
protected void btnMigrateImages_Click(object sender, EventArgs e) { int cBytesDone = 0; int cFilesDone = 0; if (!int.TryParse(txtLimitMB.Text, out int cMBytesLimit)) { cMBytesLimit = 100; } int cBytesLimit = cMBytesLimit * 1024 * 1024; if (!int.TryParse(txtLimitFiles.Text, out int cFilesLimit)) { cFilesLimit = 100; } Dictionary <string, MFBImageCollection> images = MFBImageInfo.FromDB(CurrentSource, true); List <string> lstKeys = images.Keys.ToList(); if (CurrentSource == MFBImageInfoBase.ImageClass.Aircraft || CurrentSource == MFBImageInfoBase.ImageClass.Flight) { lstKeys.Sort((sz1, sz2) => { return(Convert.ToInt32(sz2, CultureInfo.InvariantCulture) - Convert.ToInt32(sz1, CultureInfo.InvariantCulture)); }); } else { lstKeys.Sort(); } // ImageDict foreach (string szKey in lstKeys) { if (cBytesDone > cBytesLimit || cFilesDone >= cFilesLimit) { break; } AWSImageManagerAdmin im = new AWSImageManagerAdmin(); foreach (MFBImageInfo mfbii in images[szKey]) { int cBytes = im.ADMINMigrateToS3(mfbii); if (cBytes >= 0) // migration occured { cBytesDone += cBytes; cFilesDone++; } if (cBytesDone > cBytesLimit || cFilesDone >= cFilesLimit) { break; } } } lblMigrateResults.Text = String.Format(CultureInfo.CurrentCulture, Resources.Admin.MigrateImagesTemplate, cFilesDone, cBytesDone); }
// Image utilities private void AddFilesToList(DirectoryInfo dir, string szMask, List <MFBImageInfo> lst) { FileInfo[] rgFiles = dir.GetFiles(szMask); if (rgFiles != null) { foreach (FileInfo fi in rgFiles) { lst.Add(MFBImageInfo.LoadMFBImageInfo(Class, Key, fi.Name)); } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { pnlTest.Visible = true; } if (String.Compare(Request.RequestType, "POST", StringComparison.OrdinalIgnoreCase) == 0) { string szMessageType = (Request.Headers["x-amz-sns-message-type"] ?? string.Empty).ToUpperInvariant(); switch (szMessageType) { case "NOTIFICATION": SNSNotification snsNotification = ReadJSONObject <SNSNotification>(); if (String.IsNullOrEmpty(snsNotification.Signature) || snsNotification.VerifySignature()) { MFBImageInfo mfbii = new MFBImageInfo(snsNotification); // simply creating the object will do all that is necessary. } Response.Clear(); Response.Write("OK"); Response.End(); break; case "SUBSCRIPTIONCONFIRMATION": { SNSSubscriptionConfirmation snsSubscription = ReadJSONObject <SNSSubscriptionConfirmation>(); // Visit the URL to confirm it. if (snsSubscription.VerifySignature()) { using (WebClient wc = new System.Net.WebClient()) { byte[] rgdata = wc.DownloadData(snsSubscription.SubscribeURL); string szContent = System.Text.UTF8Encoding.UTF8.GetString(rgdata); } } } Response.Clear(); Response.Write("OK"); Response.End(); break; case "UNSUBSCRIBECONFIRMATION": // Nothing to do for now. break; default: // Test messages/etc. can go here. break; } } }
protected void btnUpdHdSht_Click(object sender, EventArgs e) { if (fuHdSht.HasFile) { byte[] rgb = MFBImageInfo.ScaledImage(fuHdSht.PostedFile.InputStream, 90, 90); if (rgb != null && rgb.Length > 0) { m_pf.HeadShot = rgb; m_pf.FCommit(); SetHeadShot(); } } }
protected void UpdateGrid() { Dictionary <string, MFBImageCollection> dictRows = QueryResults = MFBImageInfo.FromDB(CurrentSource, CurrentImageRowOffset, PageSize, out List <string> lstKeys); gvImages.DataSource = lstKeys; gvImages.DataBind(); int curOffset = CurrentImageRowOffset; int lastRow = CurrentImageRowOffset + dictRows.Count; lblCurrentImageRange.Text = lblCurrentImageRange2.Text = String.Format(CultureInfo.CurrentCulture, Resources.Admin.ImageRowsHeader, curOffset + 1, lastRow, TotalImageRows); btnPrevRange.Enabled = (CurrentImageRowOffset > 0); btnNextRange.Enabled = (lastRow < TotalImageRows); }
/// <summary> /// Loads the uploaded images into the specified virtual path, resets each upload control in turn /// </summary> public void ProcessUploadedImages() { if (String.IsNullOrEmpty(ImageKey)) { throw new MyFlightbookException("No Image Key specified in ProcessUploadedImages"); } if (Class == MFBImageInfo.ImageClass.Unknown) { throw new MyFlightbookException("Unknown image class in ProcessUploadedImages"); } switch (Mode) { case UploadMode.Legacy: if (m_fHasProcessed) { return; } m_fHasProcessed = true; foreach (mfbFileUpload fu in FileUploadControls) { ProcessSingleNonAjaxUpload(fu); } break; case UploadMode.Ajax: string[] rgIDs = PendingIDs.ToArray(); // make a copy of the PendingIDs, since we're going to be removing from the Pending list as we go. foreach (string szID in rgIDs) { MFBPendingImage mfbpi = (MFBPendingImage)Session[szID]; if (mfbpi == null || mfbpi.PostedFile == null) { continue; } // skip anything that isn't an image if we're not supposed to include non-image docs. if (ValidateFileType(MFBImageInfo.ImageTypeFromFile(mfbpi.PostedFile))) { mfbpi.Commit(Class, ImageKey); } // Regardless, clean up the temp file and Session.Remove(szID); // free up some memory and prevent duplicate processing. PendingIDs.Remove(szID); } RefreshPreviewList(); GC.Collect(); // could be a lot of memory used and/or temp files from the images, so clean them up. break; } }
protected void btnDeleteOrphans_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("Deleting orphaned flight images:\r\n<br />"); sb.AppendFormat(CultureInfo.CurrentCulture, "{0}\r\n<br />", MFBImageInfo.ADMINDeleteOrphans(MFBImageInfo.ImageClass.Flight)); sb.Append("Deleting orphaned endorsement images:\r\n<br />"); sb.AppendFormat(CultureInfo.CurrentCulture, "{0}\r\n<br />", MFBImageInfo.ADMINDeleteOrphans(MFBImageInfo.ImageClass.Endorsement)); sb.Append("Deleting orphaned Aircraft images:\r\n<br />"); sb.AppendFormat(CultureInfo.CurrentCulture, "{0}\r\n<br />", MFBImageInfo.ADMINDeleteOrphans(MFBImageInfo.ImageClass.Aircraft)); sb.Append("Deleting orphaned BasicMed images:\r\n<br />"); sb.AppendFormat(CultureInfo.CurrentCulture, "{0}\r\n<br />", MFBImageInfo.ADMINDeleteOrphans(MFBImageInfo.ImageClass.BasicMed)); lblDeleted.Text = sb.ToString(); }
protected void rptImg_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } Controls_mfbEditableImage c = (Controls_mfbEditableImage)e.Item.FindControl("mfbEI"); MFBImageInfo mfbii = (MFBImageInfo)e.Item.DataItem; if (String.IsNullOrEmpty(mfbii.ThumbnailFile)) { throw new MyFlightbookValidationException(String.Format(CultureInfo.CurrentCulture, "Invalid Image - empty thumbnail file: {0}", mfbii.ToString())); } c.ID = "img" + e.Item.ItemIndex.ToString(CultureInfo.InvariantCulture); }
private void ProcessSingleNonAjaxUpload(mfbFileUpload fu) { if (fu.HasFile) { // skip anything that isn't an image if we're not supposed to include non-image docs. if (!ValidateFileType(MFBImageInfo.ImageTypeFromFile(fu.PostedFile))) { return; } // Simple creation of the MFBImageInfo object will create the persisted object. MFBImageInfo _ = new MFBImageInfo(Class, ImageKey, fu.PostedFile, fu.Comment, null); } // clear the comment field now that it is uploaded. fu.Comment = string.Empty; }
/// <summary> /// Deletes the image from S3. The actual operation happens asynchronously; the result is not captured. /// </summary> /// <param name="mfbii">The image to delete</param> public static void DeleteImageOnS3(MFBImageInfo mfbii) { if (mfbii == null) { return; } try { DeleteObjectRequest dor = new DeleteObjectRequest() { BucketName = AWSConfiguration.CurrentS3Bucket, Key = mfbii.S3Key }; new Thread(new ThreadStart(() => { try { using (IAmazonS3 s3 = AWSConfiguration.S3Client()) { s3.DeleteObject(dor); if (mfbii.ImageType == MFBImageInfo.ImageFileType.S3VideoMP4) { // Delete the thumbnail too. string szs3Key = mfbii.S3Key; dor.Key = szs3Key.Replace(Path.GetFileName(szs3Key), MFBImageInfo.ThumbnailPrefixVideo + Path.GetFileNameWithoutExtension(szs3Key) + "00001" + FileExtensions.JPG); s3.DeleteObject(dor); } } } catch (Exception ex) when(ex is AmazonS3Exception) { } } )).Start(); } catch (AmazonS3Exception ex) { throw new MyFlightbookException(String.Format(CultureInfo.InvariantCulture, "Error deleting file on S3: {0}", WrapAmazonS3Exception(ex)), ex.InnerException); } catch (Exception ex) { throw new MyFlightbookException("Unknown error deleting image on S3: " + ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { string szClass = util.GetStringParam(Request, "r"); string szKey = util.GetStringParam(Request, "k"); string szThumb = util.GetStringParam(Request, "t"); MFBImageInfo.ImageClass ic = MFBImageInfo.ImageClass.Unknown; if (Enum.TryParse <MFBImageInfo.ImageClass>(szClass, out MFBImageInfo.ImageClass result)) { ic = result; } this.Title = szThumb; if (ic != MFBImageInfo.ImageClass.Unknown && !String.IsNullOrEmpty(szKey) && !String.IsNullOrEmpty(szThumb) && !szThumb.Contains("?")) // Googlebot seems to be adding "?resize=300,300 { MFBImageInfo mfbii = new MFBImageInfo(ic, szKey, szThumb); if (mfbii == null) { throw new MyFlightbookException("mfbii null in ViewPic"); } if (Request == null) { throw new MyFlightbookException("Null request in ViewPic"); } try { Response.Redirect(mfbii.ResolveFullImage()); } catch (Exception ex) when(ex is ArgumentException || ex is System.Web.HttpUnhandledException) { throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, "Argument Exception in ViewPic key={0}\r\nthumb={1}\r\n", szKey, szThumb), ex); } catch (NullReferenceException ex) { throw new MyFlightbookException("Null reference on resolve full image (but where?) ", ex); } } else { Response.Clear(); Response.StatusCode = 404; Response.End(); } }
protected void btnCleanPendingVideos_Click(object sender, EventArgs e) { List <SNSNotification> lstPending = new List <SNSNotification>(); List <int> lstFlights = new List <int>(); // Get all pending videos that are more than an hour old and create synthetic SNS notifications for them. DBHelper dbh = new DBHelper("SELECT * FROM pendingvideos pv WHERE submitted < DATE_ADD(Now(), INTERVAL -1 HOUR)"); dbh.ReadRows((comm) => { }, (dr) => { AWSETSStateMessage etsNotification = new AWSETSStateMessage() { JobId = (string)dr["jobID"], State = "COMPLETED" }; SNSNotification sns = new SNSNotification() { Message = JsonConvert.SerializeObject(etsNotification) }; lstPending.Add(sns); lstFlights.Add(Convert.ToInt32(dr["imagekey"], CultureInfo.InvariantCulture)); }); int cPending = lstPending.Count; gvVideos.DataSource = lstFlights; gvVideos.DataBind(); // Now, go through them and create each one. Should clean up as part of the process. // simply creating the object will do all that is necessary. foreach (SNSNotification sns in lstPending) { _ = new MFBImageInfo(sns); } int cRemaining = 0; dbh.CommandText = "SELECT count(*) AS numRemaining FROM pendingvideos pv WHERE submitted < DATE_ADD(Now(), INTERVAL -1 HOUR)"; dbh.ReadRow((comm) => { }, (dr) => { cRemaining = Convert.ToInt32(dr["numRemaining"], CultureInfo.InvariantCulture); }); lblPVResults.Text = String.Format(CultureInfo.CurrentCulture, "Found {0} videos orphaned, {1} now remain", cPending, cRemaining); }
protected override MFBImageInfo UploadForUser(string szUser, HttpPostedFile pf, string szComment) { int idFlight = Convert.ToInt32(Request.Form["idFlight"], CultureInfo.InvariantCulture); if (idFlight <= 0) { throw new MyFlightbookException(Resources.WebService.errInvalidFlight); } LogbookEntry le = new LogbookEntry { FlightID = idFlight }; if (!le.FLoadFromDB(le.FlightID, szUser, LogbookEntry.LoadTelemetryOption.None)) { throw new MyFlightbookException(Resources.WebService.errFlightDoesntExist); } if (le.User != szUser) { throw new MyFlightbookException(Resources.WebService.errFlightNotYours); } // Check if authorized for videos if (MFBImageInfo.ImageTypeFromFile(pf) == MFBImageInfo.ImageFileType.S3VideoMP4 && !EarnedGratuity.UserQualifies(szUser, Gratuity.GratuityTypes.Videos)) { throw new MyFlightbookException(Branding.ReBrand(Resources.LocalizedText.errNotAuthorizedVideos)); } LatLong ll = null; string szLat = Request.Form["txtLat"]; string szLon = Request.Form["txtLon"]; if (!String.IsNullOrEmpty(szLat) && !String.IsNullOrEmpty(szLon)) { ll = LatLong.TryParse(szLat, szLon, CultureInfo.InvariantCulture); } mfbImageFlight.Key = le.FlightID.ToString(CultureInfo.InvariantCulture); return(new MFBImageInfo(MFBImageInfo.ImageClass.Flight, mfbImageFlight.Key, pf, szComment, ll)); }
protected void rptFlightImages_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } MFBImageInfo mfbii = e.Item.DataItem as MFBImageInfo; Panel p = (Panel)e.Item.FindControl("pnlStatic"); if (mfbii.ImageType == MFBImageInfo.ImageFileType.S3VideoMP4 && !(mfbii is MFBPendingImage)) { ((Literal)e.Item.FindControl("litVideoOpenTag")).Text = String.Format(CultureInfo.InvariantCulture, "<video width=\"320\" height=\"240\" controls><source src=\"{0}\" type=\"video/mp4\">", mfbii.ResolveFullImage()); ((Literal)e.Item.FindControl("litVideoCloseTag")).Text = "</video>"; p.Style["max-width"] = "320px"; } else if (mfbii.WidthThumbnail > 0) { p.Style["max-width"] = mfbii.WidthThumbnail.ToString(CultureInfo.InvariantCulture); } }
private string ProcessImages() { StringBuilder szImages = new StringBuilder("["); if (Images != null) { LatLong ll; List <string> lstPhotoMarkers = new List <string>(); foreach (MFBImageInfo ii in Images) { double ratio = MFBImageInfo.ResizeRatio(MFBImageInfo.ThumbnailHeight / 2, MFBImageInfo.ThumbnailWidth / 2, ii.HeightThumbnail, ii.WidthThumbnail); if ((ll = ii.Location) != null) { lstPhotoMarkers.Add(String.Format(CultureInfo.InvariantCulture, "new MFBPhotoMarker('{0}', '{1}', {2}, {3}, '{4}', {5}, {6})", ii.URLThumbnail, ii.URLFullImage, ll.Latitude, ll.Longitude, HttpUtility.HtmlEncode(ii.Comment).JavascriptEncode(), (int)(ii.WidthThumbnail * ratio), (int)(ii.HeightThumbnail * ratio))); } } szImages.Append(String.Join(", ", lstPhotoMarkers.ToArray())); } szImages.Append("]"); return(szImages.ToString()); }
protected void ProcessClipboardImage() { // Regardless of mode, see if there's a clipboard image if (!String.IsNullOrEmpty(hImg.Value)) { try { MFBPostedFile pf = new MFBPostedFile(hImg.Value); if (ValidateFileType(MFBImageInfo.ImageTypeFromFile(pf))) { // create a pending file. string szKey = FileObjectSessionKey(pf.FileName); PendingIDs.Add(szKey); Session[szKey] = new MFBPendingImage(pf, szKey); RefreshPreviewList(); UploadComplete?.Invoke(this, new EventArgs()); } } catch (FormatException) { } // if it's bad data, just don't do anything. hImg.Value = string.Empty; // don't send it back down the wire!!! } }
/// <summary> /// Moves the full-size image to the current bucket. Actual move is done on a background thread, and the local file is deleted IF the operation is successful. /// <param name="fSynchronous">true if the call should be made synchronously; otherwise, the call returns immediately and the move is done on a background thread</param> /// <param name="mfbii">The image to move</param> /// </summary> public void MoveImageToS3(bool fSynchronous, MFBImageInfo mfbii) { if (mfbii == null) { return; } try { PutObjectRequest por = new PutObjectRequest() { BucketName = AWSConfiguration.CurrentS3Bucket, ContentType = mfbii.ImageType == MFBImageInfo.ImageFileType.JPEG ? ContentTypeJPEG : ContentTypePDF, AutoCloseStream = true, InputStream = new FileStream(mfbii.PhysicalPathFull, FileMode.Open, FileAccess.Read), Key = mfbii.S3Key, CannedACL = S3CannedACL.PublicRead, StorageClass = S3StorageClass.Standard // vs. reduced }; if (fSynchronous) { MoveByRequest(por, mfbii); } else { new Thread(new ThreadStart(() => { MoveByRequest(por, mfbii); })).Start(); } } catch (AmazonS3Exception ex) { throw new MyFlightbookException(String.Format(CultureInfo.InvariantCulture, "Error moving file to S3: {0}", WrapAmazonS3Exception(ex)), ex.InnerException); } catch (Exception ex) { throw new MyFlightbookException("Unknown error moving image to S3: " + ex.Message); } }
public static IEnumerable <MFBPhotoMarker> FromImages(IEnumerable <MFBImageInfo> rgmfbii) { if (rgmfbii == null || !rgmfbii.Any()) { return(Array.Empty <MFBPhotoMarker>()); } LatLong ll; List <MFBPhotoMarker> lst = new List <MFBPhotoMarker>(); foreach (MFBImageInfo ii in rgmfbii) { double ratio = MFBImageInfo.ResizeRatio(MFBImageInfo.ThumbnailHeight / 2, MFBImageInfo.ThumbnailWidth / 2, ii.HeightThumbnail, ii.WidthThumbnail); if ((ll = ii.Location) != null) { lst.Add(new MFBPhotoMarker() { hrefThumb = ii.URLThumbnail, hrefFull = ii.URLFullImage, latitude = ii.Location.Latitude, longitude = ii.Location.Longitude, comment = ii.Comment, height = (int)(ii.HeightThumbnail * ratio), width = (int)(ii.WidthThumbnail * ratio) }); } } return(lst); }