Esempio n. 1
1
        public static void SendFormData(string ServerPath,HttpPostedFileBase[] files, string fileName, byte[] pdfArray, byte[] xmlArray)
        {
            var message = new EmailMessage(service)
            {
                Subject = fileName, 
                Body = fileName
            };
            message.ToRecipients.Add(ConfigurationManager.AppSettings["TargetMailBox"]);
            message.Attachments.AddFileAttachment(fileName + ".pdf", pdfArray);
            message.Attachments.AddFileAttachment(fileName + ".xml", xmlArray);

            try
            {
                /*Lopp for multiple files*/
                foreach (HttpPostedFileBase file in files)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    /*Saving the file in server folder*/
                    var path = System.IO.Path.Combine(ServerPath, filename);
                    message.Attachments.AddFileAttachment(path);
                    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                }


            }
            catch
            {

            }

            message.Send();
        }
Esempio n. 2
0
        public static void Transaction_CK_OrdersSendAlert()
        {
            try
            {
                var directory = new DirectoryInfo(zipPath);
                var myFile    = (from f in directory.GetFiles()
                                 orderby f.LastWriteTime descending
                                 select f).First();

                ExchangeService service  = new ExchangeService();
                string          from     = ConfigurationSettings.AppSettings["FromAddress"];
                string          frompass = ConfigurationSettings.AppSettings["FromPassword"];
                service.Credentials = new NetworkCredential(from, frompass);

                service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                EmailMessage message = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);
                message.Subject = ConfigurationSettings.AppSettings["MailSubject_CKOrder"] + strFileNameServiceDate + "";
                message.Body    = ConfigurationSettings.AppSettings["MailBody_CKOrder"] + strFileNameServiceDate + " excel";
                var path = System.IO.Path.Combine(directory + myFile.ToString());

                message.Attachments.AddFileAttachment(path);

                foreach (var address in ConfigurationSettings.AppSettings["ToAddressCK"].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.ToRecipients.Add(address);
                }
                message.Send();
            }
            catch (Exception ex)
            {
                SendAlertError(ex);
            }
        }
Esempio n. 3
0
        public static void SendMailTest()
        {
            EmailMessage message = new EmailMessage(service);
            message.Subject = "integration testts";
            message.Body = "fkytfoyufoyfy";
            message.ToRecipients.Add(ConfigurationManager.AppSettings["TargetMailBox"]);


            message.Send();
        }
 public bool Send(string to, string subject, string body, string theme = null)
 {
     EmailMessage message = new EmailMessage(_service);
     message.ToRecipients.Add(new EmailAddress(to));
     message.Subject = subject;
     message.Body = body;
     message.From = System.Configuration.ConfigurationManager.AppSettings["Affine.Email.User"];
     message.Send();
     return true;
 }
Esempio n. 5
0
        public static void SendConfirmationEmail(string address, Guid formId, DateTime fileDate)
        {
            var message = new EmailMessage(service)
            {
                Subject = EmailResources.ConfirmationMailHeader,
                Body = String.Format(EmailResources.ConfirmationMailBody, fileDate.ToString(CultureInfo.GetCultureInfo("cs-Cz")), formId)
            };
            message.ToRecipients.Add(address);           

            message.Send();
        }
Esempio n. 6
0
        static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Error.WriteLine("Usage: mail [email protected] subject");
                return 1;
            }

            try
            {
                string account = System.Environment.GetEnvironmentVariable("EMAIL");
                if (account == null)
                {
                    Console.Error.WriteLine("Set an environment variable called EMAIL with YOUR e-mail address.");
                    return 2;
                }

                string message = ReadStdin();
                if (message.Length == 0)
                {
                    Console.Error.WriteLine("No mail sent since stdin was empty.");
                    return 3;
                }

                Console.WriteLine("Sending e-mail using account '{0}'", account);
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(account, "");
                service.UseDefaultCredentials = true;

                // For verbose logging
                /*service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;*/

                service.AutodiscoverUrl(account, RedirectionUrlValidationCallback);

                EmailMessage email = new EmailMessage(service);
                email.ToRecipients.Add(args[0]);
                email.Subject = args[1];
                message = message.Replace("\n", "<br/>\n");
                email.Body = new MessageBody(message);

                email.Send();
                Console.WriteLine("Email successfully sent to '{0}'", args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 4;
            }

            return 0;
        }
Esempio n. 7
0
 //Функция отправки сообщений на Email
 public Task SendEmail(string GetEmail, string mailSubject, string mailBody)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Body = new Exchange.MessageBody(mailBody);
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
Esempio n. 8
0
 //Функция отправки сообщений на Email
 public static Task SendEmail(string GetEmail, string itemName)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Subject = "Аукцион #ProКачка - Вы выиграли приз!";
         emailMessage.Body = new Exchange.MessageBody("Поздравляем, вы выиграли " + itemName + " на нашем аукционе #ProКачка.");
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
        public IHttpActionResult Send(SendEmailRequest request)
        {
            // Send Email
            var email = new EmailMessage(ExchangeServer.Open());

            email.ToRecipients.AddRange(request.Recipients);

            email.Subject = request.Subject;
            email.Body = new MessageBody(request.Body);


            email.Send();
            return Ok(new SendEmailResponse { Recipients = request.Recipients });
        }
Esempio n. 10
0
        private static void SendMessages(ExchangeService service, ExchangeGeneratorParameters genParameters, ServerConnectionCredentials serverCreds, Random random1)
        {
            var email = new EmailMessage(service);

            email.ToRecipients.Add(genParameters.Recipient);
            email.Body = new MessageBody(HelperMethods.RandomString((int)genParameters.MessageSize,random1));
            email.Subject = "Exchange Generator (" + genParameters.MessageSize+")";

            var serviceRequestRetryCount = 0;
            var serviceResponseRetryCount = 0;

            while (true)
            {
                try
                {
                    email.Send();
                    break;
                }
                catch (ServiceRequestException e)
                {
                    if (serviceRequestRetryCount < 3)
                    {
                        serviceRequestRetryCount++;
                        Logger.Log("ServiceRequestException has been caught, retry in 15 seconds.", Logger.LogLevel.Warning, serverCreds.Ip);
                        Thread.Sleep(15000);

                    }
                    else
                    {
                        Logger.LogError("Something wrong with exchange server.", serverCreds.Ip, e);
                        throw;
                    }

                }
                catch (ServiceResponseException e)
                {
                    if (serviceResponseRetryCount < 3)
                    {
                        serviceResponseRetryCount++;
                        Logger.Log("ServiceResponseException has been caught, retry in 15 seconds.", Logger.LogLevel.Warning, serverCreds.Ip);
                        Thread.Sleep(15000);
                    }
                    else
                    {
                        Logger.LogError("Something wrong with exchange server.", serverCreds.Ip, e);
                        throw;
                    }
                }
            }
        }
Esempio n. 11
0
        public static void SendNotiifcationEmail(string emailBody, List<string> recepients)
        {
            try
            {
                string rootUrl = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
                // Create a new Exchange service object
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                StringBuilder sbUserStatus = new StringBuilder();
                string ExchangeServerEmail = ConfigurationManager.AppSettings["ExchangeServerEmailID"];
                string ExchangeServerpwd = ConfigurationManager.AppSettings["ExchangeServerpwd"];
                foreach (string toEmail in recepients)
                {
                    string encryptedEmail = EncryptionUtility.Encrypt(toEmail);
                    string url = string.Format(rootUrl + "Usersettings/Unsubscribe?validateToken={0}", encryptedEmail);
                    emailBody = emailBody.Replace("{unsubribelink}", url);
                    // Set user login credentials
                    service.Credentials = new WebCredentials(ExchangeServerEmail, ExchangeServerpwd);
                    try
                    {
                        //Set Office 365 Exchange Webserivce Url
                        string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx";
                        service.Url = new Uri(serviceUrl);
                        EmailMessage emailMessage = new EmailMessage(service);
                        emailMessage.Subject = "PnP TestAutomation daily summary report";
                        emailMessage.Body = new MessageBody(BodyType.HTML, emailBody);
                        emailMessage.ToRecipients.Add(toEmail);
                        //emailMessage.BccRecipients.Add(toEmail);
                        emailMessage.Send();

                    }
                    catch (AutodiscoverRemoteException exception)
                    {
                        Console.WriteLine("Erroe while sending the mails to user" + toEmail + exception.Message);
                        throw;

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erroe while sending the mails to users" + ex.Message);
            }
        }
Esempio n. 12
0
        public void SendMail()
        {
            try
            {

                ExchangeService service = new ExchangeService();

                service.Credentials = new NetworkCredential("user", "pass", "banglalink");
                service.Url = new System.Uri(@"https://mail.banglalinkgsm.com/EWS/Exchange.asmx");
                service.AutodiscoverUrl("*****@*****.**");
                EmailMessage message = new EmailMessage(service);

                message.Subject = "Test Mail";
                message.Body = "Auto Generated Test Mail";
                message.ToRecipients.Add("*****@*****.**");

               // message.Attachments.AddFileAttachment("");
                message.Send();

                //ExchangeService service = new ExchangeService();
                //service.Credentials = new WebCredentials("onm_iss", "password", "banglalink"); ; //new NetworkCredential("OnMSharingDB", "password","banglalinkgsm");
                //service.AutodiscoverUrl("*****@*****.**");
                //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**");

                ////service.na
                //EmailMessage message = new EmailMessage(service);
                //message.From = "*****@*****.**";
                //message.Subject = "Test Mail";
                //message.Body = "Auto Generated Test Mail";
                //message.ToRecipients.Add("*****@*****.**");
                ////message.ToRecipients.Add("*****@*****.**");
                //message.Save();

                //message.SendAndSaveCopy();
                ////message.Send();

            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 13
0
        public static void SendAlertError(Exception ex)
        {
            string strBody = "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                             "" + Environment.NewLine + "Date :" + DateTime.Now.ToString();
            ExchangeService service  = new ExchangeService();
            string          from     = ConfigurationSettings.AppSettings["FromAddress"];
            string          frompass = ConfigurationSettings.AppSettings["FromPassword"];

            service.Credentials = new NetworkCredential(from, frompass);

            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            EmailMessage message = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);

            message.Subject = "Error in tenaris order utility : " + ex.Message;
            message.Body    = strBody;
            foreach (var address in ConfigurationSettings.AppSettings["ToAddressErrorNotification"].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.ToRecipients.Add(address);
            }
            message.Send();
        }
        /// <summary>
        /// Sends the specified <see cref="MailMessage" /> through the email server.
        /// </summary>
        /// <param name="message">The <see cref="MailMessage" /> to send.</param>
        /// <param name="attachments">The attachments to include with the message.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="message" /> is null.
        /// <para>or</para>
        /// <paramref name="attachments" /> is null.
        /// </exception>
        public void Send(MailMessage message, IEnumerable <FileInfo> attachments)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (attachments == null)
            {
                throw new ArgumentNullException(nameof(attachments));
            }

            ExchangeMessage email = new ExchangeMessage(_service);

            email.Subject = message.Subject;
            email.Body    = message.Body;

            foreach (MailAddress toRecipient in message.To)
            {
                email.ToRecipients.Add(toRecipient.Address);
            }

            foreach (MailAddress ccRecipient in message.CC)
            {
                email.CcRecipients.Add(ccRecipient.Address);
            }

            foreach (FileInfo file in attachments)
            {
                email.Attachments.AddFileAttachment(file.FullName);
            }

            foreach (string key in message.Headers.AllKeys)
            {
                ExtendedPropertyDefinition headerDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, key, MapiPropertyType.String);
                email.SetExtendedProperty(headerDefinition, message.Headers[key]);
            }

            email.Send();
        }
        public void Send(MailMessage message)
        {
            ex.EmailMessage exchangeMessage = new ex.EmailMessage(GetExchangeService(Username, Password));

            if (message.From != null && !string.IsNullOrEmpty(message.From.Address))
            {
                exchangeMessage.From = new ex.EmailAddress(message.From.Address);
            }
            else
            {
                exchangeMessage.From = new ex.EmailAddress(_config["NOME_CAIXA"]);
            }

            exchangeMessage.Subject = message.Subject;
            exchangeMessage.Body = new ex.MessageBody(message.IsBodyHtml ? ex.BodyType.HTML : ex.BodyType.Text, message.Body);

            foreach (var destinatario in message.To)
            {
                exchangeMessage.ToRecipients.Add(destinatario.Address);
            }

            foreach (var copia in message.CC)
            {
                exchangeMessage.CcRecipients.Add(copia.Address);
            }

            foreach (var copiaOculta in message.Bcc)
            {
                exchangeMessage.BccRecipients.Add(copiaOculta.Address);
            }
           
            foreach (Attachment attachment in message.Attachments)
            {
                exchangeMessage.Attachments.AddFileAttachment(attachment.Name);
            }

            exchangeMessage.Send();
        }
Esempio n. 16
0
        private static void SendEmailWithReport(ExchangeService service, string recipient)
        {
            EmailMessage email = new EmailMessage(service);
            EmailAddress to = new EmailAddress();
            MessageBody body = new MessageBody();
            body.BodyType = BodyType.HTML;
            body.Text = "sample body.";
            var subject = "Sample subject " + DateTime.Now;

            to.Address = recipient;
            email.ToRecipients.Add(to);
            email.Subject = subject;

            email.Body = body + "\r\n" + File.ReadAllText(@"C:\sample.html");

            email.Send();
        }
Esempio n. 17
0
 private void sendEmail()
 {
     EmailMessage email = new EmailMessage(service);
     email.Subject = "Hello World!";
     email.ToRecipients.Add("*****@*****.**");
     email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
     email.Send();
 }
Esempio n. 18
0
        public void SendUntrackMail(string from, string[] toList, string[] ccList, string body, string subject, string[] attachmentsPathList)
        {
            if (toList.Length > 0)
            {
                EmailMessage email = new EmailMessage(service);
                //email.From = new EmailAddress(from);
                email.Subject = subject;
                email.Body = body;

                if (null != toList)
                {
                    for (int i = 0; i < toList.Length; i++)
                    {
                        email.ToRecipients.Add(toList[i]);
                    }
                }

                if (null != ccList)
                {
                    for (int i = 0; i < ccList.Length; i++)
                    {
                        email.CcRecipients.Add(ccList[i]);
                    }
                }

                if (attachmentsPathList != null)
                {
                    for (int i = 0; i < attachmentsPathList.Length; i++)
                    {
                        email.Attachments.AddFileAttachment(attachmentsPathList[i]);
                    }
                }

                email.Send();
            }
        }
Esempio n. 19
0
        private void EwsTest_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(UserName.Text) || string.IsNullOrEmpty(Psw.Text) ||
                string.IsNullOrEmpty(DomainName.Text) ||
                string.IsNullOrEmpty(SendAddress.Text))
            {
                MessageBox.Show("请输入正确的数据,不能为空!");
                return;
            }

            try
            {
                SetUserAndSendInfo();

                ResultText.Text = "";
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

                service.Credentials = new WebCredentials(UserName.Text, Psw.Text, DomainName.Text);

                service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;
                service.TraceListener = this;

                service.AutodiscoverUrl(SendAddress.Text, RedirectionUrlValidationCallback);

                EmailMessage email = new EmailMessage(service);

                email.ToRecipients.Add(SendAddress.Text);

                email.Subject = "HelloWorld";
                email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");

                email.Send();
            }
            catch(Exception ex)
            {
                ResultText.Text += ex.Message;
            }
        }
Esempio n. 20
0
        private static void SentEmailNotificationForCreatedMatters(MatterInformationVM matterInformation1, ExchangeService service, TextWriter log, IConfigurationRoot configuration)
        {            
            string mailSubject = configuration.GetSection("Mail").GetSection("MatterMailSubject").Value;
            string defaultHtmlChunk = configuration.GetSection("Mail").GetSection("MatterMailDefaultContentTypeHtmlChunk").Value;
            string oneNoteLibrarySuffix = configuration.GetSection("Matter").GetSection("OneNoteLibrarySuffix").Value;
            string matterMailBodyMatterInformation = configuration.GetSection("Mail").GetSection("MatterMailBodyMatterInformation").Value;
            string matterMailBodyConflictCheck = configuration.GetSection("Mail").GetSection("MatterMailBodyConflictCheck").Value;
            string matterCenterDateFormat = configuration.GetSection("Mail").GetSection("MatterCenterDateFormat").Value;
            string matterMailBodyTeamMembers = configuration.GetSection("Mail").GetSection("MatterMailBodyTeamMembers").Value;
            //De Serialize the matter information
            MatterInformationVM originalMatter = JsonConvert.DeserializeObject<MatterInformationVM>(matterInformation1.SerializeMatter);
            Matter matter = originalMatter.Matter;
            MatterDetails matterDetails = originalMatter.MatterDetails;
            Client client = originalMatter.Client;

            string matterMailBody, blockUserNames;
            // Generate Mail Subject
            string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSubject,
                matter.Id, matter.Name, originalMatter.MatterCreator);

            // Step 1: Create Matter Information
            string defaultContentType = string.Format(CultureInfo.InvariantCulture,
                defaultHtmlChunk, matter.DefaultContentType);
            string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);
            if (matterType == string.Empty)
            {
                matterType = defaultContentType;
            }
            // Step 2: Create Team Information
            string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                ServiceConstants.NO : ServiceConstants.YES;
            string mailBodyTeamInformation = string.Empty;
            mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

            string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH,
                    matter.MatterGuid, oneNoteLibrarySuffix,
                            ServiceConstants.FORWARD_SLASH, matter.MatterGuid, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);

            if (originalMatter.IsConflictCheck)
            {
                string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                                ServiceConstants.NO : ServiceConstants.YES;
                blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture,
            "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                matterMailBody = string.Format(CultureInfo.InvariantCulture,
                    matterMailBodyMatterInformation, client.Name, client.Id,
                    matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture,
                    matterMailBodyConflictCheck, ServiceConstants.YES, matter.Conflict.CheckBy,
                    Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(matterCenterDateFormat, CultureInfo.InvariantCulture),
                    conflictIdentified) + string.Format(CultureInfo.InvariantCulture,
                    matterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation,
                    blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);

            }
            else
            {
                blockUserNames = string.Empty;
                matterMailBody = string.Format(CultureInfo.InvariantCulture, matterMailBodyMatterInformation,
                    client.Name, client.Id, matter.Name, matter.Id,
                    matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, matterMailBodyTeamMembers, secureMatter,
                    mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);
            }

            EmailMessage email = new EmailMessage(service);
            foreach (IList<string> userNames in matter.AssignUserEmails)
            {
                foreach (string userName in userNames)
                {
                    if (!string.IsNullOrWhiteSpace(userName))
                    {
                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                        {
                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, userName, null, log))
                            {
                                if(userName.ToLower().IndexOf("#ext")>0)
                                {
                                    string tempUserName = userName.ToLower();
                                    tempUserName = tempUserName.Replace("#ext", "$").Split('$')[0];
                                    tempUserName = ReplaceLastOccurrence(tempUserName, "_", "@");
                                    email.ToRecipients.Add(tempUserName);
                                }
                                else
                                {
                                    email.ToRecipients.Add(userName);
                                }                                
                            }
                        }
                    }
                }
            }
            email.From = new EmailAddress(configuration["General:AdminUserName"]);            
            email.Subject = matterMailSubject;
            email.Body = matterMailBody;
            email.Send();
            Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"],
                            configuration["Settings:MatterRequests"], "Accepted", "Status");
        }
Esempio n. 21
0
        private static void SentEmailNotificationForCreatedIsBackwardCompatibleMatters(MatterInformationVM matterInformation1, ExchangeService service, TextWriter log, IConfigurationRoot configuration)
        {
            
            string mailSubject = configuration.GetSection("Mail").GetSection("MatterMailSubject").Value;
            string defaultHtmlChunk = configuration.GetSection("Mail").GetSection("MatterMailDefaultContentTypeHtmlChunk").Value;
            string oneNoteLibrarySuffix = configuration.GetSection("Matter").GetSection("OneNoteLibrarySuffix").Value;
            string matterMailBodyMatterInformation = configuration.GetSection("Mail").GetSection("MatterMailBodyMatterInformation").Value;
            string matterMailBodyConflictCheck = configuration.GetSection("Mail").GetSection("MatterMailBodyConflictCheck").Value;
            string matterCenterDateFormat = configuration.GetSection("Mail").GetSection("MatterCenterDateFormat").Value;
            string matterMailBodyTeamMembers = configuration.GetSection("Mail").GetSection("MatterMailBodyTeamMembers").Value;
            ///For isbackward compatability true
            MatterInformationVM originalMatter = JsonConvert.DeserializeObject<MatterInformationVM>(matterInformation1.SerializeMatter);
            Matter matter = originalMatter.Matter;
            MatterDetails matterDetails = originalMatter.MatterDetails;
            Client client = originalMatter.Client;
            string practiceGroupColumnName = configuration["ContentTypes:ManagedColumns:ColumnName1"].ToString();
            string areaOfLawColumnName = configuration["ContentTypes:ManagedColumns:ColumnName2"].ToString();
            string matterMailBody;
            string practiceGroupValue = originalMatter.MatterDetails.ManagedColumnTerms[practiceGroupColumnName].TermName;
            string areaOfLawValue = originalMatter.MatterDetails.ManagedColumnTerms[areaOfLawColumnName].TermName;

            // Generate Mail Subject
            string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSubject,
                matter.Id, matter.Name, originalMatter.MatterCreator);

            // Step 1: Create Matter Information
            string defaultContentType = string.Format(CultureInfo.InvariantCulture,
                defaultHtmlChunk, matter.DefaultContentType);
            string matterType = defaultContentType;
            if (matterType == string.Empty)
            {
                matterType = defaultContentType;
            }
            // Step 2: Create Team Information
            string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                ServiceConstants.NO : ServiceConstants.YES;
            string mailBodyTeamInformation = string.Empty;
            mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

            string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH,
                    matter.MatterGuid, oneNoteLibrarySuffix,
                            ServiceConstants.FORWARD_SLASH, matter.Name, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);
            string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                            ServiceConstants.NO : ServiceConstants.YES;
            matterMailBody = string.Format(CultureInfo.InvariantCulture,
                matterMailBodyMatterInformation,
                practiceGroupValue,
                areaOfLawValue,
                 matter.Name,
                matter.Description,
                matter.Name + " OneNote",
                matterType,
               originalMatter.MatterCreator,
            string.Format("{0:MMM dd, yyyy}", DateTime.Now),
            originalMatter.MatterLocation,
                client.Url, oneNotePath,
                configuration["General:SiteURL"].ToString());

            EmailMessage email = new EmailMessage(service);
            foreach (IList<string> userNames in matter.AssignUserEmails)
            {
                foreach (string userName in userNames)
                {
                    if (!string.IsNullOrWhiteSpace(userName))
                    {
                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                        {
                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, userName, null, log))
                            {
                                if (userName.ToLower().IndexOf("#ext") > 0)
                                {
                                    string tempUserName = userName.ToLower();
                                    tempUserName = tempUserName.Replace("#ext", "$").Split('$')[0];
                                    tempUserName = ReplaceLastOccurrence(tempUserName, "_", "@");
                                    email.ToRecipients.Add(tempUserName);
                                }
                                else
                                {
                                    email.ToRecipients.Add(userName);
                                }
                            }
                        }
                    }
                }
            }
            string adminUserName = configuration["General:AdminUserName"];
            email.From = new EmailAddress(adminUserName);
            email.Subject = matterMailSubject;
            email.Body = matterMailBody;
            email.Send();
            log.WriteLine($"connection string. {configuration["General:CloudStorageConnectionString"]}");
            Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"],
                            configuration["Settings:MatterRequests"], "Accepted", "Status");
        }
Esempio n. 22
0
 private void Envio()
 {
     ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
     service.Credentials = new WebCredentials(EmailArq, SenhaArq);
     service.TraceEnabled = true;
     service.TraceFlags = TraceFlags.All;
     service.UseDefaultCredentials = false;
     service.AutodiscoverUrl(EmailArq, RedirectionUrlValidationCallback);
     EmailMessage email = new EmailMessage(service);
     email.ToRecipients.Add(emailDestino);
     email.Subject = assunto;
     email.Body = new MessageBody(textoEmail);
     email.Send();
 }
 protected override void CreateMailThreadInTestFolder(string subject, string body, string recipients)
 {
     var message = new EmailMessage(exchangeService)
                       {
                           Subject = subject,
                           Body = body
                       };
     message.ToRecipients.Add(recipients);
     message.Send();
     MoveMessageToTestFolder(subject);
 }
 private void SendEmail(Appointment item, string subject, string body)
 {
     var msg = new EmailMessage(_exchangeService);
     msg.Subject = subject;
     msg.Body = body;
     log.DebugFormat("Address: {0}, MailboxType: {1}", item.Organizer.Address, item.Organizer.MailboxType);
     if (item.Organizer.MailboxType == MailboxType.Mailbox)
     {
         msg.ToRecipients.Add(item.Organizer);
     }
     foreach (var x in item.RequiredAttendees.Concat(item.OptionalAttendees))
     {
         log.DebugFormat("Address: {0}, MailboxType: {1}, RoutingType: {2}", x.Address, x.MailboxType, x.RoutingType);
         if (x.RoutingType == "SMTP" && x.Address.EndsWith("@rightpoint.com"))
         {
             log.DebugFormat("Also sending to {0} @ {1}", x.Name, x.Address);
             msg.CcRecipients.Add(x.Name, x.Address);
         }
     }
     msg.Send();
 }
Esempio n. 25
0
        private void SendEmail(string email)
        {
            string encryptedEmail = EncryptionUtility.Encrypt(email);
            string rootUrl = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
            string url = string.Format(rootUrl + "/Usersettings/confirmEmail?validateToken={0}", encryptedEmail);
            // Create a new Exchange service object
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            // Set user login credentials
            string ExchangeServerEmail = ConfigurationManager.AppSettings["ExchangeServerEmailID"];
            string ExchangeServerpwd = ConfigurationManager.AppSettings["ExchangeServerpwd"];
            service.Credentials = new WebCredentials(ExchangeServerEmail, ExchangeServerpwd);

            try
            {
                //Set Office 365 Exchange Webserivce Url
                string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx";
                service.Url = new Uri(serviceUrl);
                EmailMessage emailMessage = new EmailMessage(service);
                emailMessage.Subject = "Email Confirmation for daily summary updates";
                emailMessage.Body = new MessageBody("Thanks for subscribing pnp test results, please click <a href='" + url + "'> here </a> to confirm your email address ");
                emailMessage.ToRecipients.Add(email);
                emailMessage.Send();
            }
            catch (AutodiscoverRemoteException exception)
            {
                throw;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Main method - well, do something!
        /// </summary>
        internal void FetchEmailsToSendAndDispatchThemAll()
        {
            if (this.configData.LogLevel == LogLevels.VeryVerbose) {
                // Log startup entry to Event log
                System.Diagnostics.EventLog.WriteEntry(Constants.System.NtServiceName, Constants.Messages.StartingService, System.Diagnostics.EventLogEntryType.Information, (int)EventCodes.StartingService);
            }

            var nextMail = null as Mail;

            // Do for every email you fetch from the DB
            while ((nextMail = dbConnect.GetNextMailToSend()) != null) {

                // Proceed only if you have a valid To: address
                if (!string.IsNullOrEmpty(nextMail.ToAddresses)) {

                    // Display mail dispatch operation
                    if (this.configData.Debug) {
                        Console.WriteLine(string.Format(Constants.Messages.FoundEmailToDispatch, DateTime.UtcNow.ToLongTimeString(), nextMail.ToAddresses));
                    }

                    if (this.configData.LogLevel == LogLevels.VeryVerbose) {
                        // Log email address to Event log
                        System.Diagnostics.EventLog.WriteEntry(Constants.System.NtServiceName,
                            string.Format(Constants.Messages.MailDispatchStarted,
                                            nextMail.ToAddresses),
                            System.Diagnostics.EventLogEntryType.Information,
                            (int)EventCodes.StartingTask);
                    }

                    // Current Exchange installation is Exchange 2010 SP2
                    var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

                    if ((!string.IsNullOrEmpty(this.configData.SamAccountName)) &&
                        (!string.IsNullOrEmpty(this.configData.SamAccountPassword))) {
                        service.Credentials = new WebCredentials(this.configData.SamAccountName, this.configData.SamAccountPassword);
                    }

                    // Autodiscover credentials for currently configured user from AD
                    service.AutodiscoverUrl(this.configData.MailCredentials);

                    var message = new EmailMessage(service);

                    // Subject ought to be [KeyForThisApp] Whatever foo you want
                    var builder = new StringBuilder();

                    // Send direct mails with no artificial header above body of text
                    if (nextMail.Direct) {
                        message.Subject = nextMail.Subject;
                    } else {

                        if (!string.IsNullOrEmpty(nextMail.SubjectPrefix)) {
                            // Subject ought to be [KeyForThisApp] Whatever foo you want
                            builder.Append(Constants.OpenSquareBracket);
                            builder.Append(nextMail.SubjectPrefix);
                            builder.Append(Constants.CloseSquareBracketSpace);
                            builder.Append(nextMail.Subject);

                            message.Subject = builder.ToString();
                            builder.Remove(0, builder.Length);
                        } else {
                            message.Subject = nextMail.Subject;
                        }

                        // Construct metadata header for actual sender
                        builder.Append(Constants.FromField);
                        builder.Append(nextMail.From);
                        builder.Append(Constants.SentField);
                        builder.Append(nextMail.Created.GetValueOrDefault());
                        builder.Append(Constants.UtcHrField);
                    }

                    if (!string.IsNullOrEmpty(this.configData.SendAsName)) {
                        message.From = this.configData.SendAsName;
                    } else {
                        message.From = this.configData.MailCredentials;
                    }

                    // Add actual body
                    builder.Append(nextMail.Body);
                    message.Body = builder.ToString();
                    builder.Remove(0, builder.Length);

                    // Add each recipient
                    foreach (var recipient in nextMail.ToAddressList) {
                        message.ToRecipients.Add(recipient);
                    }

                    // Add cc: recipients, if any
                    if (nextMail.CcAddressList != null) {
                        foreach (var recipient in nextMail.CcAddressList) {
                            message.CcRecipients.Add(recipient);
                        }
                    }

                    // Add Bcc: recipients, if any
                    if (nextMail.BccAddressList != null) {
                        foreach (var recipient in nextMail.BccAddressList) {
                            message.BccRecipients.Add(recipient);
                        }
                    }

                    // Set mail as important if desired so
                    if (nextMail.Importance) {
                        message.Importance = Importance.High;
                    }

                    // Add each attachment
                    if (nextMail.HasAttachments.GetValueOrDefault()) {
                        foreach (var attachment in nextMail.Attachments) {
                            // Construct new Attachment object and add it to our message
                            message.Attachments.AddFileAttachment(attachment.Filename, attachment.Bytes);
                        }
                    }

                    // Send the message!
                    message.Send();

                    // Display mail dispatch operation
                    if (this.configData.Debug) {
                        Console.WriteLine(string.Format(Constants.Messages.MailDispatched, DateTime.UtcNow.ToLongTimeString()));
                    }
                } else {
                    // Log email address to Event log
                    System.Diagnostics.EventLog.WriteEntry(Constants.System.NtServiceName,
                        string.Format(Constants.Messages.NoToAddressFound,
                                        nextMail.MailId),
                        System.Diagnostics.EventLogEntryType.Warning,
                        (int)EventCodes.EmptyEmail);
                }

                // Delete this email from DB
                this.dbConnect.DeleteEmail(nextMail.MailId.GetValueOrDefault());
            }
        }
Esempio n. 27
0
        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();
        }
Esempio n. 28
0
        private static void SendMailExchange2007Plus(string subject, string body, EmailSettings settings)
        {
            ExchangeService _service;

            //Мычаем выбранную версию Exchange
            if (!string.IsNullOrEmpty(settings.MsExchangeVersion))
            {
                try
                {
                    ExchangeVersion ver;
                    ExchangeVersion.TryParse(settings.MsExchangeVersion, out ver);
                    _service = new ExchangeService(ver);
                }
                catch(Exception ex)
                {
                    Log.Write(ex.Message);
                    _service = new ExchangeService();
                }
            }
            else
            {
                _service = new ExchangeService();
            }

            if (!String.IsNullOrEmpty(settings.MsExchangeLogin))
            {
                string login = settings.MsExchangeLogin.Remove(settings.MsExchangeLogin.IndexOf('@'));

                _service.Credentials = new WebCredentials(login, settings.MsExchangePass);
            }

            _service.AutodiscoverUrl(settings.MsExchangeLogin);

            EmailMessage mail = new EmailMessage(_service);

            mail.ToRecipients.Add(settings.MailTo.ToString());

            _service.HttpHeaders.Remove("");
            //Шлем копию письма если надо
            if (!String.IsNullOrEmpty(settings.MailCopyTo))
            {
                mail.CcRecipients.Add(settings.MailCopyTo);
            }
            else
            {
                mail.CcRecipients.Clear();
            }

            mail.Subject = subject;

            //Подготавливаем тело письма так как может не отображаться если клиент не узнает эти тэги
            //body = String.Format(@"<plaintext>{0}</plaintext>", body);

            mail.Body = new MessageBody(BodyType.Text, body);

            if (settings.Save2SentFolder)
            {
                mail.SendAndSaveCopy();
            }
            else
            {
                mail.Send();
            }
        }