/// <summary> /// Forms the memory stream of the mail with attachments. /// </summary> /// <param name="collectionOfAttachments">Collection of attachments as dictionary</param> /// <returns>Memory stream of the created mail object</returns> internal MemoryStream GetMailAsStream(Dictionary <string, Stream> collectionOfAttachments, string[] documentUrls, bool attachmentFlag) { MemoryStream result = null; string documentUrl = string.Empty; try { // need to be able to update/configure or get current version of server ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013); //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or explicitly specify the admin account (set default to false) service.Credentials = new WebCredentials(generalSettings.AdminUserName, generalSettings.AdminPassword); service.Url = new Uri(generalSettings.ExchangeServiceURL); Microsoft.Exchange.WebServices.Data.EmailMessage email = new Microsoft.Exchange.WebServices.Data.EmailMessage(service); email.Subject = documentSettings.MailCartMailSubject; if (attachmentFlag) { email.Body = new MessageBody(documentSettings.MailCartMailBody); foreach (KeyValuePair <string, Stream> mailAttachment in collectionOfAttachments) { if (null != mailAttachment.Value) { // Remove the date time string before adding the file as an attachment email.Attachments.AddFileAttachment(mailAttachment.Key.Split('$')[0], mailAttachment.Value); } } } else { int index = 0; foreach (string currentURL in documentUrls) { if (null != currentURL && 0 < currentURL.Length) { string[] currentAssets = currentURL.Split('$'); string documentURL = generalSettings.SiteURL + currentAssets[1]; string documentName = currentAssets[2]; documentUrl = string.Concat(documentUrl, string.Format(CultureInfo.InvariantCulture, "'{0} ) {1} : <a href='{2}'>{2} </a><br/>", ++index, documentName, documentURL)); } } documentUrl = string.Format(CultureInfo.InvariantCulture, "<div style='font-family:Calibri;font-size:12pt'>{0}</div>", documentUrl); email.Body = new MessageBody(documentUrl); } //// This header allows us to open the .eml in compose mode in outlook email.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Unsent", MapiPropertyType.String), "1"); email.Save(WellKnownFolderName.Drafts); // must save draft in order to get MimeContent email.Load(new PropertySet(EmailMessageSchema.MimeContent)); MimeContent mimcon = email.MimeContent; //// Do not make the StylCop fixes for MemoryStream here MemoryStream fileContents = new MemoryStream(); fileContents.Write(mimcon.Content, 0, mimcon.Content.Length); fileContents.Position = 0; result = fileContents; } catch (Exception exception) { //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); MemoryStream fileContents = new MemoryStream(); result = fileContents; } return(result); }
/// <summary> /// Forms the memory stream of the mail with attachments. /// </summary> /// <param name="collectionOfAttachments">Collection of attachments as dictionary</param> /// <returns>Memory stream of the created mail object</returns> internal MemoryStream GetMailAsStream(Dictionary<string, Stream> collectionOfAttachments, string[] documentUrls, bool attachmentFlag) { MemoryStream result = null; string documentUrl = string.Empty; try { // need to be able to update/configure or get current version of server ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013); //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or explicitly specify the admin account (set default to false) service.Credentials = new WebCredentials(generalSettings.AdminUserName, generalSettings.AdminPassword); service.Url = new Uri(generalSettings.ExchangeServiceURL); Microsoft.Exchange.WebServices.Data.EmailMessage email = new Microsoft.Exchange.WebServices.Data.EmailMessage(service); email.Subject = documentSettings.MailCartMailSubject; if (attachmentFlag) { email.Body = new MessageBody(documentSettings.MailCartMailBody); foreach (KeyValuePair<string, Stream> mailAttachment in collectionOfAttachments) { if (null != mailAttachment.Value) { // Remove the date time string before adding the file as an attachment email.Attachments.AddFileAttachment(mailAttachment.Key.Split('$')[0], mailAttachment.Value); } } } else { int index = 0; foreach (string currentURL in documentUrls) { if (null != currentURL && 0 < currentURL.Length) { string[] currentAssets = currentURL.Split('$'); string documentURL = generalSettings.SiteURL + currentAssets[1]; string documentName = currentAssets[2]; documentUrl = string.Concat(documentUrl, string.Format(CultureInfo.InvariantCulture, "{0} ) {1} : <a href='{2}'>{2} </a><br/>" , ++index, documentName, documentURL)); } } documentUrl = string.Format(CultureInfo.InvariantCulture, "<div style='font-family:Calibri;font-size:12pt'>{0}</div>", documentUrl); email.Body = new MessageBody(documentUrl); } //// This header allows us to open the .eml in compose mode in outlook email.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Unsent", MapiPropertyType.String), "1"); email.Save(WellKnownFolderName.Drafts); // must save draft in order to get MimeContent email.Load(new PropertySet(EmailMessageSchema.MimeContent)); MimeContent mimcon = email.MimeContent; //// Do not make the StylCop fixes for MemoryStream here MemoryStream fileContents = new MemoryStream(); fileContents.Write(mimcon.Content, 0, mimcon.Content.Length); fileContents.Position = 0; result = fileContents; } catch (Exception exception) { //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); MemoryStream fileContents = new MemoryStream(); result = fileContents; } return result; }
public string OutlookMain(string Subject, string BodyText, string[] ToRecipient, string[] ToRecipientC = null, string Attachment = "", bool Save = false, bool isUseDefaultCredentials=true, string SenderEmailAddress="") { try { EmailMessage message = new EmailMessage(GetService(isUseDefaultCredentials)); if (SenderEmailAddress != "") { message.From = SenderEmailAddress; } message.Subject = Subject; message.Body = BodyText; foreach (string subList in ToRecipientsSum(message, ToRecipient)) { message.ToRecipients.Add(subList); } if (ToRecipientC != null) { foreach (string subList in CCRecipientsSum(message, ToRecipientC)) { message.CcRecipients.Add(subList); } } if (!string.IsNullOrEmpty(Attachment)) { message.Attachments.AddFileAttachment(Attachment); } if (Save == true) { message.Save(); } message.SendAndSaveCopy(); MessageSent=MyConstans.Successful; } catch(ServiceResponseException) { MessageSent = MyConstans.WrongMail; } catch (ServiceRequestException) { MessageSent = MyConstans.Authenticationfailed; } catch (Exception) { throw; } return MessageSent; }
protected void ExchangeSend() { try { //String eMailExchange = System.Configuration.ConfigurationSettings.AppSettings.Get("MailExchange"); String username = System.Configuration.ConfigurationManager.AppSettings["ExchangeUsername"]; String password = System.Configuration.ConfigurationManager.AppSettings["ExchangePassword"]; String domain = System.Configuration.ConfigurationManager.AppSettings["ExchangeDomain"]; //ExchangeService service = new ExchangeService(); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //service.AutodiscoverUrl(eMailExchange); service.Credentials = new WebCredentials(username, password, domain); service.Url = new Uri("https://mail.cn.ab-inbev.com/EWS/Exchange.asmx"); EmailMessage message = new EmailMessage(service); message.Subject = Subject; message.Body = Content; message.ToRecipients.AddRange(EmailAddresses); message.Save(); message.SendAndSaveCopy(); } catch (Exception ex) { logger.LogError(ex.Message); } }
private void btnUploadConv_Click(object sender, EventArgs e) { FSWatch.EnableRaisingEvents = false; ImportProgressDialog ipd = new ImportProgressDialog(); AddOwnedForm(ipd); //ipd.Parent = this; //if (listFiles.SelectedItems.Count != 0) //{ ipd.Show(); int FileCounter = 0; String[] FileList = Directory.GetFiles(HistorySpoolerPath); int FileCount = FileList.Count(); ipd.prgImportProgress.Maximum = FileCount; foreach (String HistFile in FileList) { FileCounter++; FileInfo fi = new FileInfo(HistFile); ipd.prgImportProgress.Value = FileCounter; ipd.lblProgress.Text = String.Format("Processing file {0} of {1}...", FileCounter, FileCount); ipd.lblStatus.Text = String.Format("Uploading {0} ({1} bytes)...", fi.Name, fi.Length); if (_exchangeService == null) { _exchangeService = new ExchangeService(); var store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByExtension, "2.5.29.37", true); _exchangeService.Url = new Uri("https://autodiscover.mail.mil/EWS/Exchange.asmx"); X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(certs, "DEE Certificate Select", "Select a certificate to connect to DISA E-mail", X509SelectionFlag.SingleSelection); _exchangeService.Credentials = new ClientCertificateCredentials(scollection); } if (_imHistoryFolder == null) { _imHistoryFolder = FindImHistoryFolder(); } LyncHistoryFile lhf = new LyncHistoryFile(); lhf.ReadFromFile(fi.FullName); //lhf.ReadFromFile(((FileInfo)listFiles.SelectedItems[0].Tag).FullName); EmailMessage ConversationItem = new EmailMessage(_exchangeService); //ConversationItem.MimeContent = new MimeContent("UTF-8",File.ReadAllBytes(((FileInfo)listFiles.SelectedItems[0].Tag).FullName)); foreach(var Member in lhf._Guts.Members) { ConversationItem.ToRecipients.Add(new EmailAddress(Member.SIPAddress)); } ConversationItem.Body = lhf._Guts.HTML1; ConversationItem.Subject = lhf._Guts.Title; ConversationItem.From = new EmailAddress(lhf._Guts.Initiator.SIPAddress); ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer); //ExtendedPropertyDefinition PR_RECEIPT_TIME = new ExtendedPropertyDefinition(0x002A, MapiPropertyType.SystemTime); ConversationItem.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1); //ConversationItem.SetExtendedProperty(PR_RECEIPT_TIME, ((FileInfo)listFiles.SelectedItems[0].Tag).CreationTime); ConversationItem.Save(_imHistoryFolder.Id); if (btnLocalCopies.Checked) { if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\LyncArchive\\")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\LyncArchive\\"); } try { File.Move(HistFile, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\LyncArchive\\" + fi.Name); } catch { File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\LyncArchive\\" + fi.Name); File.Move(HistFile, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\LyncArchive\\" + fi.Name); } } else { File.Delete(HistFile); } //LoadConversation(((FileInfo)listFiles.SelectedItems[0].Tag).FullName); } ipd.Close(); UpdateFileList(); HTMLViewer.DocumentText = ""; FSWatch.EnableRaisingEvents = true; }
private GenResult EmailMessageFromMessage( StoredContact sender, StoredContact recipient, Storage.Message msg) { GenResult res = new GenResult(); try { EmailAddress em = Contact.Bind(this.service, new ItemId(sender.UniqId)) .EmailAddresses[EmailAddressKey.EmailAddress1]; EmailMessage newMsg = new EmailMessage(this.service) { From = em, Sender = em, Body = new MessageBody(msg.BodyHtml), Subject = msg.Subject }; newMsg.Save(WellKnownFolderName.Drafts); foreach (object obj in msg.Attachments) { Storage.Attachment attach = obj as Storage.Attachment; if (attach == null) continue; newMsg.Attachments.AddFileAttachment(attach.FileName, attach.Data); } this.FillAdresses(ref newMsg, recipient.Email); res.msg = newMsg; // делаем ли форвард if (RndTrueFalse()) { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage respMsg = newMsg.CreateForward(); respMsg.BodyPrefix = @"test body prefix for forward message"; this.FillAdressesForResponse(ref respMsg, this.RndRecipMail()); respMsg.Save(WellKnownFolderName.Drafts); res.response = respMsg; } // делаем ли реплай if (RndTrueFalse()) { /*newMsg.ReplyTo.Add(_RndRecipMail()); if (_RndTrueFalse()) { newMsg.ReplyTo.Add(_RndRecipMail()); } if (_RndTrueFalse()) */ { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage replMsg = newMsg.CreateReply(RndTrueFalse()); replMsg.BodyPrefix = @"test body prefix for reply message"; this.FillAdressesForResponse(ref replMsg, recipient.Email); replMsg.Save(WellKnownFolderName.Drafts); res.reply = replMsg; } } } catch (Exception exc) { GenericLogger<Generator>.Error( LocalizibleStrings.ErrorCreateFromTemplate + msg.FileName, exc); } return res; }
static void Main(string[] args) { var versionInf = new VersionInfo("old", "xref"); Filter(versionInf); var content = GetConfig <BuildConfig>(@"C:\TestFiles\xrefmap\docfx.temp.json"); var def = BranchNames.DefaultBranches; var branch1 = MappingBranch("live-sxs"); var ps = Path.Combine("/", "/basepath", "ab"); Uri uri; if (Uri.TryCreate("http://www.abc.com/base/a.html", UriKind.Relative, out uri)) { Console.WriteLine("is relative"); } var versionFolder = new VersionInfo("folder", null); File.WriteAllText(@"C:\TestFiles\xrefmap\filemap.now.json", JsonUtility.ToJsonString(versionFolder, true)); var paths = new List <string> { "1", "2" }; var joinedPath = string.Join(", ", paths); var dict = new Dictionary <int, int>(); dict.Add(0, 0); dict.Add(1, 1); dict.Add(2, 2); dict.Remove(0); dict.Add(10, 10); foreach (var entry in dict) { Console.WriteLine(entry.Key); } Dictionary <string, VersionInfo> versionInfo = new Dictionary <string, VersionInfo> { { "testMoniker-1.0_justfortest", new VersionInfo("v2.0/", null) }, { "testMoniker-1.1_justfortest", new VersionInfo("v2.1/", null) } }; var xrefmaps = new List <string> { "xrefmap.yml", "testMoniker-1.0_justfortest.xrefmap.yml", "testMoniker-1.1_justfortest.xrefmap.yml" }; var defaultXrefMap = xrefmaps.FirstOrDefault(x => string.Equals(x, DefaultXrefMap, StringComparison.OrdinalIgnoreCase)); var defaultVersionInfo = !string.IsNullOrEmpty(defaultXrefMap) ? new VersionInfo(string.Empty, defaultXrefMap) : null; var xrefmapsWithVersion = xrefmaps.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(XrefMapSuffix)); foreach (var xrefmapWithVersion in xrefmapsWithVersion) { var escapedVersion = xrefmapWithVersion.Substring(0, xrefmapWithVersion.Length - XrefMapSuffix.Length); if (!string.IsNullOrEmpty(escapedVersion)) { var unescapedversion = Uri.UnescapeDataString(escapedVersion); VersionInfo versionInfoItem; if (versionInfo.TryGetValue(unescapedversion, out versionInfoItem) && versionInfoItem != null) { versionInfoItem.XRefMap = xrefmapWithVersion; } } } var branch = "live"; myret(branch); Directory.CreateDirectory(@"c:\ab\c\text.txt"); //webc.Get(new Uri("c:\\ab.txt")); var da = new string[] { "1" }; var fir = da.First(x => x == "2"); foreach (var fi in fir) { Console.WriteLine(""); } Digit <string[]> dig = new Digit <string[]>(da); //This call invokes the implicit "double" operator string[] num = dig; //string snu = null; //var tsnu = (string)snu; //var t1 = PrintAsync(1); //var t2 = PrintAsync(2); //var t3 = PrintAsync(3); //var t4 = PrintAsync(4); //var t5 = PrintAsync(5); //var tasks = new List<Task> { t1, t2, t3 }; //TaskHelper.WhenAll(tasks, 2).Wait(); var depots = new List <string> { "1", "4", "2", "3" }; var allDepots = depots.Concat(new List <string> { "6" }); var dep = fff(depots).Result; var orderDepots = depots.OrderByDescending(depot => IsCurrentDepot("1", depot)); var nr = FileUtility.NormalizeRelativePath("test.txt"); var de = default(string); var manifestJson = File.ReadAllText(@"C:\Users\ychenu\Downloads\2929183a-17190aeb%5C201708210354455948-master\testMultipleVersion\test.json"); var buildManifest = JsonUtility.FromJsonString <BuildManifest>(manifestJson); foreach (var item in buildManifest.ItemsToPublish) { if (item.Type == PublishItemType.XrefMap) { Console.WriteLine($"{item.RelativePath} is xrefmap"); } } IEnumerable <string> itemss = new List <string> { "1.json", "2.json", "3.json" }; var itemsss = itemss.ToList(); itemss.GenerateMtaJsonFilesAsync().Wait(); var filename = Path.ChangeExtension("test\\test.md", ".mta.json"); JsonUtility.ToJsonFile(filename, "test"); var combined = Path.Combine("test\\index.md", ".mta.json"); var loop = TestLoop(3).ToList(); var version = "<abc>"; var escapedata = Uri.EscapeDataString(version); var data = Uri.UnescapeDataString(escapedata); Dictionary <string, List <string> > repoByKey = new Dictionary <string, List <string> >(); repoByKey["key1"] = new List <string> { "1" }; var repos = repoByKey["key1"]; repos.Add("2"); File.WriteAllLines(@"D:\Data\DataFix\FixLocRepoConfig\test.txt", new List <string> { "1", "2" }); File.AppendText(@"D:\Data\DataFix\FixLocRepoConfig\test.txt"); var now = $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.log"; var utcnow = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var pa = Path.Combine(@"c:\test\testfile", "RepositoryTableData.json"); var dir = Path.GetDirectoryName(@"c:\test\testfile\abc.txt"); Directory.CreateDirectory(dir); File.WriteAllText(@"c:\test\testfile\abc.txt", "test"); var list = new List <int> { }; var filter = list.Where(i => i == 3).ToList(); var useAsync = ConfigurationManager.AppSettings["UseAsync"]; var parallelism = -1; int.TryParse(ConfigurationManager.AppSettings["Parallelism"], out parallelism); Task.Factory.StartNew(() => { Thread.Sleep(5000); Console.WriteLine("sleep for 5s"); }).Wait(); var herf = "api/System.Web.UI.MobileControls.MobileListItem.OnBubbleEvent.html#System_Web_UI_MobileControls_MobileListItem_OnBubbleEvent_System_Object_System_EventArgs_"; var rep = GetNormalizedFileReference(herf, string.Empty); var dic = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); dic.Add("a", 1); dic.Add("A", 40); dic.Add("context", new Dictionary <string, object> { { "1", 3 } }); var hash = Hash.FromDictionary(dic); Console.WriteLine("before WaitForSomething"); WaitForSomething(); Console.WriteLine("after WaitForSomething"); AsyncAwaitDemo.Get().Wait(); var ie = new string[] { }.Where(i => i == ""); var jjj = string.Join(",", null); try { using (var reader = new StreamReader(@"C:\TestFiles\log.json")) { string line; while ((line = reader.ReadLine()) != null) { var logItem = JsonUtility.FromJsonString <LogItem>(line); } } } catch (Exception ex) { Console.WriteLine(ex); } var directory = @"C:\Git\OpenPublishing.Build"; var extensions = new string[] { ".config", ".csproj" }; var oldVersion = "2.19.0-alpha-0681-g405ed2d"; var newVersion = "2.19.0"; UpdatePackageVersion.Update(directory, extensions, oldVersion, newVersion); Convert.ToBoolean("s"); bool result; if (bool.TryParse(null, out result)) { var ssss = result; } var sbtest = new StringBuilder(); testsb(sbtest); sbtest.AppendLine("out of testsb"); Console.WriteLine(sbtest.ToString()); var silent = false; try { throw new FileNotFoundException(""); } catch (Exception) when(silent) { Console.WriteLine("catch"); } var li = new List <int> { 1, 2 }; var second = new List <int> { 3, 2 }; var exc = li.Except(second); li.Add(1); li.Add(1); var permission = OpsPermission.ReadOnly; permission |= OpsPermission.MonikerAdmin; var re = new int[] { 1 }.Where(x => x == 3); var co = re.Count(); CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions po = new ParallelOptions(); po.CancellationToken = cts.Token; Task.Factory.StartNew(() => { if (Console.ReadKey().KeyChar == 'c') { cts.Cancel(); } Console.WriteLine("press any key to exit"); }); Parallel.ForEach(new List <int>(), po, (algo) => { Task.Delay(2000).Wait(); // this compute lasts 1 minute Console.WriteLine("this job is finished"); po.CancellationToken.ThrowIfCancellationRequested(); }); try { Task.Run(() => { for (var i = 0; i < 100; ++i) { throw new Exception("throw from run"); } }); } catch (AggregateException aex) { Console.WriteLine("aex"); } catch (Exception ex) { Console.WriteLine("ex"); } var exchangeSvc = new MsExchange.ExchangeService(MsExchange.ExchangeVersion.Exchange2010) { Url = new Uri("https://outlook.office365.com/ews/exchange.asmx"), Credentials = new MsExchange.WebCredentials("*****@*****.**", "#Bugsfor$-160802"), TraceEnabled = true }; var message = new MsExchange.EmailMessage(exchangeSvc); message.ToRecipients.Add("*****@*****.**"); message.Subject = "test"; message.Body = "test body"; message.Save(); message.Send(); CreateOrUpdateDocument("abc_id", 6, new CreateOrUpdateDocumentRequest { ContentSourceUri = null, Metadata = new Dictionary <string, object> { { "assetId", "s" }, { "d", 7 } } }); var name = $"{nameof(args)}.{nameof(args.Rank)}"; var ar = new int[] { 6, 7, 3 }; var sortAr = ar.OrderByDescending(x => x); try { var fo = $"{"a"}{null}"; var items = new List <Item> { new Item { Version = "v1", Url = "d" }, new Item { Version = "v1", Url = "b" }, new Item { Version = "v1", Url = "c" }, new Item { Version = "v2", Url = "f" }, new Item { Version = "v2", Url = "a" } }; var web = new HtmlWeb() { //PreRequest = request => //{ // // Make any changes to the request object that will be used. // request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; // return true; //} }; var document = web.Load(@"https://opdhsblobsandbox01.blob.core.windows.net/contents/0ced3babc6274b949a9696c03ed9d944/3094b7719e20479798997b70294c9ee3"); FolderUtility.ForceDeleteAllSubDirectories(@"C:\TestFiles\Test", 1); } catch (AggregateException aex) { Console.WriteLine("aex"); } catch (Exception ex) { Console.WriteLine("ex"); } var array = new Task[] { }; var f = array.FirstOrDefault(); Array.ForEach(array, ele => { Console.WriteLine(ele); }); var commentSb = new StringBuilder(); for (int j = 0; j < 2; j++) { commentSb.AppendFormat(" [View]({0})", "path" + j); commentSb.Append("<br/>"); } commentSb.Length -= "<br/>".Length; commentSb.AppendLine(@" File | Status | Preview URL | Details ---- | ------ | ----------- | -------"); for (int i = 0; i < 2; i++) { commentSb.AppendFormat( "[{0}]({1}) | {2} |", "path" + i, "http://abc" + i, "success"); var sb = new StringBuilder(); for (int j = 0; j < 2; j++) { commentSb.AppendFormat(" [View]({0})", "path" + j); if (j == 0) { commentSb.AppendFormat("({0})", j); } commentSb.Append("<br/>"); } commentSb.AppendFormat(" |"); commentSb.AppendFormat(" [Details](#user-content-{0})", "details"); commentSb.AppendLine(); } var strsb = commentSb.ToString(); File.WriteAllText(@"C:\TestFiles\comment.md", strsb); //var derived = new DerivedPackageDownloadAndUnzipPathInfo(); string source = null; Console.WriteLine($"{source}-abc"); var packageTypeToPathsMap = new Dictionary <BlobPackageType, PackageDownloadAndUnzipPathInfo>(); var skipPackageDownloadingMap = new Dictionary <BlobPackageType, bool>(); skipPackageDownloadingMap[BlobPackageType.Source] = true; skipPackageDownloadingMap[BlobPackageType.Cache] = true; var skip = JsonUtility.ToJsonString(skipPackageDownloadingMap); var packageTypeToSkipFlagMap = JsonUtility.FromJsonString <Dictionary <BlobPackageType, bool> >(skip); foreach (var packageTypeToSkipFlagKeyValuePair in packageTypeToSkipFlagMap) { var blobPackageType = packageTypeToSkipFlagKeyValuePair.Key; var skipPackageDownloading = packageTypeToSkipFlagKeyValuePair.Value; //if (!skipPackageDownloading) { var packageBlobDownloadPath = packageTypeToPathsMap[blobPackageType].PackageBlobDownloadPath; } } var path = Path.GetTempPath(); try { var details = "data ex"; throw new InvalidDataException($"invalid {details}"); } catch (InvalidDataException idex) { Console.WriteLine($"data ex: {idex}"); } catch (Exception ex) { Console.WriteLine("ex"); } var workingDirectory = Path.Combine(@"c:\users\ychenu", Path.GetRandomFileName().Substring(0, 4)); var work = new Work(); }
private static async Task <bool> SendByExchangeAsync(EmailNetConfiguration emailConfig) { Exchange.ExchangeService service = new Exchange.ExchangeService(emailConfig.EmailExchange.ExchangeVersion); service.Credentials = new NetworkCredential(emailConfig.Username, emailConfig.Password); if (emailConfig.EmailExchange.IsTraceEnabled) { service.TraceEnabled = true; service.TraceFlags = emailConfig.EmailExchange.TraceFlags; } service.AutodiscoverUrl(emailConfig.EmailAddress.FromEmail, RedirectionUrlValidationCallback); Exchange.EmailMessage message = new Exchange.EmailMessage(service); message.Subject = emailConfig.Subject; message.Body = new Exchange.MessageBody(emailConfig.Body.Value); emailConfig.To.ForEach(to => message.ToRecipients.Add(new Exchange.EmailAddress(to.FromEmail))); if (emailConfig.Bcc?.Count > 0) { emailConfig.Bcc.ForEach(bcc => message.BccRecipients.Add(new Exchange.EmailAddress(bcc.FromEmail))); } if (emailConfig.Cc?.Count > 0) { emailConfig.Cc.ForEach(cc => message.CcRecipients.Add(new Exchange.EmailAddress(cc.FromEmail))); } if (emailConfig.Attachement.IsAttachement) { Utils.IsDirectoryExistsThrowException(emailConfig.Attachement.AttachementPathDirectory); if (emailConfig.Zip.IsCompressed) { Utils.ZipFiles(emailConfig.Attachement.AttachementPathDirectory, emailConfig.Zip.ZipPathDirectory, emailConfig.Zip.IsDelete); var file = Utils.ReadAllBytes(emailConfig.Zip.ZipPathDirectory).FirstOrDefault(); message.Attachments.AddFileAttachment(file.filename); if (emailConfig.Zip.IsDelete) { Utils.DeleteFilesDirectory(emailConfig.Zip.ZipPathDirectory, true); } } else { foreach (var file in Utils.ReadAllBytes(emailConfig.Attachement.AttachementPathDirectory)) { message.Attachments.AddFileAttachment(file.filename); } } } Utils.Show($"\nEnviando email con {nameof(EmailNetService)}..."); await message.Save(); await message.SendAndSaveCopy(); return(await Task.FromResult(true)); }