Beispiel #1
0
        public void EmptyAttachContent()
        {
            attachments.Add(new Attachment()
            {
                Name = "test", MimeType = "image/png"
            });
            this.collector = new AttachmentsCollector(attachments, additionalAttachments);
            collector.Process(null, Logger);
            string expected = @"""attachments"": [
],
";

            Assert.AreEqual(expected, Content);
        }
Beispiel #2
0
        public void TestAddStreamContentType()
        {
            var      fileName    = Path.Combine(TestHelper.ProjectDir, "TestData", "images", "girl.jpg");
            var      contentType = new ContentType("image", "gif");
            var      attachments = new AttachmentCollection();
            MimePart attachment;

            using (var stream = File.OpenRead(fileName))
                attachment = (MimePart)attachments.Add(fileName, stream, contentType);

            Assert.AreEqual(contentType.MimeType, attachment.ContentType.MimeType);
            Assert.AreEqual("girl.jpg", attachment.ContentType.Name);
            Assert.NotNull(attachment.ContentDisposition);
            Assert.AreEqual("attachment", attachment.ContentDisposition.Disposition);
            Assert.AreEqual("girl.jpg", attachment.ContentDisposition.FileName);
            Assert.AreEqual("girl.jpg", attachment.FileName);
            Assert.AreEqual(ContentEncoding.Base64, attachment.ContentTransferEncoding);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
Beispiel #3
0
 private void AddAttachments(AttachmentCollection attachmentCollection, Dictionary <string, byte[]> attachments)
 {
     foreach (var attachment in attachments ?? Enumerable.Empty <KeyValuePair <string, byte[]> >())
     {
         attachmentCollection.Add(new Attachment(new MemoryStream(attachment.Value), attachment.Key));
     }
 }
Beispiel #4
0
        //</snippet17>

        //<snippet18>
        public static void CreateMessageWithFile(string server, string to)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage("*****@*****.**", to);

            message.Subject = "Monthly Expense report";
            message.Body    = "Please review the attached report.";
            // Attach a file to this email message.
            Attachment           data        = new Attachment("data.xls", MediaTypeNames.Application.Octet);
            AttachmentCollection attachments = message.Attachments;

            attachments.Add(data);
            SmtpClient client = new SmtpClient(server);

            client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateMessageWithFile: {0}",
                                  ex.ToString());
            }
        }
 private static void CopyAttachments(IEnumerable <Attachment> from, AttachmentCollection to)
 {
     foreach (var attachment in from)
     {
         to.Add(attachment);
     }
 }
 public static AttachmentCollection AddRange(this AttachmentCollection collection, IEnumerable <Attachment> attachments)
 {
     foreach (var attachment in attachments)
     {
         collection.Add(attachment);
     }
     return(collection);
 }
Beispiel #7
0
 private static void AddAttachmentsCollection(AttachmentCollection collection,
                                              IEnumerable <Attachment> attachments)
 {
     foreach (var attachment in attachments)
     {
         collection.Add(attachment);
     }
 }
Beispiel #8
0
 public static void AddAttachments(AttachmentCollection col, IEnumerable <string> atts)
 {
     if (atts != null)
     {
         foreach (var att in atts)
         {
             col.Add(new global::System.Net.Mail.Attachment(att));
         }
     }
 }
 /// <summary>
 /// Used for attaching files by byte array to email message.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="files"></param>
 public static void AddFilesFromStream(this AttachmentCollection sender, string[] files)
 {
     foreach (var file in files)
     {
         var ba = new AttachmentByteArray()
         {
             FullFilename = file
         };
         sender.Add(ba.Attachment);
     }
 }
Beispiel #10
0
    public static AttachmentCollection GetAttachmentsInfo(IDbConnection cn,string[] fileIds)
    {
        AttachmentCollection rv = new AttachmentCollection();

        using (IDataReader reader = YZDBProviderManager.CurrentProvider.GetAttachmentsInfo(cn,fileIds))
        {
            while (reader.Read())
                rv.Add(new Attachment(reader, YZAttachmentHelper.AttachmentRootPath));
        }

        return rv;
    }
Beispiel #11
0
 /// <summary>
 /// 处理附件
 /// </summary>
 /// <param name="attachments">附件集合</param>
 /// <param name="attachmentCollection">附件集合对象</param>
 protected virtual void HandlerAttachments(IList <IAttachment> attachments, AttachmentCollection attachmentCollection)
 {
     if (attachments == null || !attachments.Any())
     {
         return;
     }
     foreach (var item in attachments)
     {
         Attachment attachment = new Attachment(item.GetFileStream(), item.GetName());
         attachmentCollection.Add(attachment);
     }
 }
Beispiel #12
0
    public static AttachmentCollection GetAttachmentsInfo(IDbConnection cn, string[] fileIds)
    {
        AttachmentCollection rv = new AttachmentCollection();

        using (IDataReader reader = QueryManager.CurrentProvider.GetAttachmentsInfo(cn, fileIds))
        {
            while (reader.Read())
            {
                rv.Add(new Attachment(reader, YZAttachmentHelper.AttachmentRootPath));
            }
        }

        return(rv);
    }
        private static void AddAttachments(List <string> attachmentPathList, AttachmentCollection Attachments)
        {
            if (attachmentPathList == null)
            {
                return;
            }

            foreach (string att in attachmentPathList)
            {
                if (File.Exists(att))
                {
                    Attachments.Add(new Attachment(att));
                }
            }
        }
            private AttachmentCollection ReadAttachments(EPActivity message)
            {
                var fs = new AttachmentCollection(_graph);

                foreach (NoteDoc notes in
                         PXSelect <NoteDoc,
                                   Where <NoteDoc.fileID, IsNotNull,
                                          And <NoteDoc.noteID, Equal <Required <NoteDoc.noteID> > > > > .
                         Select(_graph, message.NoteID))
                {
                    fs.Add((Guid)notes.FileID);
                }

                var addFiles = PXSelect <DynamicAttachment,
                                         Where <DynamicAttachment.refNoteID, Equal <Required <DynamicAttachment.refNoteID> > > > .
                               Select(_graph, message.NoteID);

                foreach (Guid fileId in DynamicAttachmentManager.Process(_graph, addFiles.Extract()))
                {
                    fs.Add(fileId);
                }

                return(fs);
            }
Beispiel #15
0
            private string ExtractInlineImages(SMEmail message, AttachmentCollection fs)
            {
                string res;
                ICollection <PX.Data.ImageExtractor.ImageInfo> files;

                if (message.Body != null && new ImageExtractor().Extract(message.Body, out res, out files))
                {
                    foreach (PX.Data.ImageExtractor.ImageInfo imageInfo in files)
                    {
                        fs.Add(imageInfo.ID, imageInfo.ID.ToString(), imageInfo.Bytes);
                    }
                    return(res);
                }
                return(message.Body);
            }
Beispiel #16
0
            private AttachmentCollection ReadAttachments(SMEmail message)
            {
                var fs = new AttachmentCollection(_graph);

                foreach (NoteDoc notes in
                         PXSelect <NoteDoc,
                                   Where <NoteDoc.fileID, IsNotNull,
                                          And <NoteDoc.noteID, Equal <Required <NoteDoc.noteID> > > > > .
                         Select(_graph, message.RefNoteID))
                {
                    fs.Add((Guid)notes.FileID);
                }

                return(fs);
            }
Beispiel #17
0
        /// <summary>
        /// Handles the add attachment button's Click event.
        /// </summary>
        /// <param name="sender">The button object.</param>
        /// <param name="e">The event arguments.</param>
        private void btnAddAttachment_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            try
            {
                bool b = _changed;

                dlg.Filter      = "All files (*.*)|*.*";
                dlg.FilterIndex = 1;
                dlg.Title       = "Select a file";
                dlg.Multiselect = true;
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                // Creates an AttachmentCollection if _attachments is null.
                if (_attachments == null)
                {
                    _attachments = new AttachmentCollection();
                }

                // Adds selected files to the attachment collection and the combo box as well.
                foreach (string fileName in dlg.FileNames)
                {
                    _attachments.Add(fileName);
                    cbxAttachment.Items.Add(System.IO.Path.GetFileName(fileName));
                }
                // Selects the last item.
                cbxAttachment.SelectedIndex = cbxAttachment.Items.Count - 1;

                btnRemoveAttachment.Enabled = true;
                _changed                      = true;
                saveButton.Enabled            = true;
                saveAttachmentsButton.Enabled = true;
                if (b == false) // sets the title if needed.
                {
                    SetTitle();
                }
            }
            catch
            {
                MessageBox.Show(dlg.FileName + " is not a file", "Error");
            }
        }
        public void TestAddTextFileName()
        {
            var      fileName    = Path.Combine(TestHelper.ProjectDir, "TestData", "text", "lorem-ipsum.txt");
            var      attachments = new AttachmentCollection();
            MimePart attachment;

            attachment = (MimePart)attachments.Add(fileName);
            Assert.AreEqual("text/plain", attachment.ContentType.MimeType);
            Assert.AreEqual("lorem-ipsum.txt", attachment.FileName);
            Assert.AreEqual(ContentEncoding.SevenBit, attachment.ContentTransferEncoding);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
Beispiel #19
0
        public void TestAddFileName()
        {
            var      fileName    = Path.Combine(TestHelper.ProjectDir, "TestData", "images", "girl.jpg");
            var      attachments = new AttachmentCollection();
            MimePart attachment;

            attachment = (MimePart)attachments.Add(fileName);
            Assert.AreEqual("image/jpeg", attachment.ContentType.MimeType);
            Assert.AreEqual("girl.jpg", attachment.FileName);
            Assert.AreEqual(ContentEncoding.Base64, attachment.ContentTransferEncoding);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
Beispiel #20
0
        public void TestAddEmailMessage()
        {
            var        fileName    = Path.Combine(TestHelper.ProjectDir, "TestData", "messages", "body.1.txt");
            var        attachments = new AttachmentCollection();
            MimeEntity attachment;

            using (var stream = File.OpenRead(fileName))
                attachment = attachments.Add("message.eml", stream);

            Assert.AreEqual("message/rfc822", attachment.ContentType.MimeType);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
Beispiel #21
0
        private void DoSend(string authUsername, string authPassword, string authDomain)
        {
            if (_smtpServerHost == null)
            {
                throw new Exception("Please specify the SMTP Host Name before attempting to send.");
            }
            if (_toAddresses.Count == 0)
            {
                throw new Exception("No Email Addresses were provoided");
            }
            MailMessage message = new MailMessage();

            message.From = new MailAddress(_fromAddress);
            addAddresses(message.To, _toAddresses);
            addAddresses(message.CC, _ccAddresses);
            addAddresses(message.Bcc, _bccAddresses);
            message.Subject = _subject;
            message.Body    = _content;
            AttachmentCollection attachments = message.Attachments;

            foreach (string attachmentPath in _attachmentPaths)
            {
                attachments.Add(new Attachment(attachmentPath));
            }
            SmtpClient smtpServer = new SmtpClient();

            smtpServer.Host      = _smtpServerHost;
            smtpServer.Port      = _smtpServerPort;
            smtpServer.EnableSsl = _enableSSL;
            if (authUsername != null && authPassword != null)
            {
                NetworkCredential auth = new NetworkCredential(authUsername, authPassword);
                if (authDomain != null)
                {
                    auth.Domain = authDomain;
                }
                smtpServer.Credentials = auth;
            }
            else
            {
                smtpServer.UseDefaultCredentials = true;
            }
            smtpServer.Send(message);
        }
Beispiel #22
0
        public void LoadAttachments(PeopleCollection people)
        {
            AttachmentsListBox.Items.Clear();

            AttachmentCollection allAttachments = new AttachmentCollection();

            foreach (Person p in people)
            {
                foreach (Attachment Attachment in p.Attachments)
                {
                    bool add = true;

                    foreach (Attachment existingAttachment in allAttachments)
                    {
                        if (string.IsNullOrEmpty(Attachment.RelativePath))
                        {
                            add = false;
                        }

                        if (existingAttachment.RelativePath == Attachment.RelativePath)
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add == true)
                    {
                        allAttachments.Add(Attachment);
                    }
                }
            }


            foreach (Attachment Attachment in allAttachments)
            {
                AttachmentsListBox.Items.Add(Attachment);
            }

            if (AttachmentsListBox.Items.Count > 0)
            {
                AttachmentsListBox.SelectedIndex = 0;
            }
        }
        public void TestAddDataContentType()
        {
            var      fileName    = Path.Combine("..", "..", "TestData", "images", "girl.jpg");
            var      contentType = new ContentType("image", "gif");
            var      attachments = new AttachmentCollection();
            MimePart attachment;

            attachment = (MimePart)attachments.Add(fileName, File.ReadAllBytes(fileName), contentType);
            Assert.AreEqual(contentType.MimeType, attachment.ContentType.MimeType);
            Assert.AreEqual("girl.jpg", attachment.FileName);
            Assert.AreEqual(ContentEncoding.Base64, attachment.ContentTransferEncoding);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
Beispiel #24
0
 private static void FillAttachmentImageCollection(AttachmentCollection attachmentCollection, List <Image> imageAttachList)
 {
     if (imageAttachList == null || imageAttachList.Count <= 0)
     {
         return;
     }
     for (int i = 0; i < imageAttachList.Count; i++)
     {
         if (imageAttachList[i] == null)
         {
             continue;
         }
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         imageAttachList[i].Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
         ms.Position = i;
         Attachment attachment = new Attachment(ms, "Image" + (i + 1).ToString(CultureInfo.InvariantCulture));
         attachment.ContentId = "ImageEmail" + (i + 1).ToString(CultureInfo.InvariantCulture);
         attachmentCollection.Add(attachment);
     }
 }
        public void TestAddStream()
        {
            var      fileName    = Path.Combine("..", "..", "TestData", "images", "girl.jpg");
            var      attachments = new AttachmentCollection();
            MimePart attachment;

            using (var stream = File.OpenRead(fileName))
                attachment = (MimePart)attachments.Add(fileName, stream);

            Assert.AreEqual("image/jpeg", attachment.ContentType.MimeType);
            Assert.AreEqual("girl.jpg", attachment.FileName);
            Assert.AreEqual(ContentEncoding.Base64, attachment.ContentTransferEncoding);
            Assert.AreEqual(1, attachments.Count);

            Assert.IsTrue(attachments.Contains(attachment), "Contains");
            Assert.AreEqual(0, attachments.IndexOf(attachment), "IndexOf");
            Assert.IsTrue(attachments.Remove(attachment), "Remove");
            Assert.AreEqual(0, attachments.Count);
            attachments.Clear();
        }
        public static void FillList(AttachmentCollection coll, OdbcDataReader reader, int totalRows, int firstRow)
        {
            int  index    = 0;
            bool readMore = true;

            while (reader.Read())
            {
                if (index >= firstRow && readMore)
                {
                    if (coll.Count >= totalRows && totalRows > 0)
                    {
                        readMore = false;
                    }
                    else
                    {
                        Attachment attachmentitem = Attachment.AttachmentItem(reader);
                        coll.Add(attachmentitem);
                    }
                }
                index++;
            }
        }
        public string AddAttachmentWithName(string files, string fileNames)
        {
            string str;

            try
            {
                char[]   chrArray  = new char[] { ';' };
                string[] strArrays = files.Split(chrArray);
                chrArray = new char[] { ';' };
                string[] strArrays1 = fileNames.Split(chrArray);
                bool     length     = (int)strArrays.Length == (int)strArrays1.Length;
                for (int i = 0; i < (int)strArrays.Length; i++)
                {
                    string str1 = strArrays[i].Trim();
                    if (!string.IsNullOrEmpty(str1))
                    {
                        if ((!length ? true : string.IsNullOrWhiteSpace(strArrays1[i])))
                        {
                            this.message.Attachments.Add(new Attachment(str1));
                        }
                        else
                        {
                            AttachmentCollection attachments = this.message.Attachments;
                            Attachment           attachment  = new Attachment(str1)
                            {
                                Name = strArrays1[i].Trim()
                            };
                            attachments.Add(attachment);
                        }
                    }
                }
                str = "";
            }
            catch (Exception exception)
            {
                str = SmtpMessage.ErrorMessage(exception);
            }
            return(str);
        }
            private string GenerateBody(string content, AttachmentCollection fs)
            {
                var body   = content ?? string.Empty;
                var images = _imagesRegex.Matches(body);

                if (images.Count > 0)
                {
                    var sb           = new StringBuilder();
                    var currentIndex = 0;
                    foreach (Match match in images)
                    {
                        var  fileid = match.Groups[_FILEID_REGEX_GROUP];
                        var  src    = match.Groups[_SRC_REGEX_GROUP];
                        Guid imgId;
                        if (GUID.TryParse(fileid.Value, out imgId))
                        {
                            fs.Add(imgId);
                            sb.Append(body.Substring(currentIndex, src.Index - currentIndex));
                            sb.Append(AttachmentCollection.CreateLink(imgId));
                            sb.Append(_SRC_ATT_POSTFIX);
                            currentIndex = body.IndexOf(_SRC_ATT_POSTFIX, fileid.Index + fileid.Length) + _SRC_ATT_POSTFIX.Length;
                        }
                        else
                        {
                            var newIndex = src.Index + src.Length + _SRC_ATT_POSTFIX.Length;
                            sb.Append(body.Substring(currentIndex, newIndex - currentIndex));
                            currentIndex = newIndex;
                        }
                    }
                    if (currentIndex < body.Length - 1)
                    {
                        sb.Append(body.Substring(currentIndex));
                    }
                    body = sb.ToString();
                }
                return(body);
            }
Beispiel #29
0
 private static void FillAttachmentCollection(AttachmentCollection attachmentCollection, List <string> attachmentList, List <string> attachNameList)
 {
     if (attachmentList == null || attachmentList.Count <= 0)
     {
         return;
     }
     attachmentList.ForEach(
         delegate(string fileName)
     {
         Attachment attachment = new Attachment(fileName);
         attachmentCollection.Add(attachment);
     }
         );
     if (attachNameList != null)
     {
         for (int i = 0; i < attachmentList.Count; i++)
         {
             if (attachmentCollection.Count > i)
             {
                 attachmentCollection[i].Name = attachNameList[i];
             }
         }
     }
 }
 public void AddCount()
 {
     ac.Add(a);
     Assert.Equal(1, ac.Count);
 }
Beispiel #31
0
        public void ProcessReview()
        {
            MessageDisplay msgDisplay = CreateMessageDisplay();
            int postUserID;

            bool isV50 = true;
            if (IsEditPost || IsEditThread)
            {
                PostV5 post = PostBOV5.Instance.GetPost(PostID, false); //PostManager.GetPost(PostID).UserID;
                postUserID = post.UserID;
                isV50 = post.IsV5_0;
            }
            else
            {
                postUserID = MyUserID;
            }


            m_Review = true;
            reviewContent = _Request.Get("editor_content", Method.Post, string.Empty, false);

            reviewSubject = ClearHTML(_Request.Get("subject", Method.Post, string.Empty));

            if ((IsEditThread || IsCreateThread) && reviewSubject.Trim() == "")
            {
                msgDisplay.AddError("标题不能为空");
                //ShowAlert("标题不能为空!");
            }

            bool enableHTML = false, enableMaxCode3 = false;
            if (AllowHtml && AllowMaxcode)
            {
                enableHTML = _Request.Get("contentFormat", Method.Post, "").ToLower() == "enablehtml";
                if (enableHTML == false)
                    enableMaxCode3 = true;
            }
            else if (AllowHtml)
                enableHTML = true;
            else if (AllowMaxcode)
                enableMaxCode3 = true;

            bool enableEmoticon = AllowEmoticon && _Request.Get("enableItem", Method.Post, "").ToLower().IndexOf("enableemoticons") > -1;

            AttachmentCollection attachments = new AttachmentCollection();


            //string attachIdsText = _Request.Get("attachIds", Method.Post, string.Empty, false);
            //if (string.IsNullOrEmpty(attachIdsText) == false)
            //{
            //    int[] attachIds = StringUtil.Split<int>(attachIdsText, ',');


            //    GetAttachments(attachIds, "0", postUserID, msgDisplay, ref attachments);
            //}

            //string diskIdsText = _Request.Get("diskFileIDs", Method.Post, string.Empty, false);
            //if (string.IsNullOrEmpty(diskIdsText) == false)
            //{
            //    int[] diskFileIDs = StringUtil.Split<int>(diskIdsText, ',');

            //    GetAttachments(diskFileIDs, "1", postUserID, msgDisplay, ref attachments);
            //}

            GetAttachments(postUserID, msgDisplay, ref attachments);

            reviewContent = PostUbbParserV5.ParseWhenSave(postUserID, enableEmoticon, Forum.ForumID, reviewContent, enableHTML, enableMaxCode3, attachments);
            reviewContent = PostUbbParserV5.ParsePreviewLocalAttachTag(Forum.ForumID, UserBO.Instance.GetUser(postUserID,GetUserOption.WithAll), reviewContent, attachments);

            MatchCollection ms = PostUbbParserV5.regex_AllAttach.Matches(reviewContent);
            List<int> historyAttachmentIDs = new List<int>();

            foreach (Match m in ms)
            {
                bool isHistoryAttach = true;
                int attachID = int.Parse(m.Groups["id"].Value);
                foreach (Attachment attach in attachments)
                {
                    if (attachID == attach.AttachmentID)
                    {
                        isHistoryAttach = false;
                        break;
                    }
                }
                if (isHistoryAttach)
                    historyAttachmentIDs.Add(attachID);
            }

            AttachmentCollection historyAttachs = PostBOV5.Instance.GetAttachments(MyUserID, historyAttachmentIDs);

            foreach (Attachment attach in historyAttachs)
            {
                attachments.Add(attach);
            }

            reviewContent = PostUbbParserV5.ParseWhenDisplay(postUserID, Forum.ForumID, PostID, reviewContent, enableHTML, false, isV50, attachments);


            if (reviewContent.Trim() == "")
            {
                msgDisplay.AddError("内容不能为空");
            }

            if (msgDisplay.HasAnyError())
            {
                m_Review = false;
            }
        }
Beispiel #32
0
        public void TestArgumentExceptions()
        {
            var contentType = new ContentType("application", "octet-stream");
            var attachments = new AttachmentCollection();
            var items       = new MimeEntity[10];
            var data        = new byte[1024];

            using (var stream = new MemoryStream()) {
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((MimeEntity)null));
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty, data));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null, data));
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty, stream));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null, stream));
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty, contentType));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null, contentType));
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty, data, contentType));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null, data, contentType));
                Assert.Throws <ArgumentException> (() => attachments.Add(string.Empty, stream, contentType));
                Assert.Throws <ArgumentNullException> (() => attachments.Add((string)null, stream, contentType));

                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", (byte[])null));
                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", (Stream)null));
                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", (byte[])null, contentType));
                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", (Stream)null, contentType));

                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", (ContentType)null));
                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", data, null));
                Assert.Throws <ArgumentNullException> (() => attachments.Add("file.dat", stream, null));

                Assert.Throws <ArgumentNullException> (() => attachments.Contains(null));

                Assert.Throws <ArgumentNullException> (() => attachments.CopyTo(null, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => attachments.CopyTo(items, -1));

                Assert.Throws <ArgumentNullException> (() => attachments.IndexOf(null));

                Assert.Throws <ArgumentNullException> (() => attachments.Remove(null));
                Assert.Throws <ArgumentOutOfRangeException> (() => attachments.RemoveAt(0));

                attachments.Add(new TextPart("plain"));
                Assert.Throws <ArgumentOutOfRangeException> (() => { var x = attachments[10]; });
                Assert.Throws <ArgumentOutOfRangeException> (() => attachments[10] = new TextPart("plain"));
                Assert.Throws <ArgumentNullException> (() => attachments[0]        = null);

                Assert.Throws <ArgumentOutOfRangeException> (() => attachments.Insert(-1, new TextPart("plain")));
                Assert.Throws <ArgumentNullException> (() => attachments.Insert(0, null));
            }
        }
Beispiel #33
0
        private void GetAttachments(int postUserID, MessageDisplay msgDisplay, ref AttachmentCollection attachs)
        {
            AttachmentCollection attachments = new AttachmentCollection();
            DiskFileCollection diskFiles = null;

            List<int> tempFileIds = new List<int>(), diskFileIds=new List<int>();

            string[] attachIndexs = _Request.Get("attachIndex", Method.Post,string.Empty).Split( new string[]{ ","}, StringSplitOptions.RemoveEmptyEntries);


            foreach (string i in attachIndexs)
            {
                if (i == "{index}")
                    continue;
                int id = _Request.Get<int>("attachid_" + i, Method.Post, 0);
                int attachType=_Request.Get<int>("attachtype_" + i, Method.Post, 0);
                if ( attachType == 0)
                    tempFileIds.Add(id);
                else if( attachType==1 )
                    diskFileIds.Add(id);
            }

           diskFiles = DiskBO.Instance.GetDiskFiles(diskFileIds);
            
                Attachment attach;

                string extendName = string.Empty;
                foreach (DiskFile file in diskFiles)
                {
                    attach = new Attachment();
                    attach.DiskFileID = file.DiskFileID;
                    attach.FileID = file.FileID;
                    attach.FileSize = file.Size;
                    attach.FileName = _Request.Get("filename_1_" + file.DiskFileID, Method.Post, "未命名", false);
                    attach.Price = _Request.Get("price_1_" + file.DiskFileID, Method.Post, 0);
                    extendName = _Request.Get("extname_1_" + file.DiskFileID, Method.Post, string.Empty);
                    attach.AttachType = AttachType.DiskFile;
                    if (!string.IsNullOrEmpty(attach.FileName) && !string.IsNullOrEmpty(extendName))
                        attach.FileName += "." + extendName;

                    attach.FileType = extendName;
                    attachments.Add(attach);
                }

                foreach (int id in tempFileIds)
                {
                    attach = new Attachment();
                    attach.AttachmentID = id;
                    attach.FileName = _Request.Get("filename_0_" + id, Method.Post, "未命名", false);
                    attach.Price = _Request.Get("price_0_" + id, Method.Post, 0);

                    attach.AttachType = AttachType.TempAttach;

                    extendName = _Request.Get("extname_0_" + id, Method.Post, string.Empty);
                    if (!string.IsNullOrEmpty(attach.FileName) && !string.IsNullOrEmpty(extendName))
                        attach.FileName += "." + extendName;

                    attach.FileType = extendName;
                    attachments.Add(attach);
                }

            foreach(Attachment att in attachments)
            {
                att.PostID = 0;

                if (IsEditPost || IsEditThread)
                    att.UserID = postUserID;
                
                else
                    att.UserID = MyUserID;

                if (att.Price < 0)
                {
                    msgDisplay.AddError("附件售价不能小于0");
                    return;
                }
            }
            attachs.AddRange(attachments);
        }