public virtual ActionResult UpdateCaches() { var entry = LogService.Info("UpdateCaches begin"); MessageResult result = null; try { //Note: only for admin (for debugging purposes) Settings.SetCacheUpdateInProgress(false); var success = Cache.UpdateDbCacheUsingSettings(Db, Settings); if (success) { result = MessageResult.Success("Success updated"); } else { result = MessageResult.Error("Cache updating already in progress"); } } catch (Exception ex) { LogService.Error("UpdateCaches", ex, entry); result = MessageResult.Error(ex.Message); } LogService.Info("UpdateCaches end", entry); return(new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public static MessageResult CheckAddOrdersToBatch(IUnitOfWork db, string orderIds) { if (string.IsNullOrEmpty(orderIds)) { return(MessageResult.Success()); } var stringOrderIdList = orderIds.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var orderIdList = stringOrderIdList.Select(long.Parse).ToList(); var printedShippings = from sh in db.OrderShippingInfos.GetAllAsDto() join o in db.Orders.GetAll() on sh.OrderId equals o.Id where orderIdList.Contains(sh.OrderId) && !String.IsNullOrEmpty(sh.TrackingNumber) && o.IsForceVisible != true select sh; var printedMailing = db.MailLabelInfos.GetAllAsDto().Where(sh => orderIdList.Contains(sh.OrderId) && !sh.LabelCanceled && !sh.CancelLabelRequested).ToList(); if (printedShippings.Any() || printedMailing.Any()) { return(MessageResult.Error()); } return(MessageResult.Success()); }
public async Task <IActionResult> PhotoSave(IFormFile photo, CancellationToken cancellationToken) { if (photo != null && photo.Length > 0) { var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/photos", photo.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await photo.CopyToAsync(stream, cancellationToken); var returnPath = $"photos/{photo.FileName}"; var photoDto = new PhotoDto { Path = returnPath }; var result = DataResult <PhotoDto> .Success(photoDto, Contract.Enums.StatusCode.Ok); return(CreateResult(result)); } } var failResult = MessageResult.Error("When Image Upload An Occurrent Error", Contract.Enums.StatusCode.Failed); return(CreateMesageResult(failResult)); }
public static FieldCopyResult Copy(int id, int?forceId, int?forceLinkId, int[] forceVirtualFieldIds, int[] forceChildFieldIds, int[] forceChildLinkIds) { var result = new FieldCopyResult(); var field = FieldRepository.GetById(id); if (field == null) { throw new Exception(string.Format(FieldStrings.FieldNotFound, id)); } if (!field.Content.Site.IsUpdatable || !field.IsAccessible(ActionTypeCode.Read)) { result.Message = MessageResult.Error(ContentStrings.CannotCopyBecauseOfSecurity); return(result); } switch (field.ExactType) { case FieldExactTypes.M2ORelation: result.Message = MessageResult.Error(FieldStrings.UnableToCopyM2O); break; case FieldExactTypes.Classifier: result.Message = MessageResult.Error(FieldStrings.UnableToCopyClassifier); break; default: if (field.ExactType == FieldExactTypes.O2MRelation && field.Aggregated) { result.Message = MessageResult.Error(FieldStrings.UnableToCopyAggregator); } else { if (forceId.HasValue) { field.ForceId = forceId.Value; } field.ForceVirtualFieldIds = forceVirtualFieldIds; if (field.ContentLink != null && forceLinkId.HasValue) { field.ContentLink.ForceLinkId = forceLinkId.Value; } field.ForceChildFieldIds = forceChildFieldIds; field.ForceChildLinkIds = forceChildLinkIds; field.LoadVeBindings(); var resultField = FieldRepository.Copy(field); result.Id = resultField.Id; result.LinkId = resultField.LinkId; result.VirtualFieldIds = resultField.NewVirtualFieldIds; result.ChildFieldIds = resultField.ResultChildFieldIds; result.ChildLinkIds = resultField.ResultChildLinkIds; } break; } return(result); }
public MessageResult MultipleAssemblePage(int[] ids) { var failedIds = new List <int>(); foreach (var id in ids) { var page = PageRepository.GetPagePropertiesById(id); if (page.PageTemplate.SiteIsDotNet) { new AssemblePageController(id, QPContext.CurrentDbConnectionString).Assemble(); AssembleRepository.UpdatePageStatus(id, QPContext.CurrentUserId); } else { var token = _qp7Service.Authenticate(); var message = _qp7Service.AssemblePage(id, token); if (!string.IsNullOrEmpty(message)) { failedIds.Add(id); } } } return(failedIds.Any() ? MessageResult.Error(SiteStrings.AssemblePagesError + string.Join(", ", failedIds), failedIds.ToArray()) : null); }
public MessageResult Remove(int id) { var user = UserRepository.GetById(id, true); if (user == null) { throw new ApplicationException(string.Format(UserStrings.UserNotFound, id)); } if (user.BuiltIn) { return(MessageResult.Error(UserStrings.CannotRemoveBuitInUser)); } var notifications = new NotificationRepository().GetUserNotifications(id).ToList(); if (notifications.Any()) { var message = string.Join(",", notifications.Select(w => $"({w.Id}) \"{w.Name}\"")); return(MessageResult.Error(string.Format(UserStrings.NotificationsExist, message))); } var workflows = WorkflowRepository.GetUserWorkflows(id).ToList(); if (workflows.Any()) { var message = string.Join(",", workflows.Select(w => $"({w.Id}) \"{w.Name}\"")); return(MessageResult.Error(string.Format(UserStrings.WorkflowsExist, message))); } UserRepository.Delete(id); return(null); }
public static MessageResult MultipleRemove(int[] ds) { var result = CheckIdResult <Field> .Create(ds, ActionTypeCode.Remove); var removeMsgResults = new List <MessageResult>(); foreach (var id in result.ValidIds) { var violationMessages = Field.Die(id).ToList(); if (violationMessages.Any()) { removeMsgResults.Add(MessageResult.Error(string.Join(Environment.NewLine, violationMessages), new[] { id })); } } if (removeMsgResults.Count > 0) { var checkResult = result.GetServiceResult(); var ids = new List <int>(checkResult != null ? checkResult.FailedIds : new int[0]); foreach (var msgr in removeMsgResults) { ids.AddRange(msgr.FailedIds); } var msg = string.Concat(checkResult != null ? checkResult.Text : string.Empty, Environment.NewLine, string.Join("", removeMsgResults.Select(r => r.Text))); return(MessageResult.Error(msg, ids.Distinct().ToArray())); } return(result.GetServiceResult()); }
public static ContentCopyResult Copy(int id, int?forceId, int[] forceFieldIds, int[] forceLinkIds) { var result = new ContentCopyResult(); var content = ContentRepository.GetById(id); if (content == null) { throw new Exception(string.Format(ContentStrings.ContentNotFound, id)); } if (!content.Site.IsUpdatable || !content.IsAccessible(ActionTypeCode.Read)) { result.Message = MessageResult.Error(ContentStrings.CannotCopyBecauseOfSecurity); } if (!content.IsContentChangingActionsAllowed) { throw new ActionNotAllowedException(ContentStrings.ContentChangingIsProhibited); } if (result.Message == null) { content = ContentRepository.Copy(content, forceId, forceFieldIds, forceLinkIds, false); result.FieldIds = content.Fields.Select(n => n.Id).ToArray(); result.LinkIds = ContentRepository.GetContentLinks(content.Id).Select(n => n.LinkId).ToArray(); result.Id = content.Id; } return(result); }
public MessageResult Remove(int id) { var status = StatusTypeRepository.GetById(id); if (status == null) { throw new ApplicationException(string.Format(StatusTypeStrings.StatusTypeNotFound, id)); } if (status.BuiltIn) { return(MessageResult.Error(StatusTypeStrings.StatusBuiltIn)); } if (StatusTypeRepository.IsInUseWithArticle(id)) { return(MessageResult.Error(StatusTypeStrings.StatusArticleUsage)); } if (StatusTypeRepository.IsInUseWithWorkflow(id)) { return(MessageResult.Error(StatusTypeStrings.StatusWorkflowUsage)); } StatusTypeRepository.SetNullAssociatedNotificationsStatusTypesIds(id); StatusTypeRepository.RemoveAssociatedContentItemsStatusHistoryRecords(id); StatusTypeRepository.RemoveAssociatedWaitingForApprovalRecords(id); StatusTypeRepository.Delete(id); return(null); }
public virtual ActionResult UploadInvoice(HttpPostedFileBase invoiceFile) { LogI("UploadInvoice"); try { if (invoiceFile != null) { LogI("fileLength=" + invoiceFile.ContentLength + ", fileName=" + invoiceFile.FileName); if (invoiceFile.ContentLength > 0) { var fileName = Path.GetFileName(invoiceFile.FileName); var folderPath = Models.UrlHelper.GetUploadDhlInvoicePath(); var filePath = Path.Combine(folderPath, fileName); invoiceFile.SaveAs(filePath); var dhlService = new DhlInvoiceService(LogService, Time, DbFactory); var records = dhlService.GetRecordsFromFile(filePath); dhlService.ProcessRecords(records, ShipmentProviderType.Dhl); return(Json(MessageResult.Success("Invoice file has been processed"))); } } return(Json(MessageResult.Error("Empty file"))); } catch (Exception ex) { LogE("UploadInvoice, file=" + invoiceFile.FileName, ex); return(Json(MessageResult.Error(ex.Message))); } }
public CopyResult Copy(int id, int[] selectedActionsIds) { var result = new CopyResult(); var action = ReadForModify(id); action.Id = 0; if (action.Action != null) { action.Action.Id = 0; } if (action == null) { throw new Exception(string.Format(CustomActionStrings.ActionNotFoundByCode, id)); } if (!action.IsUpdatable || !action.IsAccessible(ActionTypeCode.Read)) { result.Message = MessageResult.Error(CustomActionStrings.CannotCopyBecauseOfSecurity); } if (result.Message == null) { action = Normalize(action, selectedActionsIds); action = CustomActionRepository.Copy(action); } return(result); }
public virtual JsonResult Redistribute(long styleId) { LogI("Redistribute, styleId=" + styleId); try { var quantityManager = new QuantityManager(LogService, Time); var service = new QuantityDistributionService(DbFactory, quantityManager, LogService, Time, QuantityDistributionHelper.GetDistributionMarkets(), DistributeMode.None); var listings = service.RedistributeForStyle(Db, styleId); return(new JsonResult() { Data = ValueResult <IList <ListingQuantityDTO> > .Success("Quantity was redistributed", listings), JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } catch (Exception ex) { LogE("Redistribute, styleId=" + styleId, ex); return(new JsonResult() { Data = MessageResult.Error(ex.Message), JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } }
public static MessageResult AssembleContents(int id) { var site = SiteRepository.GetById(id); if (site == null) { throw new Exception(string.Format(SiteStrings.SiteNotFound, id)); } if (!site.IsDotNet) { return(MessageResult.Error(string.Format(SiteStrings.ShouldBeDotNet))); } var sqlMetalPath = QPConfiguration.ConfigVariable(Config.SqlMetalKey); if (site.ExternalDevelopment) { var liveTempDirectory = $@"{site.TempDirectoryForClasses}\live"; var stageTempDirectory = $@"{site.TempDirectoryForClasses}\stage"; if (Directory.Exists(liveTempDirectory)) { Directory.Delete(liveTempDirectory, true); } Directory.CreateDirectory(liveTempDirectory); if (Directory.Exists(stageTempDirectory)) { Directory.Delete(stageTempDirectory, true); } Directory.CreateDirectory(stageTempDirectory); if (File.Exists(site.TempArchiveForClasses)) { File.Delete(site.TempArchiveForClasses); } new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString) { SiteRoot = liveTempDirectory, IsLive = true, DisableClassGeneration = site.DownloadEfSource }.Assemble(); new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString) { SiteRoot = stageTempDirectory, IsLive = false, DisableClassGeneration = site.DownloadEfSource }.Assemble(); ZipFile.CreateFromDirectory(site.TempDirectoryForClasses, site.TempArchiveForClasses); return(MessageResult.Download($"/Backend/Site/GetClassesZip/{id}")); } new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString).Assemble(); return(null); }
public static MessageResult AssembleContents(int id) { var site = SiteRepository.GetById(id); if (site == null) { throw new Exception(string.Format(SiteStrings.SiteNotFound, id)); } if (!site.IsDotNet) { return(MessageResult.Error(string.Format(SiteStrings.ShouldBeDotNet))); } var sqlMetalPath = QPConfiguration.ConfigVariable(Config.SqlMetalKey); var extDbType = (QP.ConfigurationService.Models.DatabaseType)QPContext.DatabaseType; if (site.ExternalDevelopment) { var liveTempDirectory = $@"{site.TempDirectoryForClasses}{Path.DirectorySeparatorChar}live"; var stageTempDirectory = $@"{site.TempDirectoryForClasses}{Path.DirectorySeparatorChar}stage"; if (Directory.Exists(liveTempDirectory)) { Directory.Delete(liveTempDirectory, true); } Directory.CreateDirectory(liveTempDirectory); if (Directory.Exists(stageTempDirectory)) { Directory.Delete(stageTempDirectory, true); } Directory.CreateDirectory(stageTempDirectory); if (File.Exists(site.TempArchiveForClasses)) { File.Delete(site.TempArchiveForClasses); } new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString, extDbType) { SiteRoot = liveTempDirectory, IsLive = true, DisableClassGeneration = site.DownloadEfSource }.Assemble(); new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString, extDbType) { SiteRoot = stageTempDirectory, IsLive = false, DisableClassGeneration = site.DownloadEfSource }.Assemble(); var urlHelper = HttpContext.RequestServices.GetRequiredService <IUrlHelper>(); ZipFile.CreateFromDirectory(site.TempDirectoryForClasses, site.TempArchiveForClasses); return(MessageResult.Download(urlHelper.Content($"~/Site/GetClassesZip/{id}"))); } new AssembleContentsController(id, sqlMetalPath, QPContext.CurrentDbConnectionString, extDbType).Assemble(); return(null); }
public virtual ActionResult AllRemoveAsChild(int parentId, int?userId, int?groupId) { if (!userId.HasValue && !groupId.HasValue) { return(JsonMessageResult(MessageResult.Error(EntityPermissionStrings.UserOrGroupAreNotSelected))); } return(JsonMessageResult(ChildContentService.RemoveAll(parentId, userId, groupId))); }
public override MessageResult RemoveAll(int parentId, int?userId, int?groupId) { if (ContentRepository.IsAnyAggregatedFields(parentId)) { return(MessageResult.Error(ArticleStrings.OperationIsNotAllowedForAggregated)); } return(base.RemoveAll(parentId, userId, groupId)); }
public override MessageResult MultipleRemove(int parentId, IEnumerable <int> entityIDs, int?userId, int?groupId) { if (ContentRepository.IsAnyAggregatedFields(parentId)) { return(MessageResult.Error(ArticleStrings.OperationIsNotAllowedForAggregated)); } return(base.MultipleRemove(parentId, entityIDs, userId, groupId)); }
public IEnumerable <IResult> Send() { WasCancelled = false; var files = Attachments.ToArray(); if (SendLog) { files = files.Concat(Directory.GetFiles(FileHelper.MakeRooted("."), "*.log")).ToArray(); } if (files.Length == 0) { TryClose(); yield break; } var task = new Task(() => { if (!String.IsNullOrEmpty(ArchiveName)) { File.Delete(ArchiveName); } ArchiveName = Path.GetTempFileName(); try { using (Util.FlushLogs()) using (var zip = new ZipFile()) { zip.AlternateEncoding = Encoding.UTF8; zip.AlternateEncodingUsage = ZipOption.AsNecessary; foreach (var attachment in files) { zip.AddFile(attachment, ""); } zip.Save(ArchiveName); } if (new FileInfo(ArchiveName).Length > 4 * 1024 * 1024) { throw new EndUserError("Размер архива с вложенными файлами превышает 4Мб."); } } catch (Exception) { File.Delete(ArchiveName); throw; } }); yield return(new TaskResult(task, new WaitViewModel("Проверка вложений.\r\nПожалуйста подождите."))); if (task.IsFaulted) { var message = task.Exception.GetBaseException().Message; yield return(MessageResult.Error(message)); } else { TryClose(); } }
public virtual ActionResult ResetShippings(string orderId) { LogI("ResetShippings begin, orderid=" + orderId); var result = MessageResult.Error("Undefined"); if (!string.IsNullOrEmpty(orderId)) { var syncInfo = new EmptySyncInformer(LogService, SyncType.Orders); var rateProviders = ServiceFactory.GetShipmentProviders(LogService, Time, DbFactory, WeightService, AccessManager.Company.ShipmentProviderInfoList, null, null, null, null); DTOOrder dtoOrder = Db.ItemOrderMappings.GetOrderWithItems(WeightService, orderId, unmaskReferenceStyle: false, includeSourceItems: true); if (dtoOrder != null) { dtoOrder.OrderStatus = OrderStatusEnumEx.Unshipped; var synchronizer = new AmazonOrdersSynchronizer(LogService, AccessManager.Company, syncInfo, rateProviders, CompanyAddress, Time, WeightService, MessageService); if (synchronizer.UIUpdate(Db, dtoOrder, true, false, keepCustomShipping: false, switchToMethodId: null)) { var dbOrder = Db.Orders.Get(dtoOrder.Id); dbOrder.OrderStatus = OrderStatusEnum.Unshipped.ToString(); dbOrder.UpgradeLevel = null; Db.Commit(); result = MessageResult.Success("Success updates"); } } else { result = MessageResult.Error("Not found OrderId: " + orderId); } } else { result = MessageResult.Error("OrderId is empty"); } return(new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public async Task <MessageResult> DeleteAsync(string id) { var result = await _courseCollection.DeleteOneAsync(x => x.Id == id); if (result.DeletedCount > 0) { return(MessageResult.Success(StatusCode.OkNoContent)); } return(MessageResult.Error("Will delete data not found", StatusCode.NotFound)); }
public async Task <MessageResult> UpdateAsync(CourseUpdateDto categoryDto) { var course = _mapper.Map <Course>(categoryDto); var result = await _courseCollection.FindOneAndReplaceAsync(x => x.Id == course.Id, course); if (result == null) { return(MessageResult.Error("Will update data not found", StatusCode.NotFound)); } return(MessageResult.Success(StatusCode.Ok)); }
public MessageResult WriteMessage() { string msg = "你好"; if (string.IsNullOrEmpty(msg)) { return(MessageResult.Error("传入消息不能为空")); } var result = IBMMqService.WriteMessage(msg); return(result); }
protected override void ProcessProduct(int productId, Dictionary <string, string> actionParameters) { if (productId == 0) { var result = MessageResult.Error("MessageResult Error", new[] { 1, 2, 3 }); ValidateMessageResult(productId, result); } if (productId % 2 == 0) { throw new Exception(); } }
public MessageResult AssembleObject(int id) { var obj = ObjectRepository.GetObjectPropertiesById(id); if (obj.PageTemplate.SiteIsDotNet) { new AssembleSelectedObjectsController(id.ToString(), QPContext.CurrentDbConnectionString).Assemble(); return(null); } return(MessageResult.Error(SiteStrings.ShouldBeDotNet)); }
public static MessageResult SimpleRemove(int id) { var item = ContentRepository.GetById(id); if (item == null) { throw new ApplicationException(string.Format(FieldStrings.FieldNotFound, id)); } var violationMessages = item.Die().ToList(); return(violationMessages.Any() ? MessageResult.Error(string.Join(Environment.NewLine, violationMessages), new[] { id }) : null); }
public MessageResult AssemblePage(int id) { var page = PageRepository.GetPagePropertiesById(id); if (page.PageTemplate.SiteIsDotNet) { new AssemblePageController(id, QPContext.CurrentDbConnectionString).Assemble(); AssembleRepository.UpdatePageStatus(id, QPContext.CurrentUserId); return(null); } return(MessageResult.Error(SiteStrings.ShouldBeDotNet)); }
public override MessageResult PreAction(int parentId, int templateId) { var site = SiteRepository.GetById(parentId); if (site == null) { return(MessageResult.Error(string.Format(SiteStrings.SiteNotFound, parentId), new[] { parentId })); } if (site.IsLive) { return(MessageResult.Confirm(TemplateStrings.AssembleLiveSiteTemplateConfirmation, new[] { parentId })); } return(null); }
public IActionResult PhotoDelete(string photoUrl) { var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/photos", photoUrl); if (!System.IO.File.Exists(path)) { var failResult = MessageResult.Error("Will Delete Photo Not Found", Contract.Enums.StatusCode.NotFound); return(CreateMesageResult(failResult)); } System.IO.File.Delete(path); var successResult = MessageResult.Success(Contract.Enums.StatusCode.OkNoContent); return(CreateMesageResult(successResult)); }
public static MessageResult MoveToArchive(Article articleToArchive, bool?boundToExternal, bool disableNotifications) { if (articleToArchive == null) { throw new Exception(string.Format(ArticleStrings.ArticleNotFound, articleToArchive.Id)); } if (articleToArchive.IsAggregated) { return(MessageResult.Error(ArticleStrings.OperationIsNotAllowedForAggregated)); } if (!articleToArchive.IsArticleChangingActionsAllowed(boundToExternal)) { return(MessageResult.Error(ContentStrings.ArticleChangingIsProhibited)); } if (articleToArchive.LockedByAnyoneElse) { return(MessageResult.Error(string.Format(ArticleStrings.LockedByAnyoneElse, articleToArchive.LockedByDisplayName))); } if (!articleToArchive.IsAccessible(ActionTypeCode.Archive)) { return(MessageResult.Error(ArticleStrings.CannotUpdateBecauseOfSecurity)); } if (!articleToArchive.IsUpdatableWithWorkflow) { return(MessageResult.Error(ArticleStrings.CannotRemoveBecauseOfWorkflow)); } if (!articleToArchive.IsUpdatableWithRelationSecurity) { return(MessageResult.Error(ArticleStrings.CannotUpdateBecauseOfRelationSecurity)); } var idsToProceed = articleToArchive.SelfAndChildIds; var repo = new NotificationPushRepository(); repo.PrepareNotifications(articleToArchive, new[] { NotificationCode.Update }, disableNotifications); ArticleRepository.SetArchiveFlag(idsToProceed, true); repo.SendNotifications(); return(null); }
public ActionResult Proxy([FromBody] ProxyViewModel model) { var urlToProcess = UrlHelpers.ConvertToAbsoluteUrl(model.Url); Logger.Debug() .Message("Proxying custom action url: {url}", urlToProcess) .Write(); var parts = urlToProcess.Split("?".ToCharArray(), 2); var request = WebRequest.Create(parts[0]); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var postBytes = new ASCIIEncoding().GetBytes(parts[1]); request.ContentLength = postBytes.Length; using (var postStream = request.GetRequestStream()) { postStream.Write(postBytes, 0, postBytes.Length); postStream.Flush(); postStream.Close(); } try { var result = string.Empty; var response = request.GetResponse().GetResponseStream(); if (response != null) { result = new StreamReader(response).ReadToEnd(); } if (model.Level >= PermissionLevel.Modify) { CreateLogs(model.ActionCode, model.Ids, model.ParentEntityId); } return(Content(result)); } catch (Exception ex) { return(JsonMessageResult(MessageResult.Error(ex.Message))); } }