public Attachment CreateAttachement(IAttachment source) { Attachment attachment = null; var textAttachment = source as TextAttachment; if (textAttachment != null) { attachment = new Attachment(new MemoryStream(Encoding.ASCII.GetBytes(textAttachment.Content)), textAttachment.Name); } var streamAttachment = source as StreamAttachment; if (streamAttachment != null) { attachment = string.IsNullOrEmpty(streamAttachment.MediaType) ? new Attachment(streamAttachment.Stream, streamAttachment.Name) : new Attachment(streamAttachment.Stream, streamAttachment.Name, streamAttachment.MediaType); } var contentStreamAttachment = source as ContentStreamAttachment; if (contentStreamAttachment != null) { attachment = new Attachment(contentStreamAttachment.Stream, contentStreamAttachment.ContentType); } if (attachment != null) { attachment.Name = source.Name; } else { Logger.Warn("Unable to create attachment for unknown type"); } return attachment; }
public AttachmentViewModel(IAttachment model, MainViewModel main) : base(main) { if (model == null) throw new ArgumentNullException("model"); this.model = model; openAttachment = new OpenAttachmentCommand(this); saveAttachment = new SaveAttachmentCommand(this); main.RegisterViewModel(model, this); LoadViewModels(); }
/// <summary> /// Converts a generic attachment to a PDF. /// </summary> /// <param name="attachment">The attachment.</param> /// <param name="extension">The file extension.</param> /// <param name="outputStream">The stream to append the PDF data to.</param> public void ProcessAttachmentByExtension(IAttachment attachment, string extension, Stream outputStream) { var processor = this.processorFactory.GetAttachmentProcessor(extension); if (processor == null) { return; } processor.SetLicense(); processor.Process(attachment.Data, outputStream); }
private void AddAttachment(MailMessage mail, IAttachment attachment) { if (attachmentFactory == null) { Logger.Warn("Unable to add attachments no factory was supplied"); return; } var a = attachmentFactory.CreateAttachement(attachment); if (a != null) { mail.Attachments.Add(a); } }
public AttachmentViewModel GetViewModel(IAttachment model) { AttachmentViewModel vm; if (attachmentViewModels.ContainsKey(model.ID)) { vm = attachmentViewModels[model.ID]; vm.Model = model; } else { vm = new AttachmentViewModel(model, this); } return vm; }
public void Mount(IAttachment attachment) { if (attachment == null) { throw new ArgumentNullException(nameof(attachment), "A null attachment can not be null"); } if (this.mountedAttachments.Contains(attachment)) { return; } this.mountedAttachments.Add(attachment); }
public static string EvaluateOnAttachmentImportExpression(this DocumentTemplate dt, IAttachment Data, DiscoDataContext Database, User User, DateTime TimeStamp, List<DocumentUniqueIdentifier> PageIdentifiers) { if (!string.IsNullOrEmpty(dt.OnImportAttachmentExpression)) { var compiledExpression = dt.OnImportAttachmentExpressionFromCache(); var evaluatorVariables = Expression.StandardVariables(dt, Database, User, TimeStamp, null); evaluatorVariables.Add("PageIdentifiers", PageIdentifiers); var result = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables); if (result == null) return null; else return result.ToString(); } return null; }
public static async Task RepostPKMAsShowdownAsync(this ISocketMessageChannel channel, IAttachment att) { if (!PKX.IsPKM(att.Size)) { return; } var result = await NetUtil.DownloadPKMAsync(att).ConfigureAwait(false); if (!result.Success) { return; } var pkm = result.Data !; await channel.SendPKMAsShowdownSetAsync(pkm).ConfigureAwait(false); }
private void AddEntityAssociation(IAttachment attachment, string entityID, string entityType) { string simpleName = entityType.ToUpper().Replace("SAGE.ENTITY.INTERFACES.", ""); switch (simpleName) { case "IACCOUNT": attachment.AccountId = entityID; break; case "ICONTACT": attachment.ContactId = entityID; attachment.AccountId = EntityFactory.GetRepository<IContact>().Get(attachment.ContactId).Account.Id.ToString(); break; case "IOPPORTUNITY": attachment.OpportunityId = entityID; attachment.AccountId = EntityFactory.GetRepository<IOpportunity>().Get(attachment.OpportunityId).Id.ToString(); break; case "ITICKET": attachment.TicketId = entityID; ITicket ticket = EntityFactory.GetRepository<ITicket>().Get(attachment.TicketId); if (ticket != null) { attachment.AccountId = ticket.Account.Id.ToString(); attachment.ContactId = ticket.Contact.Id.ToString(); } break; case "ISALESORDER": attachment.SalesOrderID = entityID; attachment.AccountId = EntityFactory.GetRepository<ISalesOrder>().Get(attachment.SalesOrderID).Id.ToString(); break; case "IACTIVITY": attachment.ActivityId = entityID; attachment.AccountId = EntityFactory.GetById<IActivity>(entityID).AccountId; break; case "IHISTORY": attachment.HistoryId = entityID; var hist = EntityFactory.GetById<IHistory>(entityID); if (hist != null) { attachment.AccountId = hist.AccountId; attachment.ContactId = hist.ContactId; attachment.TicketId = hist.TicketId; attachment.OpportunityId = hist.OpportunityId; attachment.LeadId = hist.LeadId; } break; default: String tableName = GetTableName(entityType); PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(attachment).Find(String.Format("{0}Id", tableName), true); if (propertyDescriptor != null) propertyDescriptor.SetValue(attachment, entityID); break; } }
/// <summary> /// Deletes the physical file. /// </summary> /// <param name="attachment">The attachment.</param> private void DeletePhysicalFile(IAttachment attachment) { bool bIsActivityInsert = IsActivityInsert(); bool bIsHistoryInsert = IsHistoryInsert(); string attachPath; if (!bIsActivityInsert && !bIsHistoryInsert) attachPath = Rules.GetAttachmentPath(); else attachPath = Rules.GetTempAttachmentPath(); /* Make sure the attachment is not shared before removing the physical file. */ int count = Rules.CountAttachmentsWithSameName(attachment); if (count.Equals(1)) { if (File.Exists(attachPath + attachment.FileName)) { try { File.Delete(attachPath + attachment.FileName); } catch (Exception ex) { log.Error(String.Format(GetLocalResourceObject("Error_Delete_Exception").ToString(), attachment.FileName, ex.Message)); } } else { log.Info(String.Format(GetLocalResourceObject("Error_Delete_AttachNotFound").ToString(), attachment.FileName)); } } }
public void DownloadAndOpenAttachment(IAttachment attachment) { }
/// <summary> /// Export image to a new email /// </summary> /// <param name="outlookApplication"></param> /// <param name="format"></param> /// <param name="tmpFile"></param> /// <param name="subject"></param> /// <param name="attachmentName"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="url"></param> private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string cc, string bcc, string url) { using (IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem)) { if (newItem == null) { return; } //MailItem newMail = COMWrapper.Cast<MailItem>(newItem); MailItem newMail = (MailItem)newItem; newMail.Subject = subject; if (!string.IsNullOrEmpty(to)) { newMail.To = to; } if (!string.IsNullOrEmpty(cc)) { newMail.CC = cc; } if (!string.IsNullOrEmpty(bcc)) { newMail.BCC = bcc; } newMail.BodyFormat = OlBodyFormat.olFormatHTML; string bodyString = null; // Read the default signature, if nothing found use empty email try { bodyString = GetOutlookSignature(format); } catch (Exception e) { Log.Error("Problem reading signature!", e); } switch (format) { case EmailFormat.Text: // Create the attachment (and dispose the COM object after using) using (newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName)) { newMail.BodyFormat = OlBodyFormat.olFormatPlain; if (bodyString == null) { bodyString = ""; } newMail.Body = bodyString; } break; default: string contentId = Path.GetFileName(tmpFile); // Create the attachment (and dispose the COM object after using) using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) { // add content ID to the attachment if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { try { contentId = Guid.NewGuid().ToString(); IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId); } catch { Log.Info("Error working with the PropertyAccessor, using filename as contentid"); contentId = Path.GetFileName(tmpFile); } } } newMail.BodyFormat = OlBodyFormat.olFormatHTML; string href = ""; string hrefEnd = ""; if (!string.IsNullOrEmpty(url)) { href = $"<A HREF=\"{url}\">"; hrefEnd = "</A>"; } string htmlImgEmbedded = $"<BR/>{href}<IMG border=0 hspace=0 alt=\"{attachmentName}\" align=baseline src=\"cid:{contentId}\">{hrefEnd}<BR/>"; string fallbackBody = $"<HTML><BODY>{htmlImgEmbedded}</BODY></HTML>"; if (bodyString == null) { bodyString = fallbackBody; } else { int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase); if (bodyIndex >= 0) { bodyIndex = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1; bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody; } else { bodyString = fallbackBody; } } newMail.HTMLBody = bodyString; break; } // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();) newMail.Display(false); using (IInspector inspector = newMail.GetInspector()) { if (inspector != null) { try { inspector.Activate(); } catch { // Ignore } } } } }
public Stream DownloadAttachment(IAttachment attachment) { return Dal.DownloadAttachment(attachment); }
/// <summary> /// Initializes a new instance of the <see cref="AttachmentController" /> class. /// </summary> /// <param name="hremployee"></param> public AttachmentController(IAttachment attachment) { _attachment = attachment; }
public AttachmentMessage(IAttachment attachment) { this.Attachment = attachment; }
public DownloadedExternalService(IAttachment attachment) : this(new Uri(attachment.Url), attachment.Filename) { }
public void UploadResults(TB2.TestCase currentTestCase) { string testFolder = @"Root\WCS 7up Core - 5022\zz Automation\PracticeExecution\Temp_Prashant\QA72_7_31"; string testSetName = currentTestCase.Category; TestSetFactory tsFactory = (TestSetFactory)qcConnect.TestSetFactory; TestSetTreeManager tsTreeMgr = (TestSetTreeManager)qcConnect.TestSetTreeManager; TestSetFolder tsFolder = (TestSetFolder)tsTreeMgr.get_NodeByPath(testFolder); List tsList = tsFolder.FindTestSets(testSetName, false, null); TestSet testSet = tsList[1]; //foreach (TestSet testSet in tsList) //{ tsFolder = (TestSetFolder)testSet.TestSetFolder; TSTestFactory tsTestFactory = (TSTestFactory)testSet.TSTestFactory; List tsTestList = tsTestFactory.NewList(""); // And finally, update each test case status: foreach (TSTest tsTest in tsTestList) { //System.Console.Out.WriteLine("Test Case ID: " + tsTest.ID + ", Test Case Name: " + tsTest.Name + "\n"); if (currentTestCase.TestCaseName == tsTest.Name.Remove(0, 3)) { RunFactory runFactory = (RunFactory)tsTest.RunFactory; List allfields = runFactory.Fields; String browserValue = tsTest["TC_USER_TEMPLATE_10"]; // Console.WriteLine("Browser value : " + browserValue); Run lastRun = (Run)tsTest.LastRun; string runName = runFactory.UniqueRunName; RunFactory objRunFactory = tsTest.RunFactory; Run theRun = objRunFactory.AddItem(runName); theRun.Name = runName; //Get the count of test steps and compare it with the number of steps that were actually executed //and define the Execution status accordinagly theRun.CopyDesignSteps(); StepFactory Step = theRun.StepFactory; List stepList = (List)Step.NewList(""); if (currentTestCase.OverAllResult == OverAllResult.PASS) { theRun.Status = "Passed"; } else { theRun.Status = "Failed"; } theRun.Post(); //Delete current attachment from QC test set test case AttachmentFactory objAttachmentFactory = tsTest.Attachments; objSkipExec: var objCurrentAttachments = objAttachmentFactory.NewList(""); for (int objC = 1; objC <= objCurrentAttachments.Count; objC++) { try { objAttachmentFactory.RemoveItem(tsTest.Attachments.NewList("").Item(1).ID); } catch { } } if (objAttachmentFactory.NewList("").Count > 0) { goto objSkipExec; } IAttachment objAttachment = objAttachmentFactory.AddItem(DBNull.Value); objAttachment.FileName = currentTestCase.HTMLReportPath; objAttachment.Type = 1; objAttachment.Post(); string[] filePaths = System.IO.Directory.GetFiles(currentTestCase.ScreenShotPath); foreach (string file in filePaths) { objAttachment = objAttachmentFactory.AddItem(DBNull.Value); objAttachment.FileName = file; objAttachment.Type = 1; objAttachment.Post(); } break; // } } } }
public DefectItem() { Attachment = new IAttachment[] { }; Comments = new string[] { }; }
public Task Get(IAttachment attachment, int index) { return(Get(new Uri(attachment.Url), index)); }
public async Task DeleteFileAsync(IAttachment attachment) { await Misskey.Drive.Files.DeleteAsync(attachment.Id); }
// Token: 0x06000767 RID: 1895 RVA: 0x00029340 File Offset: 0x00027540 protected override int InternalExecute(int count) { string[] array = HttpUtility.UrlDecode(base.FileReference).Split(new char[] { ':' }); if (array.Length != 2) { throw new AirSyncPermanentException(StatusCode.Sync_TooManyFolders, false) { ErrorStringForProtocolLogger = "InvalidEntityAttachemtnId" }; } StoreObjectId itemId = StoreId.EwsIdToStoreObjectId(array[0]); IEvents events = EntitySyncItem.GetEvents(this.CalendaringContainer, base.Session, itemId); if (events == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EventsNotFound" }; } IAttachments attachments = events[array[0]].Attachments; if (attachments == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EntityNotFound" }; } IAttachment attachment = attachments.Read(array[1], null); if (attachment == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EntityAttachementNotFound" }; } base.ContentType = attachment.ContentType; FileAttachment fileAttachment = attachment as FileAttachment; ItemAttachment itemAttachment = attachment as ItemAttachment; if (fileAttachment != null) { if (!base.MaxAttachmentSize.IsUnlimited && fileAttachment.Content.Length > (int)base.MaxAttachmentSize.Value.ToBytes()) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } count = ((count == -1) ? fileAttachment.Content.Length : Math.Min(count, fileAttachment.Content.Length - base.MinRange)); base.OutStream.Write(fileAttachment.Content, base.MinRange, count); return(count); } else { if (itemAttachment != null) { int result; AttachmentHelper.GetAttachment(base.Session, itemId, attachment.Id, base.OutStream, base.MinRange, count, base.MaxAttachmentSize, base.RightsManagementSupport, out result); return(result); } throw new AirSyncPermanentException(StatusCode.Sync_InvalidWaitTime, new LocalizedString(string.Format("Attachment type \"{0}\" is not supported.", attachment.GetType().FullName)), false) { ErrorStringForProtocolLogger = "UnsupportedEntityAttachementType" }; } }
public void UploadResults(TestCase currentTestCase) { string testFolder = Convert.ToString(ExecutionSession.dictCommonData["QCFolder"]); string testSetName = currentTestCase.Category; TestSetFactory tsFactory = (TestSetFactory)qcConnect.TestSetFactory; TestSetTreeManager tsTreeMgr = (TestSetTreeManager)qcConnect.TestSetTreeManager; TestSetFolder tsFolder = (TestSetFolder)tsTreeMgr.get_NodeByPath(testFolder); List tsList = tsFolder.FindTestSets(testSetName, false, null); TestSet testSet = tsList[1]; tsFolder = (TestSetFolder)testSet.TestSetFolder; TSTestFactory tsTestFactory = (TSTestFactory)testSet.TSTestFactory; List tsTestList = tsTestFactory.NewList(""); // And finally, update each test case status: foreach (TSTest tsTest in tsTestList) { if (currentTestCase.TestCaseName == tsTest.Name.Remove(0, 3)) { RunFactory runFactory = (RunFactory)tsTest.RunFactory; List allfields = runFactory.Fields; String browserValue = tsTest["TC_USER_TEMPLATE_10"]; Run lastRun = (Run)tsTest.LastRun; string runName = runFactory.UniqueRunName; RunFactory objRunFactory = tsTest.RunFactory; Run theRun = objRunFactory.AddItem(runName); theRun.Name = runName; theRun.CopyDesignSteps(); StepFactory Step = theRun.StepFactory; List stepList = (List)Step.NewList(""); if (currentTestCase.OverAllResult == OverAllResult.PASS) { theRun.Status = "Passed"; } else { theRun.Status = "Failed"; } theRun.Post(); //Delete current attachment from QC test set test case AttachmentFactory objAttachmentFactory = tsTest.Attachments; var objCurrentAttachments = objAttachmentFactory.NewList(""); for (int objC = 1; objC <= objCurrentAttachments.Count; objC++) { try { objAttachmentFactory.RemoveItem(tsTest.Attachments.NewList("").Item(1).ID); } catch { } } IAttachment objAttachment = objAttachmentFactory.AddItem(DBNull.Value); objAttachment.FileName = currentTestCase.QCHTMLReportPath; objAttachment.Type = 1; objAttachment.Post(); string[] filePaths = System.IO.Directory.GetFiles(currentTestCase.QCScreenShotPath); foreach (string file in filePaths) { objAttachment = objAttachmentFactory.AddItem(DBNull.Value); objAttachment.FileName = file; objAttachment.Type = 1; objAttachment.Post(); } break; } } }
public static bool IsPlayableAttachment(this IAttachment attachment) => attachment.Filename.IsPlayableUrl();
/// <summary> /// Checks for errors before applying a rule. /// </summary> /// <param name="node">The node instance to check.</param> /// <param name="dataList">Optional data collected during inspection of sources.</param> /// <param name="data">Private data to give to Apply() upon return.</param> /// <returns>True if an error occured.</returns> public override bool CheckConsistency(IAttachmentInstruction node, IDictionary <ISourceTemplate, object> dataList, out object data) { data = null; bool Success = true; IExpression SourceExpression = (IExpression)node.Source; IResultType SourceResult = SourceExpression.ResolvedResult.Item; IClass EmbeddingClass = node.EmbeddingClass; int MaxAttachmentCount = 0; foreach (IAttachment AttachmentItem in node.AttachmentList) { if (AttachmentItem.AttachTypeList.Count > SourceResult.Count) { AddSourceError(new ErrorInvalidAttachment(AttachmentItem)); return(false); } else if (MaxAttachmentCount < AttachmentItem.AttachTypeList.Count) { MaxAttachmentCount = AttachmentItem.AttachTypeList.Count; } } for (int i = 0; i < node.AttachmentList.Count; i++) { IAttachment Attachment = node.AttachmentList[i]; bool ConformanceError = true; for (int j = 0; j < MaxAttachmentCount; j++) { if (j < Attachment.AttachTypeList.Count) { ICompiledType SourceType = SourceResult.At(j).ValueType; IObjectType AttachType = Attachment.AttachTypeList[j]; ICompiledType DestinationType = AttachType.ResolvedType.Item; if (!ObjectType.TypesHaveCommonDescendant(EmbeddingClass, DestinationType, SourceType)) { AddSourceError(new ErrorInvalidAttachment(Attachment)); return(false); } else { ConformanceError &= CheckConsistencyTyped(node, i, j, DestinationType); } } } if (ConformanceError) { AddSourceError(new ErrorInvalidAttachment(Attachment)); return(false); } } if (Success) { IResultException ResolvedException = new ResultException(); ResultException.Merge(ResolvedException, SourceExpression.ResolvedException.Item); foreach (IAttachment Item in node.AttachmentList) { ResultException.Merge(ResolvedException, Item.ResolvedException.Item); } if (node.ElseInstructions.IsAssigned) { IScope ElseInstructions = (IScope)node.ElseInstructions.Item; ResultException.Merge(ResolvedException, ElseInstructions.ResolvedException.Item); } data = ResolvedException; } return(Success); }
/// <summary> /// Uses the IMAPIPROP.SetProps to set the content ID /// </summary> /// <param name="attachment"></param> /// <param name="contentId"></param> public static void SetContentID(IAttachment attachment, string contentId) { // Pointer to IUnknown Interface IntPtr IUnknown = IntPtr.Zero; // Pointer to IMAPIProp Interface IntPtr IMAPIProp = IntPtr.Zero; // A pointer that points to the SPropValue structure IntPtr ptrPropValue = IntPtr.Zero; // Structure that will hold the Property Value SPropValue propValue; // if we have no MAPIObject everything is senseless... if (attachment == null) { return; } try { // We can pass NULL here as parameter, so we do it. MAPIInitialize(IntPtr.Zero); // retrive the IUnknon Interface from our MAPIObject comming from Outlook. IUnknown = Marshal.GetIUnknownForObject(attachment.MAPIOBJECT); IMAPIProp mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); // Create structure propValue = new SPropValue(); propValue.propTag = (uint)PropTags.PR_ATTACH_CONTENT_ID; //propValue.propTag = 0x3712001E; // Create Ansi string propValue.Value = Marshal.StringToHGlobalUni(contentId); // Create unmanaged memory for structure ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue)); // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero); propValue.propTag = (uint)PropTags.PR_ATTACH_CONTENT_LOCATION; // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero); // Free string Marshal.FreeHGlobal(propValue.Value); mapiProp.SaveChanges(KEEP_OPEN_READWRITE); } catch (Exception ex) { LOG.Error(ex); } finally { // Free used Memory structures if (ptrPropValue != IntPtr.Zero) Marshal.FreeHGlobal(ptrPropValue); // cleanup all references to COM Objects if (IMAPIProp != IntPtr.Zero) Marshal.Release(IMAPIProp); //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage); if (IUnknown != IntPtr.Zero) Marshal.Release(IUnknown); } }
/// <summary> /// Gets whether the message's attachments are spoilers or not. /// </summary> public static bool IsSpoiler(this IAttachment attachment) => attachment.Filename.StartsWith(SpoilerPrefix);
private void ExtractMetadata(IAttachment attachment) { //throw new NotImplementedException(); }
/// <summary> /// Use MAPI32.DLL "HrSetOneProp" from managed code /// </summary> /// <param name="attachment"></param> /// <param name="proptag"></param> /// <param name="propertyValue"></param> /// <returns></returns> public static bool SetMAPIProperty(IAttachment attachment, PropTags proptag, string propertyValue) { // Pointer to IUnknown Interface IntPtr IUnknown = IntPtr.Zero; // Pointer to IMAPIProp Interface IntPtr IMAPIProp = IntPtr.Zero; // Structure that will hold the Property Value SPropValue propValue; // A pointer that points to the SPropValue structure IntPtr ptrPropValue = IntPtr.Zero; object mapiObject = attachment.MAPIOBJECT; // if we have no MAPIObject everything is senseless... if (mapiObject == null) { return false; } try { // We can pass NULL here as parameter, so we do it. MAPIInitialize(IntPtr.Zero); // retrive the IUnknon Interface from our MAPIObject comming from Outlook. IUnknown = Marshal.GetIUnknownForObject(mapiObject); // create a Guid that we pass to retreive the IMAPIProp Interface. Guid guidIMAPIProp = new Guid(IID_IMAPIProp); // try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless. if (Marshal.QueryInterface(IUnknown, ref guidIMAPIProp, out IMAPIProp) != 0) { return false; } // double check, if we wave no pointer, exit... if (IMAPIProp == IntPtr.Zero) { return false; } // Create structure propValue = new SPropValue(); propValue.propTag = (uint)proptag; // Create Ansi string propValue.Value = Marshal.StringToHGlobalUni(propertyValue); // Create unmanaged memory for structure ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue)); // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); // Set the property HrSetOneProp(IMAPIProp, ptrPropValue); // Free string Marshal.FreeHGlobal(propValue.Value); IMAPIProp mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); return mapiProp.SaveChanges(4) == 0; } catch (System.Exception ex) { LOG.Error(ex); return false; } finally { // Free used Memory structures if (ptrPropValue != IntPtr.Zero) Marshal.FreeHGlobal(ptrPropValue); // cleanup all references to COM Objects if (IMAPIProp != IntPtr.Zero) Marshal.Release(IMAPIProp); //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage); if (IUnknown != IntPtr.Zero) Marshal.Release(IUnknown); MAPIUninitialize(); } }
public ArchiveImage(IAttachment original) { Original = original; }
public AttachmentFormModel(IAttachment note) { Csla.Data.DataMapper.Map(note, this, true); }
public virtual IAttachment CreateIAttachment(AttachmentType type, IAttachment attachment) { throw new NotImplementedException(); }
/// <summary> /// Opens the attachment. /// </summary> protected void OpenAttachment() { try { var fileId = String.Empty; Response.Buffer = true; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); string fileName = Request.QueryString["Filename"]; string historyid = Request.QueryString["historyid"]; if (string.IsNullOrEmpty(fileName) && string.IsNullOrEmpty(historyid)) { WriteErrorMessage(string.Concat(GetLocalResourceObject("Error_NoFileRequested_lz"), "<br />", Request.PathInfo, "?", Request.QueryString)); return; } if (!string.IsNullOrEmpty(fileName)) { //remove backslash from file name while ((fileName.IndexOf("/") == 0) || (fileName.IndexOf("\\") == 0)) { fileName = fileName.Remove(0, 1); } fileName = fileName.Replace("..\\", ""); //':', ';', '?', '*', '\', '/', '>', '<', '|', '''', '"' : Result[i] := '_'; -- but '; not replaced in library fileName = Regex.Replace(fileName, "[\\?=<>:;\\*\\|\"]", ""); } else if (!string.IsNullOrEmpty(historyid)) { var history = EntityFactory.GetById <IHistory>(historyid); if (history != null) { IList <IAttachment> attachments = Sage.SalesLogix.Attachment.Rules.GetAttachmentsFor(typeof(IHistory), history.Id.ToString()); if (attachments != null) { IAttachment attachment = null; foreach (IAttachment att in attachments) { if (att.FileName.ToUpper().EndsWith(".MSG")) { fileName = att.FileName; attachment = att; break; } } if (attachment == null) { WriteErrorMessage(GetLocalResourceObject("Error_EmailMsgAttachment").ToString()); return; } } else { WriteErrorMessage(GetLocalResourceObject("Error_EmailMsgAttachment").ToString()); return; } } } string filePath = String.Empty; string dataType = GetAttachmentType(Request.QueryString["DataType"]); if (dataType.Equals("Library")) { fileId = Request.QueryString["FileId"]; //can't use query string to get library directory as Whats New attachment/documents won't contain that property string libraryPath = Sage.SalesLogix.Attachment.Rules.GetLibraryPath(); ILibraryDocs libraryDoc = EntityFactory.GetRepository <ILibraryDocs>().Get(fileId); if (libraryDoc != null) { filePath = String.Format("{0}{1}\\", libraryPath, libraryDoc.Directory.FullPath); if (IsRemote()) { if (File.Exists(filePath + fileName)) { libraryDoc.Status = LibraryDocsStatus.DeliveredRead; libraryDoc.Save(); } } } } else { fileId = Request.QueryString["Id"]; filePath = Sage.SalesLogix.Attachment.Rules.GetAttachmentPath(); } if (dataType.Equals("Template")) { filePath += "Word Templates/"; } string tempPath = Sage.SalesLogix.Attachment.Rules.GetTempAttachmentPath(); if (File.Exists(tempPath + fileName)) { filePath = tempPath; } if (File.Exists(filePath + fileName)) { FileStream fileStream = new FileStream(filePath + fileName, FileMode.Open, FileAccess.Read, FileShare.Read); try { const int CHUNK_SIZE = 1024 * 10; long iFileLength = fileStream.Length; BinaryReader binaryReader = new BinaryReader(fileStream); try { Response.Buffer = false; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); string strFilePart = string.Empty; strFilePart = MakeValidFileName(fileName); if (string.IsNullOrEmpty(strFilePart)) { strFilePart = GetLocalResourceObject("DefaultUnknownFileName").ToString(); } if (string.IsNullOrEmpty(strFilePart)) { strFilePart = GetLocalResourceObject("DefaultUnknownFileName").ToString(); } if (strFilePart.Equals(GetLocalResourceObject("DefaultUnknownFileName").ToString())) { // Just in case the translation contains invalid file name characters. strFilePart = MakeValidFileName(strFilePart); } string strExtPart = Path.GetExtension(filePath + fileName); if (string.IsNullOrEmpty(strExtPart)) { strExtPart = ".dat"; } Response.ContentType = GetMIMEFromReg(strExtPart); if (IsIE()) { // Note: Internet Explorer will only allow 20 characters to be used for the file name (including extension) // when double byte characters are used. However, if more than 20 characters are used the Save As dialog // will show an invalid file name and an invalid file extension under the following conditions: // http://support.microsoft.com/kb/897168. The code below handles the truncation of the file name when // the file name contains double byte characters, which works around this bug. // Will return false if there were any double byte characters. bool bCanUseFullFileName; try { bCanUseFullFileName = Sage.Platform.Data.DataUtil.CalculateStorageLengthRequired(fileName).Equals(fileName.Length); } catch (Exception) { bCanUseFullFileName = false; } if (!bCanUseFullFileName) { int iExtLength = strExtPart.Length; int iCopyLength = 20 - iExtLength; // We can only use 20 characters for the filename + ext if there were double byte characters. if (strFilePart.Length > iCopyLength) { strFilePart = strFilePart.Substring(0, iCopyLength); } } } fileName = strFilePart.Replace("+", "%20"); Response.Clear(); Response.Charset = String.Empty; Encoding headerEncoding = Encoding.GetEncoding(1252); Response.HeaderEncoding = headerEncoding; Response.AddHeader("Content-Disposition", string.Format("attachment; filename{0}=\"", (IsFirefox() || IsMozilla()) ? "*" : "") + fileName + "\";"); binaryReader.BaseStream.Seek(0, SeekOrigin.Begin); int iMaxCount = (int)Math.Ceiling((iFileLength + 0.0) / CHUNK_SIZE); for (int i = 0; i < iMaxCount && Response.IsClientConnected; i++) { Response.BinaryWrite(binaryReader.ReadBytes(CHUNK_SIZE)); Response.Flush(); } HttpContext.Current.ApplicationInstance.CompleteRequest(); } finally { binaryReader.Close(); } fileStream.Close(); } finally { fileStream.Dispose(); } } else { WriteFileNotFound(fileName, fileId); } } catch (Exception ex) { if (ex.Message.IndexOf("because it is being used by another") > 0) { WriteErrorMessage(string.Concat(GetLocalResourceObject("Error_FileInUse_lz").ToString(), "\r\n", ex.Message)); } else { WriteErrorMessage(string.Concat(GetLocalResourceObject("Error_NoFileRequested_lz").ToString(), "\r\n{0}", Request.PathInfo, "?", Request.QueryString)); } } }
public static void CopyTo(this IAttachment source, IAttachment target) { target.Name = source.Name; target.Size = source.Size; target.Content = source.Content; }
private List <Embed> make_it_pretty(List <IMessage> input) //makes a list of embeds { List <Embed> res = new List <Embed>(); string usname; string prev_us = ""; string text = ""; for (int i = 0; i < input.Count; i++) { usname = input[i].Author.Username; List <IAttachment> attachments = new List <IAttachment>(); if (usname != prev_us) //if new user starts { text = ""; color_picked = false; if (i < input.Count - 1) //if not last ever { if (input[i + 1].Author.Username != usname) //if last of user { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); if (input[i].Attachments.FirstOrDefault() != null) { IAttachment att = input[i].Attachments.FirstOrDefault(); res.Add(build_attachment(att)); } } else //if not last of user { if (input[i].Attachments.FirstOrDefault() != null) { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); EmbedBuilder build_pic = build_attachment(input[i].Attachments.FirstOrDefault()); res.Add(build_pic); text = ""; } else { text += "\n" + input[i].Content; } } } else //if last ever { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); if (input[i].Attachments.FirstOrDefault() != null) { IAttachment att = input[i].Attachments.FirstOrDefault(); res.Add(build_attachment(att)); } } } else //if old user continues { if (i < input.Count - 1) //if not last ever { if (input[i + 1].Author.Username != usname) //if last of user { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); if (input[i].Attachments.FirstOrDefault() != null) { IAttachment att = input[i].Attachments.FirstOrDefault(); res.Add(build_attachment(att)); } } else { if (input[i].Attachments.FirstOrDefault() != null) { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); EmbedBuilder build_pic = build_attachment(input[i].Attachments.FirstOrDefault()); res.Add(build_pic); text = ""; } else { text += "\n" + input[i].Content; } } } else //if it's the last one { text += "\n" + input[i].Content; string icon = input[i].Author.GetAvatarUrl(); var builder = new EmbedBuilder(); builder = build_message(usname, text, icon); res.Add(builder); if (input[i].Attachments.FirstOrDefault() != null) { IAttachment att = input[i].Attachments.FirstOrDefault(); res.Add(build_attachment(att)); } } } prev_us = input[i].Author.Username; } return(res); }
internal void RegisterViewModel(IAttachment model, AttachmentViewModel vm) { if (attachmentViewModels.ContainsKey(model.ID) == false) attachmentViewModels.Add(model.ID, vm); }
public async Task <ulong> ExecuteWebhook(ITextChannel channel, string name, string avatarUrl, string content, IAttachment attachment) { _logger.Debug("Invoking webhook in channel {Channel}", channel.Id); // Get a webhook, execute it var webhook = await _webhookCache.GetWebhook(channel); var id = await ExecuteWebhookInner(webhook, name, avatarUrl, content, attachment); // Log the relevant metrics _metrics.Measure.Meter.Mark(BotMetrics.MessagesProxied); _logger.Information("Invoked webhook {Webhook} in channel {Channel}", webhook.Id, channel.Id); return(id); }
internal void UnregisterViewModel(IAttachment model) { if (attachmentViewModels.ContainsKey(model.ID)) attachmentViewModels.Remove(model.ID); }
public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, IAttachment att) { var download = await NetUtil.DownloadPKMAsync(att).ConfigureAwait(false); if (!download.Success) { await channel.SendMessageAsync(download.ErrorMessage).ConfigureAwait(false); return; } var pkm = download.Data !; if (new LegalityAnalysis(pkm).Valid) { await channel.SendMessageAsync($"{download.SanitizedFileName}: Already legal.").ConfigureAwait(false); return; } var legal = pkm.LegalizePokemon(); if (legal == null || !new LegalityAnalysis(legal).Valid) { await channel.SendMessageAsync($"{download.SanitizedFileName}: Unable to legalize.").ConfigureAwait(false); return; } legal.RefreshChecksum(); var msg = $"Here's your legalized PKM for {download.SanitizedFileName}!\n{ReusableActions.GetFormattedShowdownText(legal)}"; await channel.SendPKMAsync(legal, msg).ConfigureAwait(false); }
public string Store(IAttachment att, string fileName) { throw new NotImplementedException(); }
/// <summary> /// Writes the attachment to stream. /// </summary> /// <param name="attachment">The attachment.</param> /// <param name="target">The target.</param> public void WriteAttachmentToStream(IAttachment attachment, Stream target) { string extension = Path.GetExtension(attachment.Name).ToLower(); this.attachmentManager.ProcessAttachmentByExtension(attachment, extension, target); }
private MailContent CreateContent(MailAddress from, MailAddress[] to, bool sendEicar) { var template = _mailTemplates.Get(_timeTable.MailTemplateId); var html = ReplaceTokens(template.Html, template.Title); var text = ReplaceTokens(template.Text, template.Title); var mc = new MailContent(template.Subject, from, html, text) { HeaderEncoding = GetEncoding(template.HeaderEncoding), SubjectEncoding = GetEncoding(template.HeaderEncoding), BodyEncoding = GetEncoding(template.BodyEncoding) }; if (to.Length > 0) { mc.AddRecipient(to.First()); if (to.Length > 1) { foreach (var cc in to.Skip(1)) { mc.AddCc(cc); } } } IAttachment attachment = null; if (_timeTable.AttachmentType == AttachmentType.Fixed) { attachment = _attachments.Get(_timeTable.AttachmentName); } else if (_timeTable.AttachmentType == AttachmentType.Random) { var attachments = _attachments.All().ToArray(); attachment = attachments[_random.Next(attachments.Length)]; } if (attachment != null) { mc.AddAttachment(attachment.Name, attachment.Content); } if (sendEicar) { if (_timeTable.ProtocolLevel == ProtocolLevel.Verbose) { Logger.InfoFormat("Timetable '{0}': next mail will be sent with an EICAR file.", _timeTable.Name); } mc.AddAttachment("eicar.html", EICAR, Encoding.ASCII, MediaTypeNames.Text.Html); } if (EmlFolder != null) { if (!File.Exists(EmlFolder)) { Directory.CreateDirectory(EmlFolder); } var name = _timeTable.Name + " " + DateTime.Now.ToString("s"); var safeName = Regex.Replace(name, "\\W+", "-"); using (var file = File.OpenWrite(Path.Combine(EmlFolder, safeName + ".eml"))) using (var writer = new StreamWriter(file)) { writer.Write(mc.ToString()); } } return(mc); }
public bool Equals(IAttachment other) { throw new NotImplementedException(); }
public UploadController(IAttachment attachmentRepository) { repository = attachmentRepository; }
public static void LogImportAttachmentExpressionEvaluated(DocumentTemplate template, IAttachmentTarget target, IAttachment attachment, string Result) { DocumentsLog.Log(DocumentsLog.EventTypeIds.ImportAttachmentExpressionEvaluated, new object[] { template.Id, target.AttachmentReferenceId, attachment.Id, Result }); }
/// <summary> /// Uses the IMAPIPROP.SetProps to set the content ID /// </summary> /// <param name="attachment"></param> /// <param name="contentId"></param> public static void SetContentID(IAttachment attachment, string contentId) { // Pointer to IUnknown Interface var IUnknown = IntPtr.Zero; // Pointer to IMAPIProp Interface var IMAPIProp = IntPtr.Zero; // A pointer that points to the SPropValue structure var ptrPropValue = IntPtr.Zero; // Structure that will hold the Property Value SPropValue propValue; // if we have no MAPIObject everything is senseless... if (attachment == null) { return; } try { // We can pass NULL here as parameter, so we do it. MAPIInitialize(IntPtr.Zero); // retrive the IUnknon Interface from our MAPIObject comming from Outlook. IUnknown = Marshal.GetIUnknownForObject(attachment.MAPIOBJECT); var mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); // Create structure propValue = new SPropValue { propTag = (uint)PropTags.PR_ATTACH_CONTENT_ID, Value = Marshal.StringToHGlobalUni(contentId) }; //propValue.propTag = 0x3712001E; // Create Ansi string // Create unmanaged memory for structure ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue)); // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero); propValue.propTag = (uint)PropTags.PR_ATTACH_CONTENT_LOCATION; // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero); // Free string Marshal.FreeHGlobal(propValue.Value); mapiProp.SaveChanges(KEEP_OPEN_READWRITE); } catch (Exception ex) { Log.Error().WriteLine(ex); } finally { // Free used Memory structures if (ptrPropValue != IntPtr.Zero) { Marshal.FreeHGlobal(ptrPropValue); } // cleanup all references to COM Objects if (IMAPIProp != IntPtr.Zero) { Marshal.Release(IMAPIProp); } //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage); if (IUnknown != IntPtr.Zero) { Marshal.Release(IUnknown); } } }
protected void SetAttachmentToModel(IAttachment model, int id, RequestAttachmentTypeEnum type) { if (id == 0) return; RequestAttachment attach = RequestAttachmentDao.FindByRequestIdAndTypeId(id, type); if (attach == null) return; model.AttachmentId = attach.Id; model.Attachment = attach.FileName; }
/// <summary> /// Use MAPI32.DLL "HrSetOneProp" from managed code /// </summary> /// <param name="attachment"></param> /// <param name="proptag"></param> /// <param name="propertyValue"></param> /// <returns></returns> public static bool SetMAPIProperty(IAttachment attachment, PropTags proptag, string propertyValue) { // Pointer to IUnknown Interface var IUnknown = IntPtr.Zero; // Pointer to IMAPIProp Interface var IMAPIProp = IntPtr.Zero; // Structure that will hold the Property Value SPropValue propValue; // A pointer that points to the SPropValue structure var ptrPropValue = IntPtr.Zero; var mapiObject = attachment.MAPIOBJECT; // if we have no MAPIObject everything is senseless... if (mapiObject == null) { return(false); } try { // We can pass NULL here as parameter, so we do it. MAPIInitialize(IntPtr.Zero); // retrive the IUnknon Interface from our MAPIObject comming from Outlook. IUnknown = Marshal.GetIUnknownForObject(mapiObject); // create a Guid that we pass to retreive the IMAPIProp Interface. var guidIMAPIProp = new Guid(IID_IMAPIProp); // try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless. if (Marshal.QueryInterface(IUnknown, ref guidIMAPIProp, out IMAPIProp) != 0) { return(false); } // double check, if we wave no pointer, exit... if (IMAPIProp == IntPtr.Zero) { return(false); } // Create structure propValue = new SPropValue { propTag = (uint)proptag, Value = Marshal.StringToHGlobalUni(propertyValue) }; // Create Ansi string // Create unmanaged memory for structure ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue)); // Copy structure to unmanged memory Marshal.StructureToPtr(propValue, ptrPropValue, false); // Set the property HrSetOneProp(IMAPIProp, ptrPropValue); // Free string Marshal.FreeHGlobal(propValue.Value); var mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); return(mapiProp.SaveChanges(4) == 0); } catch (Exception ex) { Log.Error().WriteLine(ex); return(false); } finally { // Free used Memory structures if (ptrPropValue != IntPtr.Zero) { Marshal.FreeHGlobal(ptrPropValue); } // cleanup all references to COM Objects if (IMAPIProp != IntPtr.Zero) { Marshal.Release(IMAPIProp); } //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage); if (IUnknown != IntPtr.Zero) { Marshal.Release(IUnknown); } MAPIUninitialize(); } }
/// <summary> /// Export the file to the supplied inspector /// </summary> /// <param name="inspectorOrExplorer">ICommonExplorer</param> /// <param name="currentItem">Item</param> /// <param name="tmpFile"></param> /// <param name="attachmentName"></param> /// <returns></returns> private static bool ExportToInspector(ICommonExplorer inspectorOrExplorer, IItem currentItem, string tmpFile, string attachmentName) { if (currentItem == null) { Log.Warn("No current item."); return(false); } OlObjectClass itemClass = currentItem.Class; bool isMail = OlObjectClass.olMail.Equals(itemClass); bool isAppointment = OlObjectClass.olAppointment.Equals(itemClass); if (!isMail && !isAppointment) { Log.Warn("Item is no mail or appointment."); return(false); } MailItem mailItem = null; try { if (isMail) { //mailItem = COMWrapper.Cast<MailItem>(currentItem); mailItem = (MailItem)currentItem; if (mailItem.Sent) { Log.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject); return(false); } } // Make sure the inspector is activated, only this way the word editor is active! // This also ensures that the window is visible! inspectorOrExplorer.Activate(); bool isTextFormat = false; if (isMail) { isTextFormat = OlBodyFormat.olFormatPlain.Equals(mailItem.BodyFormat); } if (isAppointment || !isTextFormat) { // Check for wordmail, if so use the wordexporter // http://msdn.microsoft.com/en-us/library/dd492012%28v=office.12%29.aspx // Earlier versions of Outlook also supported an Inspector.HTMLEditor object property, but since Internet Explorer is no longer the rendering engine for HTML messages and posts, HTMLEditor is no longer supported. IWordDocument wordDocument = null; var explorer = inspectorOrExplorer as IExplorer; if (explorer != null) { wordDocument = explorer.ActiveInlineResponseWordEditor; } else { var inspector1 = inspectorOrExplorer as IInspector; if (inspector1 != null) { var inspector = inspector1; if (inspector.IsWordMail()) { wordDocument = inspector.WordEditor; } } } if (wordDocument != null) { try { if (WordExporter.InsertIntoExistingDocument(wordDocument.Application, wordDocument, tmpFile, null, null)) { Log.Info("Inserted into Wordmail"); wordDocument.Dispose(); return(true); } } catch (Exception exportException) { Log.Error("Error exporting to the word editor, trying to do it via another method", exportException); } } else if (isAppointment) { Log.Info("Can't export to an appointment if no word editor is used"); return(false); } else { Log.Info("Trying export for outlook < 2007."); } } // Only use mailitem as it should be filled!! Log.InfoFormat("Item '{0}' has format: {1}", mailItem?.Subject, mailItem?.BodyFormat); string contentId; if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { contentId = Guid.NewGuid().ToString(); } else { Log.Info("Older Outlook (<2007) found, using filename as contentid."); contentId = Path.GetFileName(tmpFile); } // Use this to change the format, it will probably lose the current selection. //if (!OlBodyFormat.olFormatHTML.Equals(currentMail.BodyFormat)) { // LOG.Info("Changing format to HTML."); // currentMail.BodyFormat = OlBodyFormat.olFormatHTML; //} bool inlinePossible = false; if (inspectorOrExplorer is IInspector && OlBodyFormat.olFormatHTML.Equals(mailItem?.BodyFormat)) { // if html we can try to inline it // The following might cause a security popup... can't ignore it. try { IHTMLDocument2 document2 = (inspectorOrExplorer as IInspector).HTMLEditor as IHTMLDocument2; if (document2 != null) { IHTMLSelectionObject selection = document2.selection; if (selection != null) { IHTMLTxtRange range = selection.createRange(); if (range != null) { // First paste, than attach (otherwise the range is wrong!) range.pasteHTML("<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentId + "\"><BR/>"); inlinePossible = true; } else { Log.DebugFormat("No range for '{0}'", inspectorOrExplorer.Caption); } } else { Log.DebugFormat("No selection for '{0}'", inspectorOrExplorer.Caption); } } else { Log.DebugFormat("No HTML editor for '{0}'", inspectorOrExplorer.Caption); } } catch (Exception e) { // Continue with non inline image Log.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e); } } // Create the attachment (if inlined the attachment isn't visible as attachment!) using (IAttachment attachment = mailItem.Attachments.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible ? 0 : 1, attachmentName)) { if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { // Add the content id to the attachment, this only works for Outlook >= 2007 try { IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId); } catch { // Ignore } } } } catch (Exception ex) { Log.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspectorOrExplorer.Caption, ex); return(false); } try { inspectorOrExplorer.Activate(); } catch (Exception ex) { Log.Warn("Problem activating inspector/explorer: ", ex); return(false); } Log.Debug("Finished!"); return(true); }
/// <summary> /// Checks for errors before applying a rule. /// </summary> /// <param name="node">The node instance to check.</param> /// <param name="dataList">Optional data collected during inspection of sources.</param> /// <param name="data">Private data to give to Apply() upon return.</param> /// <returns>True if an error occured.</returns> public override bool CheckConsistency(IAttachmentInstruction node, IDictionary <ISourceTemplate, object> dataList, out object data) { bool Success = true; data = null; IClass EmbeddingClass = node.EmbeddingClass; IList <ISealableDictionary <string, IScopeAttributeFeature> > CheckedScopeList = new List <ISealableDictionary <string, IScopeAttributeFeature> >(); for (int i = 0; i < node.AttachmentList.Count; i++) { CheckedScopeList.Add(new SealableDictionary <string, IScopeAttributeFeature>()); } for (int Index = 0; Index < node.EntityNameList.Count; Index++) { IName Item = node.EntityNameList[Index]; Debug.Assert(Item.ValidText.IsAssigned); string ValidText = Item.ValidText.Item; if (CheckedScopeList[0].ContainsKey(ValidText)) { AddSourceError(new ErrorVariableAlreadyDefined(Item, ValidText)); Success = false; continue; } for (int i = 0; i < node.AttachmentList.Count; i++) { Attachment AttachmentItem = (Attachment)node.AttachmentList[i]; ISealableDictionary <string, IScopeAttributeFeature> CheckedScope = CheckedScopeList[i]; Debug.Assert(Index < AttachmentItem.AttachTypeList.Count); IObjectType AttachedType = AttachmentItem.AttachTypeList[Index]; Debug.Assert(AttachedType.ResolvedTypeName.IsAssigned); Debug.Assert(AttachedType.ResolvedType.IsAssigned); IScopeAttributeFeature NewEntity = ScopeAttributeFeature.Create(Item, ValidText, AttachedType.ResolvedTypeName.Item, AttachedType.ResolvedType.Item); CheckedScope.Add(ValidText, NewEntity); } } IList <string> ConflictList = new List <string>(); for (int i = 0; i < node.AttachmentList.Count; i++) { IAttachment AttachmentItem = (Attachment)node.AttachmentList[i]; ISealableDictionary <string, IScopeAttributeFeature> CheckedScope = CheckedScopeList[i]; ScopeHolder.RecursiveCheck(CheckedScope, AttachmentItem.InnerScopes, ConflictList); } foreach (IName Item in node.EntityNameList) { Debug.Assert(Item.ValidText.IsAssigned); string ValidText = Item.ValidText.Item; if (ConflictList.Contains(ValidText)) { AddSourceError(new ErrorVariableAlreadyDefined(Item, ValidText)); Success = false; } } if (Success) { data = CheckedScopeList; } return(Success); }