public ActionResult _DeleteProfilePicture() { var succeeded = true; try { var azureStorageServce = new Service(); var success = azureStorageServce.DeleteFile("user/images/profilepic/" + UserServices.GetProfilePictureName(CurrentCedUser.CurrentUser.UserId)); if (!success) { return(Json(new { success = false, message = "Error while deleting profile picture" })); } } catch (Exception exc) { succeeded = false; var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); } return(succeeded ? Json(new { success = true }) : Json(new { success = false, message = "Error while deleting profile picture." })); }
public JsonResult NotifyAboutMissingEditionImages(string key, string connectionId) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { var editions = TaskServices.GetEditionsWithMissingImages(); var pattern = "<a href='{0}'>{1}</a>"; var body = "<table>"; for (var i = 0; i < editions.Count; i++) { var edition = editions[i]; var url = _editionHelper.GetEditionUrl(new EditionEntity { EditionId = edition.EditionId, EditionName = edition.EventName, Status = edition.Status.ToEnum <EditionStatusType>() }); body += "<tr><td class='font-lato' style='font-size: 14px; color: #888794'>" + string.Format(pattern, url, edition.EventName); body += edition.EventBackGroundImage == null ? " [People Image] " : ""; body += edition.EventImage == null ? " [Web Logo] " : ""; body += edition.IconFileName == null ? " [Icon] " : ""; body += edition.MasterLogoFileName == null ? " [Master Logo] " : ""; body += edition.ProductImageFileName == null ? " [Product Image] " : ""; body += "</td></tr>"; if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, "Detecting missing images...", i + 1, editions.Count, TaskType.NotifyAboutMissingEditionImages.GetHashCode()); } } body += "</table>"; var subject = "Events with Missing Images"; var recipients = WebConfigHelper.MarketingAdminEmails; _emailNotificationHelper.Send(NotificationType.MissingEditionImages, subject, body, recipients); var log = CreateInternalLog("The task NotifyAboutMissingEditionImages completed.", AutoIntegrationUser); ExternalLogHelper.Log(log, LoggingEventType.Information); return(Json("", JsonRequestBehavior.AllowGet)); } catch (Exception exc) { var message = "The task NotifyAboutMissingEditionImages failed! " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Error); return(Json(false, JsonRequestBehavior.AllowGet)); } } return(Json(false, JsonRequestBehavior.AllowGet)); }
public bool CreateFile(FileEntity fileEntity, int userId) { try { var file = new File { FileName = fileEntity.FileName, EntityId = fileEntity.EntityId, EntityType = fileEntity.EntityType, FileType = fileEntity.EditionFileType.GetDescription(), LanguageCode = fileEntity.LanguageCode, CreatedOn = DateTime.Now, CreatedBy = userId, CreatedByFullName = fileEntity.CreatedByFullName, CreatedByEmail = fileEntity.CreatedByEmail }; _unitOfWork.FileRepository.Insert(file); _unitOfWork.Save(); return(true); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(false); } }
private FileOperationResult SaveFileToLocalDisk(EditionFileType fileType, string newFileName, HttpPostedFileBase file) { var path = Server.MapPath("~/" + fileType.FileFullNameInternal(newFileName)); if (System.IO.File.Exists(path)) { return(new FileOperationResult { Result = OperationResult.AlreadyExists }); } try { file.SaveAs(path); return(new FileOperationResult { Result = OperationResult.Succeeded, Message = path }); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(new FileOperationResult { Result = OperationResult.Failed, Message = exc.Message }); } }
private bool DeleteFileFromLocalDisk(string fileName, EditionFileType editionFileType) { var path = Server.MapPath("~/" + editionFileType.FileFullNameInternal(fileName)); if (!System.IO.File.Exists(path)) { var log = CreateInternalLog($"File not found on {path}!"); ExternalLogHelper.Log(log, LoggingEventType.Error); return(false); } try { System.IO.File.Delete(path); return(true); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(false); } }
public void UpdateApprovedEditionsFromStagingDb(string key, string connectionId) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { var approvedEditions = GetApprovedEditions(); var stagingEditions = GetStagingEditionsPossiblyHaveNewEditions(approvedEditions); if (approvedEditions.Count > 0) { for (var i = 0; i < approvedEditions.Count; i++) { var approvedEdition = approvedEditions[i]; var siblingsOnCed = GetSiblingEditionsByApprovedEdition(approvedEdition); var siblingsOnStaging = stagingEditions.Where(x => x.EventMasterCode == approvedEdition.Event.MasterCode).ToList(); if (siblingsOnStaging.Count == siblingsOnCed.Count) { var newlyAddedEdition = siblingsOnStaging.OrderByDescending(x => x.EventStartDate).Take(1).SingleOrDefault(); UpdateApprovedEdition(newlyAddedEdition, approvedEdition); break; } if (siblingsOnStaging.Count > siblingsOnCed.Count) { var message = "In Staging database there are more editions of the event " + $"{approvedEdition.Event.MasterCode} - {approvedEdition.Event.MasterName} than in CED database." + "Both must be equal or the ones CED database must be lesser."; var log = CreateInternalLog(message); ExternalLogHelper.Log(log, LoggingEventType.Fatal); } if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, "Done", i + 1, approvedEditions.Count, TaskType.UpdateApprovedEditionsFromStagingDb.GetHashCode()); } } } else { if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, "Done", 1, 1, TaskType.UpdateApprovedEditionsFromStagingDb.GetHashCode()); } } var log2 = CreateInternalLog("The task UpdateApprovedEditionsFromStagingDb completed.", AutoIntegrationUser); ExternalLogHelper.Log(log2, LoggingEventType.Information); } catch (Exception exc) { var message = "The task UpdateApprovedEditionsFromStagingDb failed! " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Fatal); } } }
public ActionResult _RequestHelp(HelpRequestModel model) { if (!ModelState.IsValid) { return(Json(new { success = false, message = ModelState.GetErrors() })); } const string subject = "CED Help Request"; var recipient = WebConfigHelper.AdminEmails; // WebConfigHelper.HelpDeskUserName; var actorUserEmail = CurrentCedUser.CurrentUser.Email; var body = model.Message + "<p><b>Sender:</b> " + actorUserEmail + "</p>"; try { EmailHelper.SendEmail(subject, body, recipient); // EMAIL LOGGING LogEmail(null, recipient, body, actorUserEmail, "_RequestHelp"); return(Json(new { success = true })); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(Json(new { success = false, message = exc.Message })); } }
public ActionResult _RequestAccess(AccessRequestModel model) { if (!ModelState.IsValid) { return(Json(new { success = false, message = ModelState.GetErrors() })); } const string subject = "CED Access Request"; var recipient = WebConfigHelper.AdminEmails; // WebConfigHelper.HelpDeskUserName; var body = "Message: " + model.AdditionalNotes; body += "<br><br>Events: " + model.EventNames; body += "<br>Office: " + model.OfficeName; body += "<br>Sender: " + model.FirstName + " " + model.LastName; try { new EmailHelper().SendEmail(subject, body, recipient); // EMAIL LOGGING LogEmail(null, recipient, body, null, "_RequestAccess"); return(Json(new { success = true })); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(Json(new { success = false, message = exc.Message })); } }
/* EMAIL NOTIFICATION */ public EmailResult SendEmailNotification(EditionEntity edition, NotificationType notificationType, string recipients, UserEntity actor, string body, string buttonUrl, string unsubscribingUrl = null) { //if (string.IsNullOrWhiteSpace(recipients)) //{ // var message = $"{notificationType} type of notification email could not be sent since edition {edition.EditionId} - {edition.EditionName} has no recipients."; // var log = CreateInternalLog(message, actor); // ExternalLogHelper.Log(log, LoggingEventType.Warning); // return new EmailResult { Sent = false, ErrorMessage = message }; //} if (WebConfigHelper.RemoveActorUserFromNotificationRecipients) { recipients = NotificationControllerHelper.RemoveCurrentUserFromRecipients(recipients, actor?.Email); } //if (string.IsNullOrWhiteSpace(recipients)) // return false; try { var recipientFullName = _editionHelper.GetRecipientFullName(edition); var sendEmailAttr = notificationType.GetAttribute <NotificationAttribute>().SendEmail; if (sendEmailAttr) { var editionTranslation = edition.EditionTranslations.SingleOrDefault(x => string.Equals(x.LanguageCode, LanguageHelper.GetBaseLanguageCultureName(), StringComparison.CurrentCultureIgnoreCase)); var emailResult = _emailNotificationHelper.Send(edition, editionTranslation, notificationType, recipientFullName, body, recipients, buttonUrl, unsubscribingUrl); //// EMAIL LOGGING //if (sent) //LogEmail(edition.EditionId, recipients, body, actor?.Email, notificationType.ToString()); return(emailResult); } } catch (Exception exc) { var log = CreateInternalLog(exc, actor); ExternalLogHelper.Log(log, LoggingEventType.Error); } return(new EmailResult { Sent = false, ErrorMessage = "" }); }
private bool SaveNewEvent(Event newEvent, DWStaging.Edition stagingEdition) { try { _unitOfWork.EventRepository.Insert(newEvent); _unitOfWork.Save(); } catch (Exception exc) { var extraInfo = "Error on EventRepository.Insert() | StagingEditionEventBEID=" + stagingEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return(false); } return(true); }
public bool DeleteFile(int fileId) { try { var file = _unitOfWork.FileRepository.GetById(fileId); _unitOfWork.FileRepository.Delete(file); _unitOfWork.Save(); return(true); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); return(false); } }
public void ResetEditionStartDateDifferences(string key) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { TaskServices.ResetEditionStartDateDifferences(); var log = CreateInternalLog("One-time task ResetEditionStartDateDifferences completed.", AutoIntegrationUser); ExternalLogHelper.Log(log, LoggingEventType.Information); } catch (Exception exc) { var message = "One-time task ResetEditionStartDateDifferences failed! " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Error); } } }
private int SaveEditionTranslation(EditionTranslationEntity editionTranslation, DWStaging.Edition stagingEdition) { try { var et = Mapper.Map <EditionTranslationEntity, EditionTranslation>(editionTranslation); _unitOfWork.EditionTranslationRepository.Insert(et); _unitOfWork.Save(); return(et.EditionTranslationId); } catch (Exception exc) { var extraInfo = "StagingEditionEventBEID=" + stagingEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return(-1); } }
private void UpdateCedEventsFromKentico() { try { // Get all KenticoEditions var kenticoEditions = _unitOfWork.EventRepository.Context.Clnd_KenticoEvents.Where(x => x.EventBEID > 0).ToList(); //var kenticoEditions = _unitOfWork.EventRepository.Context.Clnd_KenticoEvents.Where(x => x.KenticoEventID == 2970).ToList(); // For every KenticoEdition; foreach (var ke in kenticoEditions) { var kenticoEdition = ke; // get the CEDEdition corresponding to this KenticoEdition. (1 adet olması gerek.) var cedEditions = _unitOfWork.EditionRepository.GetManyQueryable(x => x.AxEventId == kenticoEdition.EventBEID).ToList(); if (cedEditions.Any() && cedEditions.Count == 1) { var cedEdition = cedEditions.First(); // If it has not been already updated recently... //if (cedEdition.UpdateTimeByAutoIntegration > new DateTime(2016, 09, 08, 11, 44, 23)) // continue; var allEditionsOfThisEvent = _unitOfWork.EditionRepository.GetManyQueryable(x => x.EventId == cedEdition.EventId); var logoFound = true; foreach (var edition in allEditionsOfThisEvent) { UpdateSingleCedEventFromKentico(edition, kenticoEdition, ref logoFound); } } } } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); } }
public void UpdateEventDirectors(string key, string connectionId) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { TaskServices.UpdateEventDirectors(); var log = CreateInternalLog("The task UpdateEventDirectors completed.", AutoIntegrationUser); ExternalLogHelper.Log(log, LoggingEventType.Information); if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, "Done", 1, 1, TaskType.UpdateEventDirectors.GetHashCode()); } } catch (Exception exc) { var log = CreateInternalLog("The task UpdateEventDirectors failed!", AutoIntegrationUser); var message = log.AdditionalInfo + " | " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Fatal); } } }
public void UpdateEventEditionFromStagingDb(EditionEntity existingEdition, DWStaging.Edition stagingEdition, DateTime eventStartDate, DateTime eventEndDate) { using (var scope = new TransactionScope()) { var existingEvent = existingEdition.Event; var eventFromStaging = EditionServiceHelper.PreUpdateExistingEvent((EventEntity)existingEvent.Clone(), stagingEdition); // IF MASTERCODE HAS CHANGED: if (existingEvent.MasterCode != eventFromStaging.MasterCode) { // DELETE THIS WRONGLY UPDATED EDITION FROM CED _editionServices.DeleteEdition(existingEdition.EditionId); } else { var diffOnEvent = GetDiffOnEvent(existingEvent, eventFromStaging); var editionFromStaging = EditionServiceHelper.PreUpdateExistingEdition((EditionEntity)existingEdition.Clone(), stagingEdition, eventStartDate, eventEndDate); var diffOnEdition = existingEdition.Compare <EditionEntity, StagingDbComparableAttribute>(editionFromStaging); var existingEditionTranslation = existingEdition.EditionTranslations.Single(x => x.EditionId == existingEdition.EditionId && x.LanguageCode.ToLower() == LanguageHelper.GetBaseLanguageCultureName()); var editionTranslationFromStaging = EditionServiceHelper.PreUpdateExistingEditionTranslation((EditionTranslationEntity)existingEditionTranslation.Clone(), stagingEdition); var diffOnEditionTranslation = existingEditionTranslation.Compare <EditionTranslationEntity, StagingDbComparableAttribute>(editionTranslationFromStaging); if (diffOnEvent.Any()) { try { _eventServices.UpdateEvent(existingEvent.EventId, eventFromStaging, Constants.AutoIntegrationUserId, true); } catch (Exception exc) { var extraInfo = "Error on UpdateEvent() | EventId=" + existingEvent.EventId + " | StagingEditionEventBEID=" + stagingEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return; } } if (diffOnEditionTranslation.Any() || diffOnEdition.Any() || diffOnEvent.Any()) { try { var startDateChanged = diffOnEdition.SingleOrDefault(x => x.Prop.ToLower().Contains("startdate")) != null; if (startDateChanged) { // UPDATE STARTDATE DIFF for CURRENT EDITION SetEditionStartDateDiff(editionFromStaging); } _editionServices.UpdateEdition(existingEdition.EditionId, editionFromStaging, Constants.AutoIntegrationUserId, true); if (startDateChanged) { // UPDATE STARTDATE DIFF for NEXT EDITION UpdateNextEditionStartDateDiff(existingEdition); } var eventTypeChanged = diffOnEdition.SingleOrDefault(x => x.Prop.ToLower().Contains("eventtype")) != null; if (eventTypeChanged) { if (!Utility.Constants.ValidEventTypesForCed.Contains(existingEdition.EventTypeCode) && Utility.Constants.ValidEventTypesForCed.Contains(editionFromStaging.EventTypeCode) && editionFromStaging.StartDate > DateTime.Now) { SendNotificationEmailForEditionCreation(editionFromStaging, editionTranslationFromStaging, GetEmailTemplateForEditionCreation(editionFromStaging)); } } StartNotificationProcessForEditionNameUpdate(existingEdition, existingEditionTranslation, diffOnEdition); StartNotificationProcessForEditionLocationUpdate(existingEdition, existingEditionTranslation, diffOnEdition); } catch (Exception exc) { var extraInfo = "Error on editionServices.UpdateEdition() | EditionId=" + existingEdition.EditionId + " | StagingEditionEventBEID=" + stagingEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return; } } if (diffOnEditionTranslation.Any()) { try { _editionTranslationServices.UpdateEditionTranslation(editionTranslationFromStaging, Constants.AutoIntegrationUserId, true); } catch (Exception exc) { var extraInfo = "EditionTranslationId=" + existingEditionTranslation.EditionTranslationId + " | StagingEditionEventBEID=" + stagingEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return; } } } scope.Complete(); } }
private void UpdateSingleCedEventFromKentico(Edition cedEdition, Clnd_KenticoEvents kenticoEdition, ref bool logoFound) { try { var cedEditionTranslations = _unitOfWork.EditionTranslationRepository.GetManyQueryable(x => x.EditionId == cedEdition.EditionId && x.LanguageCode == LanguageHelper.GetBaseLanguageCultureName()).ToList(); if (cedEditionTranslations.Any() && cedEditionTranslations.Count == 1) { var cedEditionTranslation = cedEditionTranslations.First(); cedEdition.InternationalName = kenticoEdition.EventName; cedEdition.ManagingOfficeName = kenticoEdition.Organiser; cedEdition.ManagingOfficeEmail = kenticoEdition.EmailAddress; cedEdition.ManagingOfficePhone = "+" + kenticoEdition.InternationalDial + " " + kenticoEdition.Telephone; cedEdition.ManagingOfficeWebsite = kenticoEdition.Website; cedEdition.EventWebSite = kenticoEdition.Website; cedEdition.AllDayEvent = Convert.ToBoolean(kenticoEdition.EventAllDay); cedEdition.DisplayOnIteI = Convert.ToBoolean(kenticoEdition.ITEI); cedEdition.DisplayOnIteGermany = Convert.ToBoolean(kenticoEdition.GiMA); cedEdition.DisplayOnIteAsia = Convert.ToBoolean(kenticoEdition.ASIA); cedEdition.DisplayOnIteTurkey = Convert.ToBoolean(kenticoEdition.Turkey); cedEdition.DisplayOnTradeLink = Convert.ToBoolean(kenticoEdition.TradeLink); cedEdition.DisplayOnIteModa = Convert.ToBoolean(kenticoEdition.MODA); cedEdition.UpdateTimeByAutoIntegration = DateTime.Now; cedEditionTranslation.Summary = kenticoEdition.EventSummary.ReplaceBrWithNewLine().StripHtml(); cedEditionTranslation.Description = kenticoEdition.EventDetails.ReplaceBrWithNewLine().StripHtml(); cedEditionTranslation.BookStandUrl = kenticoEdition.BookTicketLink; // Get venue coordinates if (kenticoEdition.VenueLocation.HasValue) { var venue = _unitOfWork.EditionRepository.Context.Clnd_customtable_Venue.SingleOrDefault(x => x.ItemID == kenticoEdition.VenueLocation); if (venue != null) { cedEdition.VenueCoordinates = venue.VenueLocation.Replace(",", ", "); cedEditionTranslation.VenueName = venue.VenueName; } } if (logoFound) { cedEditionTranslation.WebLogoFileName = UploadEventImage(cedEditionTranslation, kenticoEdition.EventImage, true); } logoFound = cedEditionTranslation.WebLogoFileName != null; cedEditionTranslation.PeopleImageFileName = UploadEventImage(cedEditionTranslation, kenticoEdition.EventBackGroundImage, false); cedEditionTranslation.UpdateTimeByAutoIntegration = DateTime.Now; _unitOfWork.Save(); } } catch (Exception exc) { var extraInfo = "Error on UpdateSingleCedEventFromKentico() | EditionId=" + cedEdition + " | KenticoEventBEID=" + kenticoEdition.EventBEID; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); } }
public ActionResult _Delete(int fileId, string fileType) { var editionFileType = fileType.ToLower().ToEnumFromDescription <EditionFileType>(); var file = FileServices.GetFileById(fileId); if (file == null) { return(Json(new { success = false, message = Constants.FileNotFound })); } var edition = EditionServices.GetEditionById(file.EntityId); if (edition.IsCancelled()) { return(Json(new { success = false, message = Constants.WarningMessageEventCancelled })); } var success = FileServices.DeleteFile(file.FileId); if (success) { bool success2; if (file.EditionFileType.GetAttribute <FileTypeAttribute>().Private) { success2 = DeleteFileFromLocalDisk(file.FileName, file.EditionFileType); } else { var blobName = editionFileType.BlobFullName(file.FileName); try { success2 = _azureStorageService.DeleteFile(blobName); } catch (Exception exc) { var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); success2 = false; } } //if (!success2) // return Json(new {success = false, message = "File could not be deleted!"}); // UPDATE EDITON UpdateEditionUpdateInfo(edition); //// DIFF //var diff = new List<Variance> { new Variance { Prop = $"File ({file.EditionFileType})", ValA = file.FileName, ValB = null } }; //OnEditionUpdated(edition, diff); // UPDATE LOG var updatedFields = NotificationControllerHelper.GetUpdatedFieldsAsJson($"File ({file.EditionFileType})", new List <Variance> { new Variance { Prop = editionFileType.ToString() } }); UpdateLogInMemory(edition, updatedFields); // UPDATEDCONTENT var currentFileForComparison = new FileEntity { FileName = file.FileName }; var fileForComparison = new FileEntity(); fileForComparison.SetFullUrl(); var updatedContent = NotificationControllerHelper.GetUpdatedContent(currentFileForComparison, fileForComparison); PushEditionUpdateNotifications(edition, updatedContent); return(Json(new { success = true, message = Constants.FileDeleted, fileType = editionFileType.GetDescription() })); } return(Json(new { success = false, message = Constants.FileNotDeleted })); }
public ActionResult _Upload() { var entityId = Convert.ToInt32(Request.Params["EntityId"]); var fileType = Request.Params["FileType"].ToEnum <EditionFileType>(); var langCode = Request.Params["LanguageCode"]; var isSaved = true; var newFileName = ""; var edition = EditionServices.GetEditionById(entityId); if (edition == null) { return(View("NotFound", new ErrorModel { Message = Constants.EditionNotFound })); } if (edition.IsCancelled()) { return(Json(new { success = false, message = Constants.WarningMessageEventCancelled })); } try { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileNameWithoutExtension(file.FileName); // CHECK EXTENSION var extension = Path.GetExtension(file.FileName); var allowedExtensions = fileType.GetAttribute <FileTypeAttribute>().AllowedExtensions; if (!allowedExtensions.Contains(extension)) { return(Json(new { success = false, message = Constants.InvalidFileExtension })); } newFileName = EditionServiceHelper.ComposeFileName(edition.EditionId, fileName, fileType, langCode, extension); // The way of saving changes depending on fileType's Private property. var result = fileType.GetAttribute <FileTypeAttribute>().Private ? SaveFileToLocalDisk(fileType, newFileName, file) : SaveFileToAzureStorage(fileType, newFileName, file); switch (result.Result) { case OperationResult.AlreadyExists: return(Json(new { success = false, message = Constants.FileAlreadyExistsWithTheSameName })); case OperationResult.Failed: return(Json(new { success = false, message = result.Message })); } // CREATE FILE if (!SaveFileInfo(entityId, newFileName, fileType, extension, langCode)) { return(Json(new { success = false, message = Constants.ErrorWhileSavingFile })); } } } catch (Exception exc) { isSaved = false; var log = CreateInternalLog(exc); ExternalLogHelper.Log(log, LoggingEventType.Error); } if (!isSaved) { return(Json(new { success = false, message = Constants.ErrorWhileSavingFile })); } // UPDATE EDITION UpdateEditionUpdateInfo(edition); // UPDATE LOG var updatedFields = NotificationControllerHelper.GetUpdatedFieldsAsJson($"File ({fileType})", new List <Variance> { new Variance { Prop = fileType.ToString() } }); UpdateLogInMemory(edition, updatedFields); //UpdateLogInMemory(currentEdition, edition, currentEditionTranslation, editionTranslation); // UPDATEDCONTENT var currentFileForComparison = new FileEntity(); var fileForComparison = new FileEntity { FileName = newFileName }; fileForComparison.SetFullUrl(); var updatedContent = NotificationControllerHelper.GetUpdatedContent(currentFileForComparison, fileForComparison); PushEditionUpdateNotifications(edition, updatedContent); return(Json(new { success = true, message = Constants.FileSaved })); }
public JsonResult UpdateNotifications(string key, string connectionId) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { var notificationTypes = Enum.GetValues(typeof(NotificationType)); var allEditionNotifPairs = new Dictionary <EditionEntity, NotificationType>(); foreach (NotificationType notificationType in notificationTypes) { if (notificationType.GetAttribute <CompletenessNotificationTypeAttribute>() == null) { continue; } var editions = GetEditionsToNotify(notificationType); foreach (var edition in editions) { allEditionNotifPairs.Add(edition, notificationType); } } if (allEditionNotifPairs.Count > 0) { for (var i = 0; i < allEditionNotifPairs.Count; i++) { var pair = allEditionNotifPairs.ElementAt(i); ProcessEditionNotifications(pair, i, allEditionNotifPairs.Count); if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, pair.Value + " for " + pair.Key.EditionName, i + 1, allEditionNotifPairs.Count, TaskType.UpdateNotifications.GetHashCode()); } } } else { if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, "Done", 1, 1, TaskType.UpdateNotifications.GetHashCode()); } } var log = CreateInternalLog("The task UpdateNotifications completed.", AutoIntegrationUser); ExternalLogHelper.Log(log, LoggingEventType.Information); return(Json("", JsonRequestBehavior.AllowGet)); } catch (Exception exc) { var message = "The task UpdateNotifications failed! " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Fatal); return(Json(false, JsonRequestBehavior.AllowGet)); } } return(Json("", JsonRequestBehavior.AllowGet)); }
public ActionResult _SaveProfilePicture() { var imageType = UserImageType.ProfilePic; var oldFileName = UserServices.GetProfilePictureName(CurrentCedUser.CurrentUser.UserId); try { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { // Resizing & changing format(to jpg) using (var outStream = new MemoryStream()) { using (var inStream = new MemoryStream(file.InputStream.ReadAsBytes())) { var settings = new ResizeSettings("maxwidth=76&maxheight=76&format=jpg"); ImageBuilder.Current.Build(inStream, outStream, settings); var newFileName = $"{CurrentCedUser.CurrentUser.UserId }.jpg"; //// CHECK EXTENSION //var extension = Path.GetExtension(file.FileName); //var allowedExtensions = imageType.GetAttribute<ImageAttribute>().AllowedExtensions; //if (!allowedExtensions.Contains(extension)) //{ // var errorMessage = "Invalid file extension!"; // return Json(new { success = false, message = errorMessage }); //} //// CHECK LENGTH //var minMaxLengths = imageType.GetAttribute<ImageAttribute>().MinMaxLengths; //if (file.ContentLength < minMaxLengths[0] || file.ContentLength > minMaxLengths[1]) //{ // var errorMessage = "Invalid file size!"; // return Json(new { success = false, message = errorMessage }); //} //// CHECK SIZES (WIDTH AND HEIGHT) //var allowedWidth = imageType.GetAttribute<ImageAttribute>().Width; //var allowedHeight = imageType.GetAttribute<ImageAttribute>().Height; //if (allowedWidth > 0 && allowedHeight > 0) //{ // var imgFile = System.Drawing.Image.FromStream(file.InputStream); // if (imgFile.PhysicalDimension.Width > allowedWidth || // imgFile.PhysicalDimension.Width < allowedWidth // || imgFile.PhysicalDimension.Height > allowedHeight || // imgFile.PhysicalDimension.Height < allowedHeight) // { // var errorMessage = "Invalid file dimension!"; // return Json(new { success = false, message = errorMessage }); // } //} var azureStorageService = new Service(); // DELETE OLD FILE try { azureStorageService.DeleteFile(imageType.BlobFullName(oldFileName)); } catch (Exception exc) { var extraInfo = "Error while deleting file on Azure Storage."; var extLog = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(extLog, LoggingEventType.Error); } var result = azureStorageService.UploadFile( "user/images/" + imageType.GetAttribute <ImageAttribute>().Key.ToLower() + "/" + newFileName, file.ContentType, outStream); if (result.Result == OperationResult.Failed) { var intLog = CreateInternalLog(result.Message); ExternalLogHelper.Log(intLog, LoggingEventType.Error); return(Json(new { success = false, message = result.Message })); } } } } } catch (Exception exc) { return(Json(new { success = false, message = Utility.Constants.ErrorWhileSavingFile + (CurrentCedUser.IsSuperAdmin ? " Reason: " + exc.InnerException.GetFullMessage() : "") })); } return(Json(new { success = true, fileName = "" })); }
private string UploadEventImage(EditionTranslation editionTranslation, string imageUrl, bool isWebLogo) { const string remoteImageDomain = "https://www.hyve.group/"; try { if (string.IsNullOrWhiteSpace(imageUrl)) { return(null); } // D:\PROJECTS\ITE.CED\Ced.Web\content\images\edition\logo var newFileName = editionTranslation.EditionId + "-" + editionTranslation.Edition.EditionName.Trim() .Replace(" ", "") .Replace("'", "") .Replace("&", " ") .Replace("\"", " ") .ToLower() + "-" + editionTranslation.LanguageCode.ToLower() + Path.GetExtension(imageUrl); var remoteImgPath = remoteImageDomain + imageUrl.Replace("~/", ""); remoteImgPath = remoteImgPath.Substring(0, remoteImgPath.IndexOf(".aspx", StringComparison.Ordinal)); var folderName = isWebLogo ? EditionImageType.WebLogo.GetAttribute <ImageAttribute>().Key : EditionImageType.PeopleImage.GetAttribute <ImageAttribute>().Key; var localPath = AppDomain.CurrentDomain.BaseDirectory + @"content\images\edition\" + $@"{folderName}\" + newFileName; var webClient = new WebClient(); try { webClient.DownloadFile(remoteImgPath, localPath); } catch (Exception exc) { var extraInfo = "remoteImgPath: " + remoteImgPath + " | EditionId: " + editionTranslation.EditionId; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); if (isWebLogo) { // When the image cannot be found... var kenticoEditions = _unitOfWork.EventRepository.Context.Clnd_KenticoEvents.Where(x => x.EventBEID == editionTranslation.Edition.AxEventId); Clnd_KenticoEvents kenticoEdition = null; if (kenticoEditions.Any()) { kenticoEdition = kenticoEditions.First(); } if (!string.IsNullOrWhiteSpace(kenticoEdition?.EventImage)) { var lostImageUrl = ""; try { // sample: https://www.hyve.group/getmedia/fe18dac0-002d-42a2-b293-2f79a41d8028/anystring.aspx const int guidLength = 36; const string strGetMedia = "/getmedia/"; var indexGetMedia = kenticoEdition.EventImage.IndexOf(strGetMedia, StringComparison.Ordinal); var indexStart = indexGetMedia + strGetMedia.Length; if (indexStart == -1) { return(null); } if (kenticoEdition.EventImage.Length < indexStart + guidLength) { return(null); } var guid = kenticoEdition.EventImage.Substring(indexStart, guidLength); lostImageUrl = $"{remoteImageDomain}getmedia/{guid}/anystring.aspx"; webClient.DownloadFile(lostImageUrl, localPath); return(newFileName); } catch (Exception exc2) { var extraInfo2 = "lostImageUrl: " + lostImageUrl + " | EditionId: " + editionTranslation.EditionId + " | 2nd attempt"; var log2 = CreateInternalLog(exc2, extraInfo2); ExternalLogHelper.Log(log2, LoggingEventType.Error); return(null); } } return(null); } return(null); } return(newFileName); } catch (Exception exc) { var extraInfo = "EditionId: " + editionTranslation.EditionId; var log = CreateInternalLog(exc, extraInfo); ExternalLogHelper.Log(log, LoggingEventType.Error); return(null); } }
public JsonResult UpdateEventsFromStagingDb(string key, string connectionId) { if (key == WebConfigHelper.TaskSchedulerSecretKey) { try { var stagingEditionServices = new DWStaging.BusinessServices.EditionServices(); var stagingEditions = WebConfigHelper.IsLocal || WebConfigHelper.IsTest //? stagingEditionServices.GetEditionsByEventBeId("101558") : ? stagingEditionServices.GetEditionsByMasterCode(new[] { "1102" }) : stagingEditionServices.GetEditions(); //var stagingEditions = // stagingEditionServices.GetEditionsQueryable() // //.Where(x => new[] { "10117", "10215", "941", "969", "980" }.Contains(x.EventMasterCode)) // .Where(x => x.EventMaster.ToLower().Contains("agent")) // .ToList(); stagingEditions = stagingEditions.OrderBy(x => x.EventStartDate).ToList(); for (var i = 0; i < stagingEditions.Count; i++) { var stagingEdition = stagingEditions[i]; var axId = Convert.ToInt32(stagingEdition.EventBEID); if (!DateTime.TryParseExact(stagingEdition.EventStartDate.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime eventStartDate)) { eventStartDate = new DateTime(1970, 1, 1); } if (!DateTime.TryParseExact(stagingEdition.EventEndDate.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime eventEndDate)) { eventEndDate = new DateTime(1970, 1, 1); } var existingEdition = EditionServices.GetEditionByAxId(axId); if (existingEdition != null) // UPDATE { TaskServices.UpdateEventEditionFromStagingDb(existingEdition, stagingEdition, eventStartDate, eventEndDate); } else // CREATE { TaskServices.CreateEventEditionFromStagingDb(stagingEdition, eventStartDate, eventEndDate); } if (!string.IsNullOrWhiteSpace(connectionId)) { ProgressHub.SendProgress(connectionId, stagingEdition.EventName, i + 1, stagingEditions.Count, TaskType.UpdateEventsFromStagingDb.GetHashCode()); } } var log = CreateInternalLog("The task UpdateEventsFromStagingDb completed.", AutoIntegrationUser); ExternalLogHelper.Log(log, LoggingEventType.Information); return(Json("", JsonRequestBehavior.AllowGet)); } catch (Exception exc) { var message = "The task UpdateEventsFromStagingDb failed! " + exc.GetFullMessage(); ExternalLogHelper.Log(message, LoggingEventType.Fatal); return(Json(false, JsonRequestBehavior.AllowGet)); } } return(Json(false, JsonRequestBehavior.AllowGet)); }