public ActionResult DownloadFile(int downloadId) { var download = _downloadService.GetDownloadById(downloadId); if (download == null) { return(Content(T("Common.Download.NoDataAvailable"))); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { //use stored data var data = _downloadService.LoadDownloadBinary(download); if (data == null || data.LongLength == 0) { return(Content(T("Common.Download.NoDataAvailable"))); } var fileName = download.MediaFile.Name; var contentType = download.MediaFile.MimeType; return(new FileContentResult(data, contentType) { FileDownloadName = fileName }); } }
public ActionResult DownloadFile(int downloadId) { var download = _downloadService.GetDownloadById(downloadId); if (download == null) { return(Content(T("Common.Download.NoDataAvailable"))); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { //use stored data var data = _downloadService.LoadDownloadBinary(download); if (data == null || data.LongLength == 0) { return(Content(T("Common.Download.NoDataAvailable"))); } var fileName = (download.Filename.HasValue() ? download.Filename : downloadId.ToString()); var contentType = (download.ContentType.HasValue() ? download.ContentType : "application/octet-stream"); return(new FileContentResult(data, contentType) { FileDownloadName = fileName + download.Extension }); } }
public ActionResult Sample(int id /* productId */) { var product = _productService.GetProductById(id); if (product == null) { return(HttpNotFound()); } if (!product.HasSampleDownload) { return(Content(T("Common.Download.HasNoSample"))); } var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault()); if (download == null) { return(Content(T("Common.Download.SampleNotAvailable"))); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } return(GetFileContentResultFor(download, product)); }
public ActionResult Sample(int productId) { var product = _productService.GetProductById(productId); if (product == null) { return(HttpNotFound()); } if (!product.HasSampleDownload) { NotifyError(T("Common.Download.HasNoSample")); return(RedirectToRoute("Product", new { SeName = product.GetSeName() })); } var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault()); if (download == null) { NotifyError(T("Common.Download.SampleNotAvailable")); return(RedirectToRoute("Product", new { SeName = product.GetSeName() })); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } return(GetFileContentResultFor(download, product)); }
public ActionResult Index(UploadModel model) { var download = _downloadService.GetDownloadById(model.Id); Action <Download> uploadDelegate = _uploadCatalogService.UploadStructure; uploadDelegate.BeginInvoke(download, null, null); return(View(model)); }
public virtual async Task <IActionResult> DownloadFile(string id) { var customer = _workContext.CurrentCustomer; var lesson = await _courseLessonService.GetById(id); if (lesson == null || string.IsNullOrEmpty(lesson.AttachmentId)) { return(InvokeHttp404()); } var course = await _courseService.GetById(lesson.CourseId); if (course == null) { return(InvokeHttp404()); } if (!await CheckPermission(course, customer)) { return(InvokeHttp404()); } var download = await _downloadService.GetDownloadById(lesson.AttachmentId); if (download == null) { return(Content("No download record found with the specified id")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } //use stored data if (download.DownloadBinary == null) { return(Content(string.Format("Download data is not available any more. Download GD={0}", download.Id))); } string fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString(); string contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); }
/// <summary> /// 从内容中获取文件信息并下载 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Sample(int id /* articleId */) { var article = _articleService.GetArticleById(id); if (article == null) { return(HttpNotFound()); } if (!article.IsDownload) { return(Content("Article variant doesn't have a sample download.")); } var download = _downloadService.GetDownloadById(article.DownloadId); if (download == null) { return(Content("Sample download is not available any more.")); } if (!article.UnlimitedDownloads && article.DownloadCount >= article.MaxNumberOfDownloads) { return(Content(string.Format("You have reached maximum number of downloads {0}", article.MaxNumberOfDownloads))); } if (download.UseDownloadUrl) { article.DownloadCount++; _articleService.UpdateArticle(article); return(new RedirectResult(download.DownloadUrl)); } else { if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } //increase download article.DownloadCount++; _articleService.UpdateArticle(article); string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : article.Id.ToString(); string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); } }
public ActionResult DownloadFile(int downloadId) { var download = _downloadService.GetDownloadById(downloadId); if (download == null) { return(Content("No download record found with the specified id")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { //use stored data if (download.DownloadBinary == null) { return(Content(string.Format("Download data is not available any more. Download ID={0}", downloadId))); } string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : downloadId.ToString(); string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); } }
/// <summary> /// Prepare the customer return requests model /// </summary> /// <returns>Customer return requests model</returns> public virtual CustomerReturnRequestsModel PrepareCustomerReturnRequestsModel() { var model = new CustomerReturnRequestsModel(); var returnRequests = _returnRequestService.SearchReturnRequests(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id); foreach (var returnRequest in returnRequests) { var subscriptionItem = _subscriptionService.GetSubscriptionItemById(returnRequest.SubscriptionItemId); if (subscriptionItem != null) { var article = subscriptionItem.Article; var download = _downloadService.GetDownloadById(returnRequest.UploadedFileId); var itemModel = new CustomerReturnRequestsModel.ReturnRequestModel { Id = returnRequest.Id, CustomNumber = returnRequest.CustomNumber, ReturnRequestStatus = returnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, _workContext), ArticleId = article.Id, ArticleName = article.GetLocalized(x => x.Name), ArticleSeName = article.GetSeName(), Quantity = returnRequest.Quantity, ReturnAction = returnRequest.RequestedAction, ReturnReason = returnRequest.ReasonForReturn, Comments = returnRequest.CustomerComments, UploadedFileGuid = download != null ? download.DownloadGuid : Guid.Empty, CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc), }; model.Items.Add(itemModel); } } return(model); }
private Download CopyDownload(int downloadId) { var download = _downloadService.GetDownloadById(downloadId); if (download == null) { return(null); } var clone = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = download.UseDownloadUrl, DownloadUrl = download.DownloadUrl, ContentType = download.ContentType, Filename = download.Filename, Extension = download.Extension, IsNew = download.IsNew, UpdatedOnUtc = DateTime.UtcNow }; using (var scope = new DbContextScope(ctx: _productRepository.Context, autoCommit: true)) { _downloadService.InsertDownload(clone, download.MediaStorage?.Data); } return(clone); }
public ActionResult DownloadFile(int downloadId) { var download = _downloadService.GetDownloadById(downloadId); if (download == null) { throw new ArgumentException("No download record found with the specified id", "downloadId"); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { //use stored data if (download.DownloadBinary == null) { throw new NopException(string.Format("Download data is not available any more. Download ID={0}", downloadId)); } string fileName = download.Filename ?? downloadId.ToString(); return(new FileContentResult(download.DownloadBinary, download.ContentType) { FileDownloadName = fileName + download.Extension }); } }
/// <summary> /// Prepare the customer return requests model /// </summary> /// <returns>Customer return requests model</returns> public virtual CustomerReturnRequestsModel PrepareCustomerReturnRequestsModel() { var model = new CustomerReturnRequestsModel(); var returnRequests = _returnRequestService.SearchReturnRequests(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id); foreach (var returnRequest in returnRequests) { var orderItem = _orderService.GetOrderItemById(returnRequest.OrderItemId); if (orderItem != null) { var product = orderItem.Product; var download = _downloadService.GetDownloadById(returnRequest.UploadedFileId); var itemModel = new CustomerReturnRequestsModel.ReturnRequestModel { Id = returnRequest.Id, CustomNumber = returnRequest.CustomNumber, ReturnRequestStatus = _localizationService.GetLocalizedEnum(returnRequest.ReturnRequestStatus), ProductId = product.Id, ProductName = _localizationService.GetLocalized(product, x => x.Name), ProductSeName = _urlRecordService.GetSeName(product), Quantity = returnRequest.Quantity, ReturnAction = returnRequest.RequestedAction, ReturnReason = returnRequest.ReasonForReturn, Comments = returnRequest.CustomerComments, UploadedFileGuid = download != null ? download.DownloadGuid : Guid.Empty, CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc), }; model.Items.Add(itemModel); } } return(model); }
public virtual IActionResult Sample(int productId) { var product = _productService.GetProductById(productId); if (product == null) { return(InvokeHttp404()); } if (!product.HasSampleDownload) { return(Content("Product doesn't have a sample download.")); } var download = _downloadService.GetDownloadById(product.SampleDownloadId); if (download == null) { return(Content("Sample download is not available any more.")); } //A warning (SCS0027 - Open Redirect) from the "Security Code Scan" analyzer may appear at this point. //In this case, it is not relevant. Url may not be local. if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString(); var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); }
public ActionResult Sample(int productId) { var product = _productService.GetProductById(productId); if (product == null) { return(RedirectToRoute("HomePage")); } if (!product.HasSampleDownload) { return(Content("Product variant doesn't have a sample download.")); } var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault()); if (download == null) { return(Content("Sample download is not available any more.")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString(); string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); } }
public ActionResult Sample(int productVariantId) { var productVariant = _productService.GetProductVariantById(productVariantId); if (productVariant == null) { return(RedirectToAction("Index", "Home")); } if (!productVariant.HasSampleDownload) { return(Content("Product variant doesn't have a sample download.")); } var download = _downloadService.GetDownloadById(productVariant.SampleDownloadId); if (download == null) { return(Content("Sample download is not available any more.")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } else { if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } string fileName = download.Filename ?? productVariant.Id.ToString(); return(new FileContentResult(download.DownloadBinary, download.ContentType) { FileDownloadName = fileName + download.Extension }); } }
public virtual IActionResult Sample(int productId) { var product = _productService.GetProductById(productId); if (product == null) { return(InvokeHttp404()); } if (!product.HasSampleDownload) { return(Content("Product doesn't have a sample download.")); } var download = _downloadService.GetDownloadById(product.SampleDownloadId); if (download == null) { return(Content("Sample download is not available any more.")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString(); var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); }
/// <summary> /// Prepare return request model /// </summary> /// <param name="model">Return request model</param> /// <param name="returnRequest">Return request</param> /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param> /// <returns>Return request model</returns> public virtual ReturnRequestModel PrepareReturnRequestModel(ReturnRequestModel model, ReturnRequest returnRequest, bool excludeProperties = false) { if (returnRequest == null) { return(model); } //fill in model values from the entity model ??= new ReturnRequestModel { Id = returnRequest.Id, CustomNumber = returnRequest.CustomNumber, CustomerId = returnRequest.CustomerId, Quantity = returnRequest.Quantity }; var customer = _customerService.GetCustomerById(returnRequest.CustomerId); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc); model.CustomerInfo = _customerService.IsRegistered(customer) ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"); model.UploadedFileGuid = _downloadService.GetDownloadById(returnRequest.UploadedFileId)?.DownloadGuid ?? Guid.Empty; var orderItem = _orderService.GetOrderItemById(returnRequest.OrderItemId); if (orderItem != null) { var order = _orderService.GetOrderById(orderItem.OrderId); var product = _productService.GetProductById(orderItem.ProductId); model.ProductId = product.Id; model.ProductName = product.Name; model.OrderId = order.Id; model.AttributeInfo = orderItem.AttributeDescription; model.CustomOrderNumber = order.CustomOrderNumber; } if (excludeProperties) { return(model); } model.ReasonForReturn = returnRequest.ReasonForReturn; model.RequestedAction = returnRequest.RequestedAction; model.CustomerComments = returnRequest.CustomerComments; model.StaffNotes = returnRequest.StaffNotes; model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId; return(model); }
public virtual async Task <IActionResult> Sample(string productId) { var product = await _productService.GetProductById(productId); if (product == null) { return(InvokeHttp404()); } if (!product.HasSampleDownload) { return(Content("Product doesn't have a sample download.")); } var download = await _downloadService.GetDownloadById(product.SampleDownloadId); if (download == null) { return(Content("Sample download is not available any more.")); } if (download.UseDownloadUrl) { return(new RedirectResult(download.DownloadUrl)); } if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString(); string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); }
protected virtual void PrepareReturnRequestModel(ReturnRequestModel model, ReturnRequest returnRequest, bool excludeProperties) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (returnRequest == null) { throw new ArgumentNullException(nameof(returnRequest)); } var orderItem = _orderService.GetOrderItemById(returnRequest.OrderItemId); if (orderItem != null) { model.ProductId = orderItem.ProductId; model.ProductName = orderItem.Product.Name; model.OrderId = orderItem.OrderId; model.AttributeInfo = orderItem.AttributeDescription; model.CustomOrderNumber = orderItem.Order.CustomOrderNumber; } model.Id = returnRequest.Id; model.CustomNumber = returnRequest.CustomNumber; model.CustomerId = returnRequest.CustomerId; var customer = returnRequest.Customer; model.CustomerInfo = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"); model.Quantity = returnRequest.Quantity; model.ReturnRequestStatusStr = returnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, _workContext); var download = _downloadService.GetDownloadById(returnRequest.UploadedFileId); model.UploadedFileGuid = download != null ? download.DownloadGuid : Guid.Empty; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc); if (!excludeProperties) { model.ReasonForReturn = returnRequest.ReasonForReturn; model.RequestedAction = returnRequest.RequestedAction; model.CustomerComments = returnRequest.CustomerComments; model.StaffNotes = returnRequest.StaffNotes; model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId; } }
public ProjectProgressListModel PrepareProjectProgressListModel(ProjectProgressSearchModel searchModel, Project project) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } //get researcher educations //chai //var researcherEducations = researcher.ResearcherEducations.OrderByDescending(edu => edu.Degree).ToList(); var projectProgresses = _projectService.GetAllProjectProgresses(project.Id).ToList(); //prepare list model var model = new ProjectProgressListModel { Data = projectProgresses.PaginationByRequestModel(searchModel).Select(x => { //fill in model values from the entity string guid = x.ProjectUploadId != 0 ? _downloadService.GetDownloadById(x.ProjectUploadId.Value).DownloadGuid.ToString() : string.Empty; var projectProfessorModel = new ProjectProgressModel { Id = x.Id, ProjectId = x.ProjectId, Comment = x.Comment, LastUpdateBy = x.LastUpdateBy, ModifiedName = CommonHelper.ConvertToThaiDate(x.Modified), ProgressStartDateName = CommonHelper.ConvertToThaiDate(x.ProgressStartDate), ProgressEndDateName = CommonHelper.ConvertToThaiDate(x.ProgressEndDate), ProgressStatusName = x.ProgressStatus.GetAttributeOfType <EnumMemberAttribute>().Value, DownloadGuid = guid, }; return(projectProfessorModel); }), Total = projectProgresses.Count }; return(model); }
public virtual async Task <IList <ShipmentModel.ShipmentNote> > PrepareShipmentNotes(Shipment shipment) { //shipment notes var shipmentNoteModels = new List <ShipmentModel.ShipmentNote>(); foreach (var shipmentNote in (await _shipmentService.GetShipmentNotes(shipment.Id)) .OrderByDescending(on => on.CreatedOnUtc)) { var download = await _downloadService.GetDownloadById(shipmentNote.DownloadId); shipmentNoteModels.Add(new ShipmentModel.ShipmentNote { Id = shipmentNote.Id, ShipmentId = shipment.Id, DownloadId = String.IsNullOrEmpty(shipmentNote.DownloadId) ? "" : shipmentNote.DownloadId, DownloadGuid = download != null ? download.DownloadGuid : Guid.Empty, DisplayToCustomer = shipmentNote.DisplayToCustomer, Note = shipmentNote.Note, CreatedOn = _dateTimeHelper.ConvertToUserTime(shipmentNote.CreatedOnUtc, DateTimeKind.Utc), CreatedByCustomer = shipmentNote.CreatedByCustomer }); } return(shipmentNoteModels); }
public virtual async Task <IList <ReturnRequestModel.ReturnRequestNote> > PrepareReturnRequestNotes(ReturnRequest returnRequest) { //return request notes var returnRequestNoteModels = new List <ReturnRequestModel.ReturnRequestNote>(); foreach (var returnRequestNote in (await _returnRequestService.GetReturnRequestNotes(returnRequest.Id)) .OrderByDescending(on => on.CreatedOnUtc)) { var download = await _downloadService.GetDownloadById(returnRequestNote.DownloadId); returnRequestNoteModels.Add(new ReturnRequestModel.ReturnRequestNote { Id = returnRequestNote.Id, ReturnRequestId = returnRequest.Id, DownloadId = String.IsNullOrEmpty(returnRequestNote.DownloadId) ? "" : returnRequestNote.DownloadId, DownloadGuid = download != null ? download.DownloadGuid : Guid.Empty, DisplayToCustomer = returnRequestNote.DisplayToCustomer, Note = returnRequestNote.FormatReturnRequestNoteText(), CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequestNote.CreatedOnUtc, DateTimeKind.Utc), CreatedByCustomer = returnRequestNote.CreatedByCustomer }); } return(returnRequestNoteModels); }
public async Task <IActionResult> DownloadLicense(int downloadId) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManagePlugins)) { return(AccessDeniedView()); } var download = await _downloadService.GetDownloadById(downloadId); if (download == null) { return(Content("No download record found with the specified id")); } var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString(); var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); }
public virtual async Task <IList <MerchandiseReturnModel.MerchandiseReturnNote> > PrepareMerchandiseReturnNotes(MerchandiseReturn merchandiseReturn) { //merchandise return notes var merchandiseReturnNoteModels = new List <MerchandiseReturnModel.MerchandiseReturnNote>(); foreach (var merchandiseReturnNote in (await _merchandiseReturnService.GetMerchandiseReturnNotes(merchandiseReturn.Id)) .OrderByDescending(on => on.CreatedOnUtc)) { var download = await _downloadService.GetDownloadById(merchandiseReturnNote.DownloadId); merchandiseReturnNoteModels.Add(new MerchandiseReturnModel.MerchandiseReturnNote { Id = merchandiseReturnNote.Id, MerchandiseReturnId = merchandiseReturn.Id, DownloadId = String.IsNullOrEmpty(merchandiseReturnNote.DownloadId) ? "" : merchandiseReturnNote.DownloadId, DownloadGuid = download != null ? download.DownloadGuid : Guid.Empty, DisplayToCustomer = merchandiseReturnNote.DisplayToCustomer, Note = merchandiseReturnNote.Note, CreatedOn = _dateTimeService.ConvertToUserTime(merchandiseReturnNote.CreatedOnUtc, DateTimeKind.Utc), CreatedByCustomer = merchandiseReturnNote.CreatedByCustomer }); } return(merchandiseReturnNoteModels); }
/// <summary> /// Sends an email /// </summary> /// <param name="emailAccount">Email account to use</param> /// <param name="subject">Subject</param> /// <param name="body">Body</param> /// <param name="fromAddress">From address</param> /// <param name="fromName">From display name</param> /// <param name="toAddress">To address</param> /// <param name="toName">To display name</param> /// <param name="replyTo">ReplyTo address</param> /// <param name="replyToName">ReplyTo display name</param> /// <param name="bcc">BCC addresses list</param> /// <param name="cc">CC addresses list</param> /// <param name="attachmentFilePath">Attachment file path</param> /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param> /// <param name="attachedDownloadId">Attachment download ID (another attachment)</param> /// <param name="headers">Headers</param> public virtual void SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, string replyTo = null, string replyToName = null, IEnumerable <string> bcc = null, IEnumerable <string> cc = null, string attachmentFilePath = null, string attachmentFileName = null, int attachedDownloadId = 0, IDictionary <string, string> headers = null) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(fromName, fromAddress)); message.To.Add(new MailboxAddress(toName, toAddress)); if (!string.IsNullOrEmpty(replyTo)) { message.ReplyTo.Add(new MailboxAddress(replyToName, replyTo)); } //BCC if (bcc != null) { foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue))) { message.Bcc.Add(new MailboxAddress(address.Trim())); } } //CC if (cc != null) { foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue))) { message.Cc.Add(new MailboxAddress(address.Trim())); } } //content message.Subject = subject; //headers if (headers != null) { foreach (var header in headers) { message.Headers.Add(header.Key, header.Value); } } var multipart = new Multipart("mixed") { new TextPart(TextFormat.Html) { Text = body } }; //create the file attachment for this e-mail message if (!string.IsNullOrEmpty(attachmentFilePath) && _fileProvider.FileExists(attachmentFilePath)) { multipart.Add(CreateMimeAttachment(attachmentFilePath, attachmentFileName)); } //another attachment? if (attachedDownloadId > 0) { var download = _downloadService.GetDownloadById(attachedDownloadId); //we do not support URLs as attachments if (!download?.UseDownloadUrl ?? false) { multipart.Add(CreateMimeAttachment(download)); } } message.Body = multipart; //send email using var smtpClient = _smtpBuilder.Build(emailAccount); smtpClient.Send(message); smtpClient.Disconnect(true); }
/// <summary> /// Sends an email /// </summary> /// <param name="emailAccount">Email account to use</param> /// <param name="subject">Subject</param> /// <param name="body">Body</param> /// <param name="fromAddress">From address</param> /// <param name="fromName">From display name</param> /// <param name="toAddress">To address</param> /// <param name="toName">To display name</param> /// <param name="replyTo">ReplyTo address</param> /// <param name="replyToName">ReplyTo display name</param> /// <param name="bcc">BCC addresses list</param> /// <param name="cc">CC addresses list</param> /// <param name="attachmentFilePath">Attachment file path</param> /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param> /// <param name="attachedDownloadId">Attachment download ID (another attachedment)</param> public virtual async Task SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, string replyToAddress = null, string replyToName = null, IEnumerable <string> bccAddresses = null, IEnumerable <string> ccAddresses = null, string attachmentFilePath = null, string attachmentFileName = null, IEnumerable <string> attachedDownloads = null) { var message = new MimeMessage(); //from, to, reply to message.From.Add(new MailboxAddress(fromName, fromAddress)); message.To.Add(new MailboxAddress(toName, toAddress)); if (!String.IsNullOrEmpty(replyToAddress)) { message.ReplyTo.Add(new MailboxAddress(replyToName, replyToAddress)); } //BCC if (bccAddresses != null && bccAddresses.Any()) { foreach (var address in bccAddresses.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue))) { message.Bcc.Add(new MailboxAddress(address.Trim())); } } //CC if (ccAddresses != null && ccAddresses.Any()) { foreach (var address in ccAddresses.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue))) { message.Cc.Add(new MailboxAddress(address.Trim())); } } //subject message.Subject = subject; //content var builder = new BodyBuilder(); builder.HtmlBody = body; //create the file attachment for this e-mail message if (!String.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath)) { // TODO: should probably include a check for the attachmentFileName not being null or white space var attachment = new MimePart(_mimeMappingService.Map(attachmentFileName)) { Content = new MimeContent(File.OpenRead(attachmentFilePath), ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment) { CreationDate = File.GetCreationTime(attachmentFilePath), ModificationDate = File.GetLastWriteTime(attachmentFilePath), ReadDate = File.GetLastAccessTime(attachmentFilePath) }, ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(attachmentFilePath), }; builder.Attachments.Add(attachment); } //another attachment? if (attachedDownloads != null) { foreach (var attachedDownloadId in attachedDownloads) { var download = await _downloadService.GetDownloadById(attachedDownloadId); if (download != null) { //we do not support URLs as attachments if (!download.UseDownloadUrl) { string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id; fileName += download.Extension; var ms = new MemoryStream(download.DownloadBinary); var attachment = new MimePart(download.ContentType ?? _mimeMappingService.Map(fileName)) { Content = new MimeContent(ms, ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment) { CreationDate = DateTime.UtcNow, ModificationDate = DateTime.UtcNow, ReadDate = DateTime.UtcNow }, ContentTransferEncoding = ContentEncoding.Base64, FileName = fileName, }; builder.Attachments.Add(attachment); } } } } message.Body = builder.ToMessageBody(); //send email using (var smtpClient = new SmtpClient()) { smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => emailAccount.UseServerCertificateValidation; await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port, (SecureSocketOptions)emailAccount.SecureSocketOptionsId); await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password); await smtpClient.SendAsync(message); await smtpClient.DisconnectAsync(true); } }
public void SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, string replyToAddress = null, string replyToName = null, IEnumerable <string> bcc = null, IEnumerable <string> cc = null, string attachmentFilePath = null, string attachmentFileName = null, int attachedDownloadId = 0) { var message = new MailMessage(); message.From = new MailAddress(fromAddress, fromName); message.To.Add(new MailAddress(toAddress, toName)); if (!string.IsNullOrEmpty(replyToAddress)) { message.ReplyToList.Add(new MailAddress(replyToAddress, replyToName)); } if (bcc != null) { foreach (var address in bcc.Where(m => !string.IsNullOrWhiteSpace(m))) { message.Bcc.Add(address.Trim()); } } if (cc != null) { foreach (var address in cc.Where(m => !string.IsNullOrEmpty(m))) { message.CC.Add(address.Trim()); } } message.Subject = subject; message.Body = body; message.IsBodyHtml = true; if (!string.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath)) { var attachment = new Attachment(attachmentFilePath); attachment.ContentDisposition.CreationDate = File.GetCreationTime(attachmentFilePath); attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath); attachment.ContentDisposition.ReadDate = File.GetLastAccessTime(attachmentFilePath); if (!string.IsNullOrEmpty(attachmentFileName)) { attachment.Name = attachmentFileName; } message.Attachments.Add(attachment); } if (attachedDownloadId > 0) { var download = _downloadService.GetDownloadById(attachedDownloadId); if (download != null) { if (!download.UseDownloadUrl) { string fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString(); fileName += download.Extension; var ms = new MemoryStream(download.DownloadBinary); var attachment = new Attachment(ms, fileName); attachment.ContentDisposition.CreationDate = DateTime.UtcNow; attachment.ContentDisposition.ModificationDate = DateTime.UtcNow; attachment.ContentDisposition.ReadDate = DateTime.UtcNow; message.Attachments.Add(attachment); } } } using (var smtpClient = new SmtpClient()) { smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials; smtpClient.Host = emailAccount.Host; smtpClient.Port = emailAccount.Port; smtpClient.EnableSsl = emailAccount.EnableSsl; smtpClient.Credentials = emailAccount.UseDefaultCredentials ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(emailAccount.Username, emailAccount.Password); smtpClient.Send(message); } }
/// <summary> /// Create a copy of product with all depended data /// </summary> /// <param name="product">The product to copy</param> /// <param name="newName">The name of product duplicate</param> /// <param name="isPublished">A value indicating whether the product duplicate should be published</param> /// <param name="copyImages">A value indicating whether the product images should be copied</param> /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param> /// <returns>Product copy</returns> public virtual Product CopyProduct(Product product, string newName, bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true) { if (product == null) { throw new ArgumentNullException("product"); } if (String.IsNullOrEmpty(newName)) { throw new ArgumentException("Product name is required"); } //product download & sample download int downloadId = product.DownloadId; int sampleDownloadId = product.SampleDownloadId; if (product.IsDownload) { var download = _downloadService.GetDownloadById(product.DownloadId); if (download != null) { var downloadCopy = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = download.UseDownloadUrl, DownloadUrl = download.DownloadUrl, DownloadBinary = download.DownloadBinary, ContentType = download.ContentType, Filename = download.Filename, Extension = download.Extension, IsNew = download.IsNew, }; _downloadService.InsertDownload(downloadCopy); downloadId = downloadCopy.Id; } if (product.HasSampleDownload) { var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId); if (sampleDownload != null) { var sampleDownloadCopy = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = sampleDownload.UseDownloadUrl, DownloadUrl = sampleDownload.DownloadUrl, DownloadBinary = sampleDownload.DownloadBinary, ContentType = sampleDownload.ContentType, Filename = sampleDownload.Filename, Extension = sampleDownload.Extension, IsNew = sampleDownload.IsNew }; _downloadService.InsertDownload(sampleDownloadCopy); sampleDownloadId = sampleDownloadCopy.Id; } } } // product var productCopy = new Product { ProductTypeId = product.ProductTypeId, ParentGroupedProductId = product.ParentGroupedProductId, VisibleIndividually = product.VisibleIndividually, Name = newName, ShortDescription = product.ShortDescription, FullDescription = product.FullDescription, VendorId = product.VendorId, ProductTemplateId = product.ProductTemplateId, AdminComment = product.AdminComment, ShowOnHomePage = product.ShowOnHomePage, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, MetaTitle = product.MetaTitle, AllowCustomerReviews = product.AllowCustomerReviews, LimitedToStores = product.LimitedToStores, Sku = product.Sku, ManufacturerPartNumber = product.ManufacturerPartNumber, Gtin = product.Gtin, IsGiftCard = product.IsGiftCard, GiftCardType = product.GiftCardType, OverriddenGiftCardAmount = product.OverriddenGiftCardAmount, RequireOtherProducts = product.RequireOtherProducts, RequiredProductIds = product.RequiredProductIds, AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts, IsDownload = product.IsDownload, DownloadId = downloadId, UnlimitedDownloads = product.UnlimitedDownloads, MaxNumberOfDownloads = product.MaxNumberOfDownloads, DownloadExpirationDays = product.DownloadExpirationDays, DownloadActivationType = product.DownloadActivationType, HasSampleDownload = product.HasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = product.HasUserAgreement, UserAgreementText = product.UserAgreementText, IsRecurring = product.IsRecurring, RecurringCycleLength = product.RecurringCycleLength, RecurringCyclePeriod = product.RecurringCyclePeriod, RecurringTotalCycles = product.RecurringTotalCycles, IsRental = product.IsRental, RentalPriceLength = product.RentalPriceLength, RentalPricePeriod = product.RentalPricePeriod, IsShipEnabled = product.IsShipEnabled, IsFreeShipping = product.IsFreeShipping, ShipSeparately = product.ShipSeparately, AdditionalShippingCharge = product.AdditionalShippingCharge, DeliveryDateId = product.DeliveryDateId, IsTaxExempt = product.IsTaxExempt, TaxCategoryId = product.TaxCategoryId, IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices, ManageInventoryMethod = product.ManageInventoryMethod, ProductAvailabilityRangeId = product.ProductAvailabilityRangeId, UseMultipleWarehouses = product.UseMultipleWarehouses, WarehouseId = product.WarehouseId, StockQuantity = product.StockQuantity, DisplayStockAvailability = product.DisplayStockAvailability, DisplayStockQuantity = product.DisplayStockQuantity, MinStockQuantity = product.MinStockQuantity, LowStockActivityId = product.LowStockActivityId, NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow, BackorderMode = product.BackorderMode, AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions, OrderMinimumQuantity = product.OrderMinimumQuantity, OrderMaximumQuantity = product.OrderMaximumQuantity, AllowedQuantities = product.AllowedQuantities, AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations, NotReturnable = product.NotReturnable, DisableBuyButton = product.DisableBuyButton, DisableWishlistButton = product.DisableWishlistButton, AvailableForPreOrder = product.AvailableForPreOrder, PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc, CallForPrice = product.CallForPrice, Price = product.Price, OldPrice = product.OldPrice, ProductCost = product.ProductCost, SpecialPrice = product.SpecialPrice, SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = product.SpecialPriceEndDateTimeUtc, CustomerEntersPrice = product.CustomerEntersPrice, MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice, BasepriceEnabled = product.BasepriceEnabled, BasepriceAmount = product.BasepriceAmount, BasepriceUnitId = product.BasepriceUnitId, BasepriceBaseAmount = product.BasepriceBaseAmount, BasepriceBaseUnitId = product.BasepriceBaseUnitId, MarkAsNew = product.MarkAsNew, MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc, MarkAsNewEndDateTimeUtc = product.MarkAsNewEndDateTimeUtc, Weight = product.Weight, Length = product.Length, Width = product.Width, Height = product.Height, AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc, AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc, DisplayOrder = product.DisplayOrder, Published = isPublished, Deleted = product.Deleted, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow }; //validate search engine name _productService.InsertProduct(productCopy); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0); var languages = _languageService.GetAllLanguages(true); //localization foreach (var lang in languages) { var name = product.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id); } var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(shortDescription)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id); } var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(fullDescription)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id); } var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false); if (!String.IsNullOrEmpty(metaKeywords)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id); } var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(metaDescription)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id); } var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false); if (!String.IsNullOrEmpty(metaTitle)) { _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id); } //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id); } //product tags foreach (var productTag in product.ProductTags) { productCopy.ProductTags.Add(productTag); } _productService.UpdateProduct(productCopy); //product pictures //variable to store original and new picture identifiers var originalNewPictureIdentifiers = new Dictionary <int, int>(); if (copyImages) { foreach (var productPicture in product.ProductPictures) { var picture = productPicture.Picture; var pictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(picture), picture.MimeType, _pictureService.GetPictureSeName(newName), picture.AltAttribute, picture.TitleAttribute); _productService.InsertProductPicture(new ProductPicture { ProductId = productCopy.Id, PictureId = pictureCopy.Id, DisplayOrder = productPicture.DisplayOrder }); originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id); } } // product <-> warehouses mappings foreach (var pwi in product.ProductWarehouseInventory) { var pwiCopy = new ProductWarehouseInventory { ProductId = productCopy.Id, WarehouseId = pwi.WarehouseId, StockQuantity = pwi.StockQuantity, ReservedQuantity = 0, }; productCopy.ProductWarehouseInventory.Add(pwiCopy); } _productService.UpdateProduct(productCopy); // product <-> categories mappings foreach (var productCategory in product.ProductCategories) { var productCategoryCopy = new ProductCategory { ProductId = productCopy.Id, CategoryId = productCategory.CategoryId, IsFeaturedProduct = productCategory.IsFeaturedProduct, DisplayOrder = productCategory.DisplayOrder }; _categoryService.InsertProductCategory(productCategoryCopy); } // product <-> manufacturers mappings foreach (var productManufacturers in product.ProductManufacturers) { var productManufacturerCopy = new ProductManufacturer { ProductId = productCopy.Id, ManufacturerId = productManufacturers.ManufacturerId, IsFeaturedProduct = productManufacturers.IsFeaturedProduct, DisplayOrder = productManufacturers.DisplayOrder }; _manufacturerService.InsertProductManufacturer(productManufacturerCopy); } // product <-> releated products mappings foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true)) { _productService.InsertRelatedProduct( new RelatedProduct { ProductId1 = productCopy.Id, ProductId2 = relatedProduct.ProductId2, DisplayOrder = relatedProduct.DisplayOrder }); } // product <-> cross sells mappings foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true)) { _productService.InsertCrossSellProduct( new CrossSellProduct { ProductId1 = productCopy.Id, ProductId2 = csProduct.ProductId2, }); } // product specifications foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes) { var psaCopy = new ProductSpecificationAttribute { ProductId = productCopy.Id, AttributeTypeId = productSpecificationAttribute.AttributeTypeId, SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId, CustomValue = productSpecificationAttribute.CustomValue, AllowFiltering = productSpecificationAttribute.AllowFiltering, ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage, DisplayOrder = productSpecificationAttribute.DisplayOrder }; _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy); } //store mapping var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product); foreach (var id in selectedStoreIds) { _storeMappingService.InsertStoreMapping(productCopy, id); } // product <-> attributes mappings var associatedAttributes = new Dictionary <int, int>(); var associatedAttributeValues = new Dictionary <int, int>(); foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id)) { var productAttributeMappingCopy = new ProductAttributeMapping { ProductId = productCopy.Id, ProductAttributeId = productAttributeMapping.ProductAttributeId, TextPrompt = productAttributeMapping.TextPrompt, IsRequired = productAttributeMapping.IsRequired, AttributeControlTypeId = productAttributeMapping.AttributeControlTypeId, DisplayOrder = productAttributeMapping.DisplayOrder, ValidationMinLength = productAttributeMapping.ValidationMinLength, ValidationMaxLength = productAttributeMapping.ValidationMaxLength, ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions, ValidationFileMaximumSize = productAttributeMapping.ValidationFileMaximumSize, DefaultValue = productAttributeMapping.DefaultValue, //UNDONE copy ConditionAttributeXml (we should replace attribute IDs with new values) }; _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy); //save associated value (used for combinations copying) associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id); // product attribute values var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id); foreach (var productAttributeValue in productAttributeValues) { int attributeValuePictureId = 0; if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId)) { attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId]; } var attributeValueCopy = new ProductAttributeValue { ProductAttributeMappingId = productAttributeMappingCopy.Id, AttributeValueTypeId = productAttributeValue.AttributeValueTypeId, AssociatedProductId = productAttributeValue.AssociatedProductId, Name = productAttributeValue.Name, ColorSquaresRgb = productAttributeValue.ColorSquaresRgb, PriceAdjustment = productAttributeValue.PriceAdjustment, WeightAdjustment = productAttributeValue.WeightAdjustment, Cost = productAttributeValue.Cost, CustomerEntersQty = productAttributeValue.CustomerEntersQty, Quantity = productAttributeValue.Quantity, IsPreSelected = productAttributeValue.IsPreSelected, DisplayOrder = productAttributeValue.DisplayOrder, PictureId = attributeValuePictureId, }; //picture associated to "iamge square" attribute type (if exists) if (productAttributeValue.ImageSquaresPictureId > 0) { var origImageSquaresPicture = _pictureService.GetPictureById(productAttributeValue.ImageSquaresPictureId); if (origImageSquaresPicture != null) { //copy the picture var imageSquaresPictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(origImageSquaresPicture), origImageSquaresPicture.MimeType, origImageSquaresPicture.SeoFilename, origImageSquaresPicture.AltAttribute, origImageSquaresPicture.TitleAttribute); attributeValueCopy.ImageSquaresPictureId = imageSquaresPictureCopy.Id; } } _productAttributeService.InsertProductAttributeValue(attributeValueCopy); //save associated value (used for combinations copying) associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id); //localization foreach (var lang in languages) { var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) { _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id); } } } } //attribute combinations foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id)) { //generate new AttributesXml according to new value IDs string newAttributesXml = ""; var parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml); foreach (var oldAttribute in parsedProductAttributes) { if (associatedAttributes.ContainsKey(oldAttribute.Id)) { var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]); if (newAttribute != null) { var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id); foreach (var oldAttributeValueStr in oldAttributeValuesStr) { if (newAttribute.ShouldHaveValues()) { //attribute values int oldAttributeValue = int.Parse(oldAttributeValueStr); if (associatedAttributeValues.ContainsKey(oldAttributeValue)) { var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]); if (newAttributeValue != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newAttribute, newAttributeValue.Id.ToString()); } } } else { //just a text newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newAttribute, oldAttributeValueStr); } } } } } var combinationCopy = new ProductAttributeCombination { ProductId = productCopy.Id, AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders, Sku = combination.Sku, ManufacturerPartNumber = combination.ManufacturerPartNumber, Gtin = combination.Gtin, OverriddenPrice = combination.OverriddenPrice, NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow }; _productAttributeService.InsertProductAttributeCombination(combinationCopy); } //tier prices foreach (var tierPrice in product.TierPrices) { _productService.InsertTierPrice( new TierPrice { ProductId = productCopy.Id, StoreId = tierPrice.StoreId, CustomerRoleId = tierPrice.CustomerRoleId, Quantity = tierPrice.Quantity, Price = tierPrice.Price }); } // product <-> discounts mapping foreach (var discount in product.AppliedDiscounts) { productCopy.AppliedDiscounts.Add(discount); _productService.UpdateProduct(productCopy); } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productCopy); _productService.UpdateHasDiscountsApplied(productCopy); //associated products if (copyAssociatedProducts) { var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true); foreach (var associatedProduct in associatedProducts) { var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name), isPublished, copyImages, false); associatedProductCopy.ParentGroupedProductId = productCopy.Id; _productService.UpdateProduct(productCopy); } } return(productCopy); }
/// <summary> /// Sends an email /// </summary> /// <param name="emailAccount">Email account to use</param> /// <param name="subject">Subject</param> /// <param name="body">Body</param> /// <param name="fromAddress">From address</param> /// <param name="fromName">From display name</param> /// <param name="toAddress">To address</param> /// <param name="toName">To display name</param> /// <param name="replyTo">ReplyTo address</param> /// <param name="replyToName">ReplyTo display name</param> /// <param name="bcc">BCC addresses list</param> /// <param name="cc">CC addresses list</param> /// <param name="attachmentFilePath">Attachment file path</param> /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param> /// <param name="attachedDownloadId">Attachment download ID (another attachedment)</param> /// <param name="headers">Headers</param> public virtual void SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, string replyTo = null, string replyToName = null, IEnumerable <string> bcc = null, IEnumerable <string> cc = null, string attachmentFilePath = null, string attachmentFileName = null, int attachedDownloadId = 0, IDictionary <string, string> headers = null) { var message = new MailMessage { //from, to, reply to From = new MailAddress(fromAddress, fromName) }; message.To.Add(new MailAddress(toAddress, toName)); if (!string.IsNullOrEmpty(replyTo)) { message.ReplyToList.Add(new MailAddress(replyTo, replyToName)); } //BCC if (bcc != null) { foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue))) { message.Bcc.Add(address.Trim()); } } //CC if (cc != null) { foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue))) { message.CC.Add(address.Trim()); } } //content message.Subject = subject; message.Body = body; message.IsBodyHtml = true; //headers if (headers != null) { foreach (var header in headers) { message.Headers.Add(header.Key, header.Value); } } //create the file attachment for this e-mail message if (!string.IsNullOrEmpty(attachmentFilePath) && _fileProvider.FileExists(attachmentFilePath)) { var attachment = new Attachment(attachmentFilePath); attachment.ContentDisposition.CreationDate = _fileProvider.GetCreationTime(attachmentFilePath); attachment.ContentDisposition.ModificationDate = _fileProvider.GetLastWriteTime(attachmentFilePath); attachment.ContentDisposition.ReadDate = _fileProvider.GetLastAccessTime(attachmentFilePath); if (!string.IsNullOrEmpty(attachmentFileName)) { attachment.Name = attachmentFileName; } message.Attachments.Add(attachment); } //another attachment? if (attachedDownloadId > 0) { var download = _downloadService.GetDownloadById(attachedDownloadId); if (download != null) { //we do not support URLs as attachments if (!download.UseDownloadUrl) { var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString(); fileName += download.Extension; var ms = new MemoryStream(download.DownloadBinary); var attachment = new Attachment(ms, fileName); //string contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; //var attachment = new Attachment(ms, fileName, contentType); attachment.ContentDisposition.CreationDate = DateTime.UtcNow; attachment.ContentDisposition.ModificationDate = DateTime.UtcNow; attachment.ContentDisposition.ReadDate = DateTime.UtcNow; message.Attachments.Add(attachment); } } } //send email using (var smtpClient = new SmtpClient()) { smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials; smtpClient.Host = emailAccount.Host; smtpClient.Port = emailAccount.Port; smtpClient.EnableSsl = emailAccount.EnableSsl; smtpClient.Credentials = emailAccount.UseDefaultCredentials ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(emailAccount.Username, emailAccount.Password); smtpClient.Send(message); } }
public ActionResult Index() { var model = new List <GoogleAnaliticsStats>(); var scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(); string clientId = _googleAnliticsSettings.ClientId; string keyPassword = "******"; var todayStat = new GoogleAnaliticsStatisticModel(); var week = new GoogleAnaliticsStatisticModel(); var mounth = new GoogleAnaliticsStatisticModel(); var year = new GoogleAnaliticsStatisticModel(); var download = _downloadService.GetDownloadById(_googleAnliticsSettings.PrivateKeyId); DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone; //today DateTime t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); if (!timeZone.IsInvalidTime(t1)) { DateTime startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); todayStat = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime1, nowDt); } DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; DateTime today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow)); if (!timeZone.IsInvalidTime(t2)) { DateTime startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); week = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime2, nowDt); } DateTime t3 = new DateTime(nowDt.Year, nowDt.Month, 1); if (!timeZone.IsInvalidTime(t3)) { DateTime startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); mounth = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime3, nowDt); } DateTime t4 = new DateTime(nowDt.Year, 1, 1); if (!timeZone.IsInvalidTime(t4)) { DateTime startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); year = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime4, nowDt); } model.Add(new GoogleAnaliticsStats() { Name = "Visitors", Today = todayStat.Visitors, Weekly = week.Visitors, Mounthly = mounth.Visitors, Year = year.Visitors }); model.Add(new GoogleAnaliticsStats() { Name = "Unique page views", Today = todayStat.UniquePageViews, Weekly = week.UniquePageViews, Mounthly = mounth.UniquePageViews, Year = year.UniquePageViews }); model.Add(new GoogleAnaliticsStats() { Name = "Average time on site", Today = todayStat.AverageTimeOnSite, Weekly = week.AverageTimeOnSite, Mounthly = mounth.AverageTimeOnSite, Year = year.AverageTimeOnSite }); model.Add(new GoogleAnaliticsStats() { Name = "Exit rate", Today = todayStat.ExitRate, Weekly = week.ExitRate, Mounthly = mounth.ExitRate, Year = year.ExitRate }); model.Add(new GoogleAnaliticsStats() { Name = "New to old visitors rate", Today = todayStat.NewToOldVisitorsRate, Weekly = week.NewToOldVisitorsRate, Mounthly = mounth.NewToOldVisitorsRate, Year = year.NewToOldVisitorsRate }); return(View(model)); }