public ActionResult ImportFromUrl(int orderItemNodeId, string url) { // Json response var json = new ResultResponse(); Stream stream = null; try { HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url); fileReq.CookieContainer = new CookieContainer(); fileReq.AllowAutoRedirect = true; HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse(); stream = fileResp.GetResponseStream(); var orderItem = _orderItemManager.GetOrderItem(orderItemNodeId); var cdPattern = new Regex("filename=\"?(.*)\"?(?:;|$)"); var fileEndingPattern = new Regex("(?i)\\.(?:pdf|txt|tif|tiff)$"); string name = ""; if (fileEndingPattern.IsMatch(url)) { name = fileResp.ResponseUri.AbsoluteUri.Substring(fileResp.ResponseUri.AbsoluteUri.LastIndexOf("/") + 1); } else { name = cdPattern.Match(fileResp.Headers["Content-Disposition"]).Groups[1].Value; } if (String.IsNullOrEmpty(name)) { throw new Exception("Not a valid document."); } else { var savedMediaItem = _mediaItemManager.CreateMediaItem(name, orderItem.NodeId, orderItem.OrderId, stream, fileResp.ContentType); var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE); _orderItemManager.AddExistingMediaItemAsAnAttachment(orderItem.NodeId, savedMediaItem.Id, name, savedMediaItem.Url, eventId); json.Success = true; json.Message = "Document imported successfully."; } } catch (Exception e) { json.Success = false; json.Message = "Failed to import document: " + e.Message; } return(Json(json, JsonRequestBehavior.AllowGet)); }
public SourcePollingResult Poll() { _result = new SourcePollingResult("Huvudpostlåda"); // List of read mails List <MailQueueModel> list = null; // Connect to Exchange Service try { _exchangeMailWebApi.ConnectToExchangeService(ConfigurationManager.AppSettings["chalmersIllExhangeLogin"], ConfigurationManager.AppSettings["chalmersIllExhangePass"]); } catch (Exception e) { throw new SourcePollingException("Error connecting to Exchange Service.", e); } // Get a list of mails from Inbox folder try { list = _exchangeMailWebApi.ReadMailQueue(); } catch (Exception e) { throw new SourcePollingException("Error reading mail from Exchange.", e); } // Post processing of e-mails if (list.Count > 0) { try { string deliveryOrderId; foreach (MailQueueModel item in list) { try { var orderIdPattern = new Regex("#+(cthb-.{8}-[0-9]+)"); deliveryOrderId = getBoundOrder(item); // Bind the type of messages we have (NEW or REPLY) if ((item.Subject != null && item.Subject.Contains("#new")) || item.To.Contains("+new")) { item.Type = MailQueueType.NEW; } else if ((item.Subject != null && item.Subject.Contains("#cthb-"))) { item.OrderId = orderIdPattern.Match(item.Subject).Groups[1].Value; item.OrderItemNodeId = Convert.ToInt32(item.OrderId.Split('-').Last()); item.Type = MailQueueType.REPLY; FixLegacyNodeIds(item); } else if (item.To.Contains("+cthb-")) { item.OrderId = orderIdPattern.Match(item.To).Groups[1].Value; item.OrderItemNodeId = Convert.ToInt32(item.OrderId.Split('-').Last()); item.Type = MailQueueType.REPLY; FixLegacyNodeIds(item); } else if (deliveryOrderId != null) { item.OrderId = deliveryOrderId; item.OrderItemNodeId = Convert.ToInt32(deliveryOrderId.Split('-').Last()); item.Type = MailQueueType.DELIVERY; FixLegacyNodeIds(item); } else { item.Type = MailQueueType.UNKNOWN; } } catch (Exception e) { item.Type = MailQueueType.ERROR; item.ParseErrorMessage = "Chillin failed to process E-mail. Reason: " + e.Message; LogHelper.Error <SystemSurfaceController>("Failed to process one E-mail, tagging it with ERROR.", e); _result.Errors++; _result.Messages.Add(item.ParseErrorMessage); } } } catch (Exception e) { throw new SourcePollingException("Error when post processing E-mails.", e); } // Get SierraInfo to the list try { int indexet = 0; foreach (MailQueueModel item in list) { // New order received from someone if (item.Type == MailQueueType.NEW) { list[indexet].SierraPatronInfo = _patronDataProvider.GetPatronInfoFromLibraryCardNumberOrPersonnummer(item.PatronCardNo, item.PatronCardNo); } indexet++; } } catch (Exception e) { throw new SourcePollingException("Error connecting to Sierra.", e); } // Continues if we have a list of mail messages... int index = 0; // For each fetched mail to process foreach (MailQueueModel item in list) { // New order received from someone if (item.Type == MailQueueType.NEW) { try { // Write a new OrderItem int orderItemNodeId = _orderItemManager.CreateOrderItemInDbFromMailQueueModel(item, false, false); var eventId = _orderItemManager.GenerateEventId(CREATE_ORDER_FROM_MAIL_DATA_EVENT_TYPE); _orderItemManager.AddSierraDataToLog(orderItemNodeId, item.SierraPatronInfo, eventId); // Archive the mail message to correct folder if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true") { FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id); list[index].ArchiveFolderId = archiveFolderId; } // Update item with some useful data list[index].OrderItemNodeId = orderItemNodeId; list[index].StatusResult = "Created new OrderItem node."; _result.NewOrders++; } catch (Exception e) { list[index].OrderItemNodeId = -1; list[index].StatusResult = "Error creating new OrderItem node: " + e.Message; LogHelper.Error <SystemSurfaceController>("Error creating new OrderItem node", e); _result.Errors++; _result.Messages.Add(list[index].StatusResult); } } // Reply from user to existing order else if (item.Type == MailQueueType.REPLY) { try { var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_MAIL_DATA_PATRON_EVENT_TYPE); // Set the OrderItem Status so it appears in lists try { _orderItemManager.SetStatus(item.OrderItemNodeId, "02:Åtgärda", eventId, false, false); } catch (Exception es) { throw new Exception("Exception during SetOrderItemStatusInternal: " + es.Message); } // Set new FollowUpDate for the OrderItem try { _orderItemManager.SetFollowUpDateWithoutLogging(item.OrderItemNodeId, DateTime.Now, false, false); } catch (Exception ef) { throw new Exception("Exception during SetFollowUpDate: " + ef.Message); } // Write LogItem with the mail received and metadata try { _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL", getTextFromHtml(item.MessageBody), eventId, false, false); _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL_NOTE", "Svar från " + item.Sender + " [" + item.From + "]", eventId); } catch (Exception el) { throw new Exception("Exception during WriteLogItemInternal: " + el.Message); } // Archive the mail message to correct folder try { if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true") { FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id); list[index].ArchiveFolderId = archiveFolderId; } } catch (Exception ea) { throw new Exception("Exception during Archiving: " + ea.Message); } // Update item with some useful data list[index].StatusResult = "Wrote LogItem type MAIL for this OrderId."; _notifier.UpdateOrderItemUpdate(item.OrderItemNodeId, "-1", "", true, true, true); _result.UpdatedOrders++; } catch (Exception e) { list[index].StatusResult = "Error following up reply on OrderItem: " + e.Message; LogHelper.Error <SystemSurfaceController>("Error following up reply on OrderItem", e); _result.Errors++; _result.Messages.Add(list[index].StatusResult); } } else if (item.Type == MailQueueType.DELIVERY) { try { var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_MAIL_DATA_NOT_PATRON_EVENT_TYPE); // Set the OrderItem Status so it appears in lists try { _orderItemManager.SetStatus(item.OrderItemNodeId, "09:Mottagen", eventId, false, false); } catch (Exception es) { throw new Exception("Exception during SetOrderItemStatusInternal: " + es.Message); } // Check if the incoming mail mentions drm content. try { if (item.MessageBody.ToLower().Contains("drm")) { _orderItemManager.SetDrmWarningWithoutLogging(item.OrderItemNodeId, true, false, false); } } catch (Exception es) { throw new Exception("Exception during toggling of DrmWarning" + es.Message); } // Set new FollowUpDate for the OrderItem try { _orderItemManager.SetFollowUpDateWithoutLogging(item.OrderItemNodeId, DateTime.Now, false, false); } catch (Exception ef) { throw new Exception("Exception during SetFollowUpDate: " + ef.Message); } // Pick out attachments and save them in Umbracos media repository. try { if (item.Attachments.Count > 0) { foreach (var attachment in item.Attachments) { var savedMediaItem = _mediaItemManager.CreateMediaItem(attachment.Title, item.OrderItemNodeId, item.OrderId, attachment.Data, attachment.ContentType); if (attachment.Data != null) { attachment.Data.Dispose(); } _orderItemManager.AddExistingMediaItemAsAnAttachment(item.OrderItemNodeId, savedMediaItem.Id, attachment.Title, savedMediaItem.Url, eventId, false, false); } } } catch (Exception el) { throw new Exception("Failed to extract attachments from delivery mail: " + el.Message); } // Write LogItem with the mail received and metadata try { _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL", getTextFromHtml(item.MessageBody), eventId, false, false); _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL_NOTE", "Leverans från " + item.Sender + " [" + item.From + "]", eventId); } catch (Exception el) { throw new Exception("Exception during WriteLogItemInternal: " + el.Message); } // Archive the mail message to correct folder try { if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true") { FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id); list[index].ArchiveFolderId = archiveFolderId; } } catch (Exception ea) { throw new Exception("Exception during Archiving: " + ea.Message); } // Update item with some useful data list[index].StatusResult = "Wrote LogItem type MAIL for this OrderId."; _notifier.UpdateOrderItemUpdate(item.OrderItemNodeId, "-1", "", true, true, true); _result.UpdatedOrders++; } catch (Exception e) { list[index].StatusResult = "Error following up delivery on OrderItem: " + e.Message; LogHelper.Error <SystemSurfaceController>("Error following up delivery on OrderItem", e); _result.Errors++; _result.Messages.Add(list[index].StatusResult); } } else if (item.Type == MailQueueType.ERROR) { try { // Forward failed mail to bug fixers. try { foreach (var addressWithPotentialWs in ConfigurationManager.AppSettings["bugFixersMailingList"].Split(',')) { var address = addressWithPotentialWs.Trim(); try { _exchangeMailWebApi.ForwardMailMessage(item.Id, address, item.ParseErrorMessage, false); } catch (Exception innerInnerExc) { LogHelper.Error <SystemSurfaceController>("Failed to forward message to " + address + ".", innerInnerExc); } } } catch (Exception innerExc) { LogHelper.Error <SystemSurfaceController>("Failed to forward message to bug fixers.", innerExc); } // Forward failed mail to manual handling. _exchangeMailWebApi.ForwardMailMessage(item.Id, ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]); list[index].StatusResult = "This message has been forwarded to " + ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]; _result.Errors++; _result.Messages.Add(list[index].StatusResult); } catch (Exception e) { list[index].StatusResult = "Error forwarding mail: " + e.Message; LogHelper.Error <SystemSurfaceController>("Error forwarding mail", e); _result.Errors++; _result.Messages.Add(list[index].StatusResult); } } else // UNKNOWN, forward to mailbox configured in web.config { try { _exchangeMailWebApi.ForwardMailMessage(item.Id, ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]); list[index].StatusResult = "This message has been forwarded to " + ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]; } catch (Exception e) { list[index].StatusResult = "Error forwarding mail: " + e.Message; LogHelper.Error <SystemSurfaceController>("Error forwarding mail", e); _result.Errors++; _result.Messages.Add(list[index].StatusResult); } } item.Attachments = null; index++; } } return(Result); }
public ActionResult MigrateOrderItem(int nodeId) { var json = new ResultResponse(); try { var orderItemToBeMoved = _legacyOrderItemManager.GetOrderItem(nodeId); // There is an item to move. if (orderItemToBeMoved != null) { var existingOrderItem = _orderItemManager.GetOrderItem(orderItemToBeMoved.OrderId); // There is no item with the same order id already in the store. if (existingOrderItem == null) { // Copy and clear attachments and create the order item without attachments in the storage. var attachmentsToCopy = new List <OrderAttachment>(); foreach (var attachmentToBeMoved in orderItemToBeMoved.AttachmentList) { attachmentsToCopy.Add(attachmentToBeMoved); } orderItemToBeMoved.AttachmentList.Clear(); orderItemToBeMoved.Attachments = JsonConvert.SerializeObject(orderItemToBeMoved.AttachmentList); var newOrderItemNodeId = _orderItemManager.CreateOrderItemInDbFromOrderItemModel(orderItemToBeMoved); var newOrderItem = _orderItemManager.GetOrderItem(newOrderItemNodeId); if (newOrderItem != null) { // Create all the connected media items in the media storage. var newMediaItems = new List <MediaItemModel>(); bool successfullyAddedAllMediaItems = true; string failedMediaItemId = ""; string failedMediaItemName = ""; foreach (var attachmentToCopy in attachmentsToCopy) { var mediaItemToBeMoved = _legacyMediaItemManager.GetOne(attachmentToCopy.MediaItemNodeId); // Calculate the content type. string contentType = ""; if (attachmentToCopy.Title.EndsWith(".pdf")) { contentType = "application/pdf"; } else if (attachmentToCopy.Title.EndsWith(".txt")) { contentType = "text/plain"; } else if (attachmentToCopy.Title.EndsWith(".tif")) { contentType = "image/tiff"; } else if (attachmentToCopy.Title.EndsWith(".tiff")) { contentType = "image/tiff"; } if (!String.IsNullOrEmpty(contentType)) { var newMediaItem = _mediaItemManager.CreateMediaItem(attachmentToCopy.Title, newOrderItem.NodeId, newOrderItem.OrderId, mediaItemToBeMoved.Data, contentType); newMediaItems.Add(newMediaItem); } else { successfullyAddedAllMediaItems = false; failedMediaItemId = mediaItemToBeMoved.Id; failedMediaItemName = mediaItemToBeMoved.Name; break; } } // Connect all the newly created media items. if (successfullyAddedAllMediaItems) { foreach (var newMediaItem in newMediaItems) { _orderItemManager.AddExistingMediaItemAsAnAttachmentWithoutLogging(newOrderItemNodeId, newMediaItem.Id, newMediaItem.Name, newMediaItem.Url, true, false); } } else { throw new Exception("Failed to create media items connected to order item with ID = " + orderItemToBeMoved.NodeId + ". The troublesome media item has ID = " + failedMediaItemId + " and name '" + failedMediaItemName + "'."); } } else { throw new Exception("Failed to read back order item with ID = " + newOrderItem.NodeId + " after creating it in the current storage."); } } else { throw new Exception("There is already an order item with order ID = " + orderItemToBeMoved.OrderId + " in the current storage. Skipping move."); } } else { throw new Exception("There was no order item with node ID = " + nodeId + ". Nothing to move."); } json.Success = true; json.Message = "Successfully moved order with node ID = " + nodeId + "."; } catch (Exception e) { json.Success = false; json.Message = "Something went horribly wrong: " + e.Message; } return(Json(json, JsonRequestBehavior.AllowGet)); }