private void AnalyzeProfileOriginal(string key) { var profileOriginalBlob = PoliticiansImagesBlobs.GetProfileOriginal(key); if (profileOriginalBlob != null) { var dataTable = PoliticiansImagesData.GetData(key); bool nullIt = dataTable.Count == 1 && dataTable[0].ProfileOriginalDate <= dataTable[0].HeadshotDate; byte[] newBlob = null; MemoryStream memoryStream = new MemoryStream(profileOriginalBlob); Image image = Image.FromStream(memoryStream); if (nullIt) { AppendStatusText("{0}: {1}x{2} {3}->{4} [{5}:{6}]", key, image.Width, image.Height, profileOriginalBlob.Length, 0, profileOriginalBlob.Length, ImageManager.GetContentType(image).Replace("image/", "")); } else { newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 0, 0); AppendStatusText("{0}: {1}x{2} {3}->{4} [{5}:{6}]", key, image.Width, image.Height, profileOriginalBlob.Length, newBlob.Length, profileOriginalBlob.Length - newBlob.Length, ImageManager.GetContentType(image).Replace("image/", "")); File.WriteAllBytes(@"c:\ProfileOriginals\" + key + ".jpg", newBlob); } } }
private void CheckProfileContentTypeButton_Click(object sender, EventArgs e) { List <string> errors = new List <string>(); CheckProfileContentTypeButton.Enabled = false; int count = 0; var table = PoliticiansImagesData.GetAllData(); foreach (var row in table) { count++; string politicianKey = row.PoliticianKey; byte[] blob = PoliticiansImagesBlobs.GetProfileOriginalByPoliticianKey(politicianKey); if (blob != null) { string dbContentType = PoliticiansImagesData .GetProfileOriginalContentTypeByPoliticianKey(politicianKey); string actualContentType = Images.GetContentType(blob); if (dbContentType != actualContentType) { errors.Add(String.Format("PoliticianKey: {0} Database: {1} Actual: {2}", politicianKey, dbContentType == null ? "<null>" : dbContentType, actualContentType == null ? "<null>" : actualContentType)); } } } }
public string UpdateVoteUsaImage(string politicianKey, string url) { var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); using (var inputStream = response.GetResponseStream()) using (var memoryStream = new MemoryStream()) { Debug.Assert(inputStream != null, "inputStream != null"); inputStream.CopyTo(memoryStream); byte[] originalBlob; Size originalSize; if (PoliticiansImagesBlobs.GetHeadshot100(politicianKey) == null) { ImageManager.UpdateAllPoliticianImages(politicianKey, memoryStream, DateTime.UtcNow, true, out originalSize, out originalBlob); } else { ImageManager.UpdatePoliticianProfileImages(politicianKey, memoryStream, DateTime.UtcNow, true, out originalSize, out originalBlob); } } return(VotePage.GetPoliticianImageUrl(politicianKey, 300, true)); }
private static void CopyCommonBlobsToLocal(string politicianKey) { PoliticiansImagesBlobsTable table = null; try { table = PoliticiansImagesBlobs.GetCacheDataByPoliticianKey(politicianKey); } // ReSharper disable once EmptyGeneralCatchClause catch {} // suppress errors on Insert because a parallel thread may have already // copied the row into the local database try { if (table != null && table.Count == 1) { var row = table[0]; DB.VoteImagesLocal.PoliticiansImagesBlobs.Upsert(politicianKey, null, row.Profile300, row.Profile200, row.Headshot100, row.Headshot75, row.Headshot50, row.Headshot35, row.Headshot25, row.Headshot20, row.Headshot15); } else if (table != null && table.Count == 0) // negative caching { DB.VoteImagesLocal.PoliticiansImagesBlobs.Upsert(politicianKey, null, null, null, null, null, null, null, null, null, null); } } // ReSharper disable once EmptyGeneralCatchClause catch {} }
protected void ButtonNoCrop_Click(object sender, EventArgs e) { try { var politicianKey = LabelPoliticianKey.Text; // We get the current profile original, convert it to a stream, then // use it as the HeadshotOriginal image var blob = PoliticiansImagesBlobs.GetProfileOriginal(politicianKey); if (blob == null) { return; } var uploadTime = DateTime.UtcNow; var stream = new MemoryStream(blob); Size originalSize; ImageManager.UpdateAllPoliticianHeadshotImages(politicianKey, stream, uploadTime, out originalSize); CommonCacheInvalidation.ScheduleInvalidation("politicianimage", politicianKey); MarkProcessed(); UpdateRowCountAfterChange(); } catch (Exception ex) { HandleException(ex); } }
private void SetProfileContentTypeButton_Click(object sender, EventArgs e) { List <string> errors = new List <string>(); SetProfileContentTypeButton.Enabled = false; int count = 0; var table = PoliticiansImagesData.GetAllData(); foreach (var row in table) { count++; string politicianKey = row.PoliticianKey; byte[] blob = PoliticiansImagesBlobs.GetProfileOriginalByPoliticianKey(politicianKey); if (blob != null) { string contentType = Images.GetContentType(blob); if (contentType == null) { errors.Add(politicianKey); } else { PoliticiansImagesData.UpdateProfileOriginalContentTypeByPoliticianKey( contentType, politicianKey); } } } }
public static string GetPoliticianImageColumnNameByWidth(int width) { var politicianImageInfo = PoliticianImageInfoList.SingleOrDefault(info => info.MaxWidth == width); return(politicianImageInfo == null ? string.Empty : PoliticiansImagesBlobs.GetColumnName(politicianImageInfo.BlobsColumn)); }
private void FixNoPhotoImage() { string path = @"c:\Temp\NoPhoto300.png"; string key = "NoPhoto"; DateTime now = DateTime.Now; using (Stream stream = File.OpenRead(path)) { Image image = Image.FromStream(stream); var newBlob300 = ImageManager.GetResizedImageBlob(image, 300, 0); File.WriteAllBytes(@"c:\VoteImages\Profile300\" + key + ".png", newBlob300); PoliticiansImagesBlobs.UpdateProfile300(newBlob300, key); PoliticiansImagesBlobs.UpdateProfileOriginal(newBlob300, key); var newBlob200 = ImageManager.GetResizedImageBlob(image, 200, 0); File.WriteAllBytes(@"c:\VoteImages\Profile200\" + key + ".png", newBlob200); PoliticiansImagesBlobs.UpdateProfile200(newBlob200, key); var newBlob100 = ImageManager.GetResizedImageBlob(image, 100, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot100\" + key + ".png", newBlob100); PoliticiansImagesBlobs.UpdateHeadshot100(newBlob100, key); var newBlob75 = ImageManager.GetResizedImageBlob(image, 75, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot75\" + key + ".png", newBlob75); PoliticiansImagesBlobs.UpdateHeadshot75(newBlob75, key); var newBlob50 = ImageManager.GetResizedImageBlob(image, 50, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot50\" + key + ".png", newBlob50); PoliticiansImagesBlobs.UpdateHeadshot50(newBlob50, key); var newBlob35 = ImageManager.GetResizedImageBlob(image, 35, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot35\" + key + ".png", newBlob35); PoliticiansImagesBlobs.UpdateHeadshot35(newBlob35, key); var newBlob25 = ImageManager.GetResizedImageBlob(image, 25, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot25\" + key + ".png", newBlob25); PoliticiansImagesBlobs.UpdateHeadshot25(newBlob25, key); var newBlob20 = ImageManager.GetResizedImageBlob(image, 20, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot20\" + key + ".png", newBlob20); PoliticiansImagesBlobs.UpdateHeadshot20(newBlob20, key); var newBlob15 = ImageManager.GetResizedImageBlob(image, 15, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot15\" + key + ".png", newBlob15); PoliticiansImagesBlobs.UpdateHeadshot15(newBlob15, key); PoliticiansImagesData.UpdateHeadshotDate(now, key); PoliticiansImagesData.UpdateHeadshotResizeDate(now, key); PoliticiansImagesData.UpdateProfileOriginalDate(now, key); AppendStatusText("Complete"); } }
private void FixHeadshots(string key) { byte[] originalBlob = null; var logTable = LogPoliticiansImagesHeadshot.GetLatestData(key); if (logTable.Count > 0) { originalBlob = logTable[0].HeadshotOriginal; } else { originalBlob = PoliticiansImagesBlobs.GetProfileOriginal(key); } if (originalBlob != null) { MemoryStream memoryStream = new MemoryStream(originalBlob); Image image = Image.FromStream(memoryStream); var newBlob100 = ImageManager.GetResizedImageBlobAsJpg(image, 100, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot100\" + key + ".jpg", newBlob100); PoliticiansImagesBlobs.UpdateHeadshot100(newBlob100, key); var newBlob75 = ImageManager.GetResizedImageBlobAsJpg(image, 75, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot75\" + key + ".jpg", newBlob75); PoliticiansImagesBlobs.UpdateHeadshot75(newBlob75, key); var newBlob50 = ImageManager.GetResizedImageBlobAsJpg(image, 50, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot50\" + key + ".jpg", newBlob50); PoliticiansImagesBlobs.UpdateHeadshot50(newBlob50, key); var newBlob35 = ImageManager.GetResizedImageBlobAsJpg(image, 35, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot35\" + key + ".jpg", newBlob35); PoliticiansImagesBlobs.UpdateHeadshot35(newBlob35, key); var newBlob25 = ImageManager.GetResizedImageBlobAsJpg(image, 25, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot25\" + key + ".jpg", newBlob25); PoliticiansImagesBlobs.UpdateHeadshot25(newBlob25, key); var newBlob20 = ImageManager.GetResizedImageBlobAsJpg(image, 20, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot20\" + key + ".jpg", newBlob20); PoliticiansImagesBlobs.UpdateHeadshot20(newBlob20, key); var newBlob15 = ImageManager.GetResizedImageBlobAsJpg(image, 15, 0); File.WriteAllBytes(@"c:\VoteImages\Headshot15\" + key + ".jpg", newBlob15); PoliticiansImagesBlobs.UpdateHeadshot15(newBlob15, key); AppendStatusText("processed: {0}", key); } else { AppendStatusText("no original: {0}", key); } }
private static void MakeCategory(Control parent, string title, string classNamePrefix, string content1, string content2, CategoryOptions options = CategoryOptions.None) { var asLink = (options & CategoryOptions.AsLink) != 0; var isScrollable = (options & CategoryOptions.Scrollable) != 0; var createParagraphs = (options & CategoryOptions.Paragraphs) != 0; var isHeadshot = (options & CategoryOptions.Headshot) != 0; var isProfile = (options & CategoryOptions.Profile) != 0; var isPicture = isHeadshot || isProfile; var heading = new HtmlDiv().AddTo(parent, "category-heading", true); new HtmlSpan { InnerText = title }.AddTo(heading); var hasContent1 = isPicture ? PoliticiansImagesBlobs.PoliticianKeyExists(content1) : !IsNullOrWhiteSpace(content1); var hasContent2 = isPicture ? PoliticiansImagesBlobs.PoliticianKeyExists(content2) : !IsNullOrWhiteSpace(content2); var category = new HtmlDiv().AddTo(parent, classNamePrefix + "-databoxes databoxes clearfix", true); var d1 = new HtmlDiv().AddTo(category, "databox databox-1", true) as HtmlContainerControl; if (!hasContent1) { d1.AddCssClasses("no-content"); } var d2 = new HtmlDiv().AddTo(category, "databox databox-2", true) as HtmlContainerControl; if (!hasContent2) { d2.AddCssClasses("no-content"); } if (isScrollable) { d1.AddCssClasses("scrollable"); d2.AddCssClasses("scrollable"); } if (asLink) { if (!IsNullOrWhiteSpace(content1)) { new HtmlAnchor { InnerText = content1, HRef = VotePage.NormalizeUrl(content1), Target = "content" } }
private static void DeleteAllPoliticianReferences(string politicianKey) { Answers2.DeleteByPoliticianKey(politicianKey); ElectionsIncumbentsRemoved.DeleteByPoliticianKey(politicianKey); ElectionsIncumbentsRemoved.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey); ElectionsPoliticians.DeleteByPoliticianKey(politicianKey); ElectionsPoliticians.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey); OfficesOfficials.DeleteByPoliticianKey(politicianKey); OfficesOfficials.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey); PoliticiansImagesBlobs.DeleteByPoliticianKey(politicianKey); PoliticiansImagesData.DeleteByPoliticianKey(politicianKey); TempEmail.DeleteByPoliticianKey(politicianKey); }
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { switch (RunType) { case RunType.FixNoPhotoImage: FixNoPhotoImage(); break; default: // Get list of keys in PoliticiansImagesBlobs var keys = PoliticiansImagesBlobs.GetAllKeyData(0) .Select(row => row.PoliticianKey) .ToList(); foreach (string key in keys) //if (key.IsGeIgnoreCase("OHGreenDoug")) { switch (RunType) { case RunType.AnalyzeProfileOriginal: AnalyzeProfileOriginal(key); break; case RunType.ConvertProfileOriginal: ConvertProfileOriginal(key); break; case RunType.ConvertProfileImages: ConvertProfileImages(key); break; //case RunType.ConvertHeadshotImages: // ConvertHeadshotImages(key); // break; case RunType.FixHeadshots: FixHeadshots(key); break; } } break; } } catch (Exception ex) { AppendStatusText(ex.Message); } }
private void ConvertProfileOriginal(string key) { var profileOriginalBlob = PoliticiansImagesBlobs.GetProfileOriginal(key); if (profileOriginalBlob != null) { MemoryStream memoryStream = new MemoryStream(profileOriginalBlob); Image image = Image.FromStream(memoryStream); var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 1600, 1600); File.WriteAllBytes(@"c:\VoteImages\ProfileOriginal\" + key + ".jpg", newBlob); PoliticiansImagesBlobs.UpdateProfileOriginal(newBlob, key); AppendStatusText("{0}: {1} -> {2}", key, profileOriginalBlob.Length, newBlob.Length); } }
private static bool IsColumnNameProfileImage(string columnName) { var result = false; if (PoliticiansImagesBlobs.TryGetColumn(columnName, out var column)) { var politicianImageInfo = PoliticianImageInfoList.SingleOrDefault( info => info.BlobsColumn == column); if (politicianImageInfo != null) { result = politicianImageInfo.IsProfile; } } return(result); }
protected void ButtonUploadPictureProfile_ServerClick(object sender, EventArgs e) { try { var postedFile = Request.Files[ImageFileProfile.Name]; var politicianKey = LabelPoliticianKey.Text; var uploadTime = DateTime.UtcNow; if ((postedFile == null) || (postedFile.ContentLength == 0)) { return; } Size originalSize; ImageManager.UpdatePoliticianProfileImages(politicianKey, postedFile.InputStream, uploadTime, out originalSize); CommonCacheInvalidation.ScheduleInvalidation("politicianimage", politicianKey); // We only want to propagate the profile to the headshot if there // is no current Headshot -- we check Headshot100 if (PoliticiansImagesBlobs.GetHeadshot100(politicianKey) == null) { ImageManager.UpdateResizedPoliticianHeadshotImages(politicianKey, postedFile.InputStream, uploadTime, out originalSize); } var memoryStream = new MemoryStream(); postedFile.InputStream.Position = 0; postedFile.InputStream.CopyTo(memoryStream); postedFile.InputStream.Position = 0; var imageBlob = memoryStream.ToArray(); LogPoliticiansImagesOriginal.Insert(politicianKey, imageBlob, uploadTime, UserSecurityClass, UserName, 0); UpdateRowCountAfterChange(); Msg.Text = Ok("The profile image for ID " + politicianKey + " was uploaded."); } catch (Exception ex) { HandleException(ex); } }
protected void ButtonAsIs_Click(object sender, EventArgs e) { try { var politicianKey = LabelPoliticianKey.Text.Trim(); PoliticiansImagesData.GuaranteePoliticianKeyExists(politicianKey); PoliticiansImagesBlobs.GuaranteePoliticianKeyExists(politicianKey); PoliticiansImagesData.UpdateHeadshotDate(DateTime.UtcNow, politicianKey); CommonCacheInvalidation.ScheduleInvalidation("politicianimage", politicianKey); MarkProcessed(); UpdateRowCountAfterChange(); } catch (Exception ex) { HandleException(ex); } }
//private void ConvertHeadshotImages(string key) //{ // var headshotOriginalBlob = PoliticiansImagesBlobs.GetHeadshotOriginal(key); // if (headshotOriginalBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotOriginalBlob); // Image image = Image.FromStream(memoryStream); // var newBlob100 = ImageManager.GetResizedImageBlobAsJpg(image, 100, 100); // File.WriteAllBytes(@"c:\VoteImages\Headshot100\" + key + ".jpg", newBlob100); // PoliticiansImagesBlobs.UpdateHeadshot100(newBlob100, key); // var newBlob75 = ImageManager.GetResizedImageBlobAsJpg(image, 75, 75); // File.WriteAllBytes(@"c:\VoteImages\Headshot75\" + key + ".jpg", newBlob75); // PoliticiansImagesBlobs.UpdateHeadshot75(newBlob75, key); // var newBlob50 = ImageManager.GetResizedImageBlobAsJpg(image, 50, 50); // File.WriteAllBytes(@"c:\VoteImages\Headshot50\" + key + ".jpg", newBlob50); // PoliticiansImagesBlobs.UpdateHeadshot50(newBlob50, key); // var newBlob35 = ImageManager.GetResizedImageBlobAsJpg(image, 35, 35); // File.WriteAllBytes(@"c:\VoteImages\Headshot35\" + key + ".jpg", newBlob35); // PoliticiansImagesBlobs.UpdateHeadshot35(newBlob35, key); // var newBlob25 = ImageManager.GetResizedImageBlobAsJpg(image, 25, 25); // File.WriteAllBytes(@"c:\VoteImages\Headshot25\" + key + ".jpg", newBlob25); // PoliticiansImagesBlobs.UpdateHeadshot25(newBlob25, key); // var newBlob20 = ImageManager.GetResizedImageBlobAsJpg(image, 20, 20); // File.WriteAllBytes(@"c:\VoteImages\Headshot20\" + key + ".jpg", newBlob20); // PoliticiansImagesBlobs.UpdateHeadshot20(newBlob20, key); // var newBlob15 = ImageManager.GetResizedImageBlobAsJpg(image, 15, 15); // File.WriteAllBytes(@"c:\VoteImages\Headshot15\" + key + ".jpg", newBlob15); // PoliticiansImagesBlobs.UpdateHeadshot15(newBlob15, key); // AppendStatusText(key); // } // else // { // Byte[] headshotBlob; // headshotBlob = PoliticiansImagesBlobs.GetHeadshot100(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 100, 100); // File.WriteAllBytes(@"c:\VoteImages\Headshot100\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot100(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot75(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 75, 75); // File.WriteAllBytes(@"c:\VoteImages\Headshot75\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot75(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot50(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 50, 50); // File.WriteAllBytes(@"c:\VoteImages\Headshot50\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot50(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot35(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 35, 35); // File.WriteAllBytes(@"c:\VoteImages\Headshot35\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot35(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot25(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 25, 25); // File.WriteAllBytes(@"c:\VoteImages\Headshot25\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot25(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot20(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 20, 20); // File.WriteAllBytes(@"c:\VoteImages\Headshot20\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot20(newBlob, key); // } // headshotBlob = PoliticiansImagesBlobs.GetHeadshot15(key); // if (headshotBlob != null) // { // MemoryStream memoryStream = new MemoryStream(headshotBlob); // Image image = Image.FromStream(memoryStream); // var newBlob = ImageManager.GetResizedImageBlobAsJpg(image, 15, 15); // File.WriteAllBytes(@"c:\VoteImages\Headshot15\" + key + ".jpg", newBlob); // PoliticiansImagesBlobs.UpdateHeadshot15(newBlob, key); // } // } //} private void ConvertProfileImages(string key) { var profileOriginalBlob = PoliticiansImagesBlobs.GetProfileOriginal(key); if (profileOriginalBlob != null) { MemoryStream memoryStream = new MemoryStream(profileOriginalBlob); Image image = Image.FromStream(memoryStream); var newBlob300 = ImageManager.GetResizedImageBlobAsJpg(image, 300, 400); File.WriteAllBytes(@"c:\VoteImages\Profile300\" + key + ".jpg", newBlob300); PoliticiansImagesBlobs.UpdateProfile300(newBlob300, key); var newBlob200 = ImageManager.GetResizedImageBlobAsJpg(image, 200, 275); File.WriteAllBytes(@"c:\VoteImages\Profile200\" + key + ".jpg", newBlob200); PoliticiansImagesBlobs.UpdateProfile200(newBlob200, key); AppendStatusText(key); } else { var profile300Blob = PoliticiansImagesBlobs.GetProfile300(key); if (profile300Blob != null) { MemoryStream memoryStream = new MemoryStream(profile300Blob); Image image = Image.FromStream(memoryStream); var newBlob300 = ImageManager.GetResizedImageBlobAsJpg(image, 300, 400); File.WriteAllBytes(@"c:\VoteImages\Profile300\" + key + ".jpg", newBlob300); PoliticiansImagesBlobs.UpdateProfile300(newBlob300, key); } var profile200Blob = PoliticiansImagesBlobs.GetProfile200(key); if (profile200Blob != null) { MemoryStream memoryStream = new MemoryStream(profile200Blob); Image image = Image.FromStream(memoryStream); var newBlob200 = ImageManager.GetResizedImageBlobAsJpg(image, 200, 275); File.WriteAllBytes(@"c:\VoteImages\Profile200\" + key + ".jpg", newBlob200); PoliticiansImagesBlobs.UpdateProfile200(newBlob200, key); } } }
private void DoConsolidation() { try { var selectedIndex = ConsolidateSelectedIndex.Value; string selectedKey; string unselectedKey; switch (selectedIndex) { case "1": selectedKey = ConsolidateKey1.Value; unselectedKey = ConsolidateKey2.Value; break; case "2": selectedKey = ConsolidateKey2.Value; unselectedKey = ConsolidateKey1.Value; break; default: throw new VoteException("Index not 1 or 2"); } //throw new VoteException("An error"); // Politicians var selectedPolitician = Politicians.GetData(selectedKey); var unselectedPolitician = Politicians.GetData(unselectedKey); if (selectedPolitician.Count != 1) { throw new VoteException("Politician " + selectedPolitician + " not found"); } if (unselectedPolitician.Count != 1) { throw new VoteException("Politician " + unselectedKey + " not found"); } var selectedData = UpdatePoliticians(selectedIndex, selectedPolitician, unselectedPolitician); // PoliticiansImagesData and PoliticiansImagesBlobs var selectedImagesData = PoliticiansImagesData.GetData(selectedKey); var unselectedImagesData = PoliticiansImagesData.GetData(unselectedKey); var selectedImagesBlobs = PoliticiansImagesBlobs.GetData(selectedKey); var unselectedImagesBlobs = PoliticiansImagesBlobs.GetData(unselectedKey); UpdateImages(selectedIndex, selectedData, selectedKey, selectedImagesData, selectedImagesBlobs, unselectedImagesData, unselectedImagesBlobs); // Answers var selectedAnswers = Answers.GetActiveDataByPoliticianKey(selectedKey); var unselectedAnswers = Answers.GetDataByPoliticianKey(unselectedKey); UpdateAnswers(selectedKey, selectedAnswers, unselectedAnswers); // ElectionsIncumbentsRemoved var selectedIncumbentsRemoved = ElectionsIncumbentsRemoved.GetDataByPoliticianKey(selectedKey); var unselectedIncumbentsRemoved = ElectionsIncumbentsRemoved.GetDataByPoliticianKey(unselectedKey); UpdateIncumbentsRemoved(selectedKey, unselectedIncumbentsRemoved, selectedIncumbentsRemoved); // ElectionsPoliticians var selectedElectionsPoliticians = ElectionsPoliticians.GetDataByPoliticianKey(selectedKey); var unselectedElectionsPoliticians = ElectionsPoliticians.GetDataByPoliticianKey(unselectedKey); UpdateElectionsPoliticians(selectedKey, unselectedElectionsPoliticians, selectedElectionsPoliticians); // OfficesOfficials var selectedOfficesOfficials = OfficesOfficials.GetDataByPoliticianKey(selectedKey); var unselectedOfficesOfficials = OfficesOfficials.GetDataByPoliticianKey(unselectedKey); UpdateOfficesOfficials(selectedKey, unselectedOfficesOfficials, selectedOfficesOfficials); // Update everything as one transaction, politicians last PoliticiansImagesData.UpdateTable(selectedImagesData); PoliticiansImagesData.UpdateTable(unselectedImagesData); PoliticiansImagesBlobs.UpdateTable(selectedImagesBlobs); PoliticiansImagesBlobs.UpdateTable(unselectedImagesBlobs); Answers.UpdateTable(selectedAnswers); Answers.UpdateTable(unselectedAnswers); ElectionsIncumbentsRemoved.UpdateTable(unselectedIncumbentsRemoved); ElectionsPoliticians.UpdateTable(unselectedElectionsPoliticians); OfficesOfficials.UpdateTable(unselectedOfficesOfficials); Politicians.UpdateTable(selectedPolitician); Politicians.UpdateTable(unselectedPolitician); // Log LogDataChange.LogUpdate("*ConsolidatePoliticians", "*Various", unselectedKey, selectedKey, VotePage.UserName, SecurePage.UserSecurityClass, DateTime.UtcNow, selectedKey); // After the main update, refresh the LiveOfficeKey, LiveOfficeStatus and LiveElectionKey var view = PoliticiansLiveOfficeKeyView.GetData(selectedKey); if (view.Count == 1) { var keyAndStatus = PoliticianOfficeStatus.FromLiveOfficeKeyAndStatus( view[0].LiveOfficeKeyAndStatus); selectedPolitician[0].LiveOfficeKey = keyAndStatus.OfficeKey; selectedPolitician[0].LiveOfficeStatus = keyAndStatus.PoliticianStatus.ToString(); selectedPolitician[0].LiveElectionKey = keyAndStatus.ElectionKey; Politicians.UpdateTable(selectedPolitician); } ConsolidateReloaded.Value = "ok"; } catch (Exception ex) { FeedbackConsolidate.AddError("There was an unexpected error: " + ex.Message); } }
internal static byte[] GetPoliticianImage(string politicianKey, string columnName, string defaultColumnName, bool noCache) { byte[] blob; if (noCache) { // Validate the columnName and get the column enum from the columnName PoliticiansImagesBlobs.Column column; if (columnName == null || !PoliticiansImagesBlobs.TryGetColumn(columnName, out column)) { return(null); } // The following will be null if the politicianKey is bad, if the image doesn't // exist, or if a valid but non-image column name was passed blob = PoliticiansImagesBlobs.GetColumn(column, politicianKey) as byte[]; // Optional recursive call to return the appropriate NoPhoto image if // the requested image not found if (!string.IsNullOrWhiteSpace(defaultColumnName) && blob == null) { // if the defaultColumnName is invalid, use the original column if (!PoliticiansImagesBlobs.TryGetColumn(defaultColumnName, out column)) { defaultColumnName = columnName; } blob = GetPoliticianImage("NoPhoto", defaultColumnName, null, true); } } else // normal caching { // Validate the columnName and get the column enum from the columnName DB.VoteImagesLocal.PoliticiansImagesBlobs.Column column; if (columnName == null || !DB.VoteImagesLocal.PoliticiansImagesBlobs.TryGetColumn(columnName, out column)) { return(null); } // The following will be null if the politicianKey is bad, if the image doesn't // exist, or if a valid but non-image column name was passed blob = DB.VoteImagesLocal.PoliticiansImagesBlobs.GetColumn(column, politicianKey) as byte[]; // Optional recursive call to return the appropriate NoPhoto image if // the requested image not found if (!string.IsNullOrWhiteSpace(defaultColumnName) && blob == null) { // make sure the NoPhoto image has been cached if ( !DB.VoteImagesLocal.PoliticiansImagesData.PoliticianKeyExists("NoPhoto")) { CopyCommonDataToLocal("NoPhoto"); } // if the defaultColumnName is invalid, use the original column if ( !DB.VoteImagesLocal.PoliticiansImagesBlobs.TryGetColumn( defaultColumnName, out column)) { defaultColumnName = columnName; } blob = GetPoliticianImage("NoPhoto", defaultColumnName, null, false); } } return(blob); }
private static void ServeImageContent(string politicianKey, string column, string defaultColumn, DateTime lastModDate, bool isModified, bool noCache) { var response = HttpContext.Current.Response; //var maxAge = new TimeSpan(24, 0, 0); // 24 hours -- used in headers var maxAge = new TimeSpan(0, 0, 0); // force a server query always var expiration = DateTime.UtcNow + maxAge; var isProfileOriginal = column.IsEqIgnoreCase( PoliticiansImagesBlobs.GetColumnName( PoliticiansImagesBlobs.Column.ProfileOriginal)); 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 cache = HttpContext.Current.Cache; var cacheKey = "politicianImage." + politicianKey + "." + column; ApplicationCacheEntry cacheEntry = null; // We don't use memory cache for profile originals if (!noCache && !isProfileOriginal) { cacheEntry = cache.Get(cacheKey) as ApplicationCacheEntry; } if (cacheEntry != null && cacheEntry.Expiration > DateTime.UtcNow) { response.ContentType = cacheEntry.ContentType; response.BinaryWrite(cacheEntry.Blob); Interlocked.Increment(ref CurrentStatistics.ImagesServedFromMemoryCache); } else { var blob = GetPoliticianImage(politicianKey, column, defaultColumn, noCache); if (blob != null) { // we get the content type from the actual image var contentType = GetContentType(blob); response.ContentType = contentType; response.BinaryWrite(blob); if (!isProfileOriginal) { var cacheExpiration = DateTime.UtcNow.AddMinutes(MemCache.CacheExpiration); cacheEntry = new ApplicationCacheEntry { Expiration = cacheExpiration, Blob = blob, ContentType = contentType }; cache.Add(cacheKey, cacheEntry, null, cacheExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } Interlocked.Increment(ref CurrentStatistics.ImagesServedFromDisc); } } } else // tell browser to use cached version { response.AddHeader("Content-Length", "0"); Interlocked.Increment(ref CurrentStatistics.ImagesServedFromBrowserCache); } if (_LastStatisticsSnapshot.SnapshotTime + StatisticsSnapshotInterval < DateTime.UtcNow) { // May need to snapshot statistics, but make sure only one thread does it if (Interlocked.Exchange(ref _SnapshottingStatistics, 1) == 0) // it's our job { var previousSnapshot = _LastStatisticsSnapshot; _LastStatisticsSnapshot = CurrentStatistics.Clone(); _LastStatisticsSnapshot.SnapshotTime = DateTime.UtcNow; VotePage.LogInfo("ImageCaching", $"Image caching from {previousSnapshot.SnapshotTime} to {_LastStatisticsSnapshot.SnapshotTime}:" + $" {_LastStatisticsSnapshot.ImagesServedFromBrowserCache - previousSnapshot.ImagesServedFromBrowserCache} from browser cache," + $" {_LastStatisticsSnapshot.ImagesServedFromMemoryCache - previousSnapshot.ImagesServedFromMemoryCache} from memory cache," + $" {_LastStatisticsSnapshot.ImagesServedFromDisc - previousSnapshot.ImagesServedFromDisc} from disc"); Interlocked.Exchange(ref _SnapshottingStatistics, 0); } } response.End(); }
private static byte[] UpdatePoliticianImages(string politicianKey, Stream imageStream, DateTime uploadTime, bool includeAllProfileImages, bool includeHeadshotOriginal, bool includeHeadshotResizedImages, bool checkForDuplicates, out Size originalSize, out byte[] originalBlob) { var memoryStream = new MemoryStream(); imageStream.Position = 0; imageStream.CopyTo(memoryStream); imageStream.Position = 0; var image = Image.FromStream(imageStream); originalSize = image.Size; var blob = memoryStream.ToArray(); if (!image.RawFormat.Equals(ImageFormat.Jpeg)) // could be transparent { // draw on a white background var b = new Bitmap(image.Width, image.Height); b.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var g = Graphics.FromImage(b)) { g.Clear(Color.White); g.DrawImageUnscaled(image, 0, 0); //b.Save(@"c:\temp\zz.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } image = b; } // This is so all subsequent db operations can be updates PoliticiansImagesData.GuaranteePoliticianKeyExists(politicianKey); PoliticiansImagesBlobs.GuaranteePoliticianKeyExists(politicianKey); originalBlob = null; if (checkForDuplicates) { // We fetch this image to see if its a duplicate var duplicateTester = GetImageToUseForDuplicateTesting(); if (duplicateTester != null) { var duplicateTesterBlob = GetResizedImageBlobAsJpg(image, duplicateTester.MaxWidth, duplicateTester.MaxHeight); originalBlob = duplicateTesterBlob; var dbBlob = PoliticiansImagesBlobs.GetColumn(duplicateTester.BlobsColumn, politicianKey) as Byte[]; if (dbBlob != null && dbBlob.Length == duplicateTesterBlob.Length) { var isDuplicate = !dbBlob.Where((t, inx) => t != duplicateTesterBlob[inx]) .Any(); if (isDuplicate) { return(null); // signals duplicate } } } } if (includeAllProfileImages) { PoliticiansImagesData.UpdateProfileOriginalDate(uploadTime, politicianKey); //PoliticiansImagesBlobs.UpdateProfileOriginal(blob, politicianKey); foreach (var info in GetAllProfilePoliticianImageInfos()) { var resizedBlob = GetResizedImageBlobAsJpg(image, info.MaxWidth, info.MaxHeight); PoliticiansImagesBlobs.UpdateColumn(info.BlobsColumn, resizedBlob, politicianKey); } } if (includeHeadshotOriginal) { PoliticiansImagesData.UpdateHeadshotDate(uploadTime, politicianKey); } if (includeHeadshotResizedImages) { foreach (var info in GetResizedHeadshotPoliticianImageInfos()) { var resizedBlob = GetResizedImageBlobAsJpg(image, info.MaxWidth, info.MaxHeight); PoliticiansImagesBlobs.UpdateColumn(info.BlobsColumn, resizedBlob, politicianKey); } PoliticiansImagesData.UpdateHeadshotResizeDate(uploadTime, politicianKey); } // Don't do this here. It belongs as a separate call. //CommonCacheInvalidation.ScheduleInvalidation("politicianimage", politicianKey); // We return the blob for logging purposes return(blob); }
private static void InvalidatePoliticianImage(string politicianKey) { // We do this via updates to avoid synchronization problems var oldBlobs = PoliticiansImagesBlobs.GetDataByPoliticianKey(politicianKey); if (oldBlobs.Count == 1) { var newBlobs = DB.Vote.PoliticiansImagesBlobs.GetCacheDataByPoliticianKey(politicianKey); switch (newBlobs.Count) { case 1: { var oldRow = oldBlobs[0]; var newRow = newBlobs[0]; oldRow.Profile300 = newRow.Profile300; oldRow.Profile200 = newRow.Profile200; oldRow.Headshot100 = newRow.Headshot100; oldRow.Headshot75 = newRow.Headshot75; oldRow.Headshot50 = newRow.Headshot50; oldRow.Headshot35 = newRow.Headshot35; oldRow.Headshot25 = newRow.Headshot25; oldRow.Headshot20 = newRow.Headshot20; oldRow.Headshot15 = newRow.Headshot15; PoliticiansImagesBlobs.UpdateTable(oldBlobs); } break; case 0: PoliticiansImagesBlobs.DeleteByPoliticianKey(politicianKey); break; } } var oldData = PoliticiansImagesData.GetDataByPoliticianKey(politicianKey); if (oldData.Count != 1) { return; } var newData = DB.Vote.PoliticiansImagesData.GetDataByPoliticianKey(politicianKey); switch (newData.Count) { case 1: { var oldRow = oldData[0]; var newRow = newData[0]; //oldRow.ProfileOriginalContentType = newRow.ProfileOriginalContentType; oldRow.ProfileOriginalDate = newRow.ProfileOriginalDate; //oldRow.ProfileOriginalWidth = newRow.ProfileOriginalWidth; //oldRow.ProfileOriginalHeight = newRow.ProfileOriginalHeight; //oldRow.HeadshotContentType = newRow.HeadshotContentType; oldRow.HeadshotDate = newRow.HeadshotDate; //oldRow.HeadshotWidth = newRow.HeadshotWidth; //oldRow.HeadshotHeight = newRow.HeadshotHeight; oldRow.HeadshotResizeDate = newRow.HeadshotResizeDate; PoliticiansImagesData.UpdateTable(oldData); } break; case 0: PoliticiansImagesData.DeleteByPoliticianKey(politicianKey); break; } }
public static void GuaranteePoliticianKeyExists(string politicianKey) { PoliticiansImagesData.GuaranteePoliticianKeyExists(politicianKey); PoliticiansImagesBlobs.GuaranteePoliticianKeyExists(politicianKey); }
// ReSharper disable MemberCanBePrivate.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnassignedField.Global #endregion ReSharper disable public static void DeleteByPoliticianKey( string politicianKey, int commandTimeout = -1) { PoliticiansImagesData.DeleteByPoliticianKey(politicianKey, commandTimeout); PoliticiansImagesBlobs.DeleteByPoliticianKey(politicianKey, commandTimeout); }
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { var politicianKey = PoliticianKeyTextBox.Text.Trim(); if (IsNullOrEmpty(politicianKey)) { throw new VoteException("Politician Key is missing"); } if (IsNullOrEmpty(FolderTextBox.Text.Trim())) { throw new VoteException("Save Folder is missing"); } var folder = new DirectoryInfo(FolderTextBox.Text.Trim()); if (!folder.Exists) { throw new VoteException("Save Folder does not exist"); } var newOriginalsTable = LogDataChange.GetDataByTableNameColumnNameKeyValues( PoliticiansImagesBlobs.TableName, PoliticiansImagesBlobs.GetColumnName( PoliticiansImagesBlobs.Column.ProfileOriginal), politicianKey, 0); var newHeadshotsTable = LogDataChange.GetDataByTableNameColumnNameKeyValues( PoliticiansImagesBlobs.TableName, PoliticiansImagesBlobs.GetColumnName( PoliticiansImagesBlobs.Column.Headshot100), politicianKey, 0); var images = new List <ImageInfo>(); images.AddRange(newOriginalsTable.Where(row => row.NewValue != null) .Select(row => new ImageInfo { ImageType = "Profile", Date = row.DateStamp, User = row.UserName, Blob = Convert.FromBase64String(row.NewValue) })); images.AddRange(newHeadshotsTable.Where(row => row.NewValue != null) .Select(row => new ImageInfo { ImageType = "Headshot", Date = row.DateStamp, User = row.UserName, Blob = Convert.FromBase64String(row.NewValue) })); if (images.Count == 0) { throw new VoteException("No logged images found for this Politician Key"); } folder.CreateSubdirectory(politicianKey); AppendStatusText("Found {0} images:", images.Count); foreach (var imageInfo in images) { var memoryStream = new MemoryStream(imageInfo.Blob); var image = Image.FromStream(memoryStream); var contentType = ImageManager.GetContentType(image); var extension = $".{contentType.Replace("image/", "")}"; var filename = $"{imageInfo.ImageType}_{imageInfo.Date:yyyy-MM-dd-HH-mm-ss}_{imageInfo.User}{extension}"; var path = Path.Combine(folder.FullName, politicianKey, filename); File.WriteAllBytes(path, imageInfo.Blob); AppendStatusText(filename); } AppendStatusText(Empty); } catch (VoteException ex) { AppendStatusText(ex.Message); } catch (Exception ex) { AppendStatusText(ex.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { var result = new AjaxResponse(); try { // assume success unless an exception is thrown result.Success = true; // copy back the groupname and uploadid result.GroupName = Request.Form["groupname"]; result.UploadId = Request.Form["uploadid"]; // there should always be exactly one file if (Request.Files.Count == 0) { throw new VoteException("The upload file is missing"); } if (Request.Files.Count > 1) { throw new VoteException("Unexpected files in the upload package"); } // Test error handling //throw new VoteException("Some weird-ass error"); // get the file var postedFile = Request.Files[0]; // save the timestamp so the time we post to all the various tables matches // exactly... var uploadTime = DateTime.UtcNow; // We only update headshot images if there is no Headshot -- // we check Headshot100 determine if this is so // We request duplicate testing... byte[] blob; Size originalSize; byte[] originalBlob; if (PoliticiansImagesBlobs.GetHeadshot100(PoliticianKey) == null) { blob = ImageManager.UpdateAllPoliticianImages(PoliticianKey, postedFile.InputStream, uploadTime, true, out originalSize, out originalBlob); } else { blob = ImageManager.UpdatePoliticianProfileImages(PoliticianKey, postedFile.InputStream, uploadTime, true, out originalSize, out originalBlob); } if (blob == null) // means it was a duplicate { result.Duplicate = true; result.Message = "The uploaded picture is the same as we already have on our servers."; } else { result.Message = "The picture uploaded successfully. Original file length = " + postedFile.InputStream.Length.ToString(CultureInfo.InvariantCulture); result.Length = postedFile.InputStream.Length; result.Width = originalSize.Width; result.Height = originalSize.Height; // invalidate cached image on load-balanced servers CommonCacheInvalidation.ScheduleInvalidation("politicianimage", PoliticianKey); LogImageChange(originalBlob, blob, uploadTime); Politicians.UpdateDatePictureUploaded(uploadTime, PoliticianKey); } } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } WriteJsonResultToResponse(result); }