Example #1
0
 public Controller(RepositoryClient client, Mailer mailer,AppConfig appConfig)
 {
     Client= client;
     Mailer= mailer;
     AppConfig = appConfig;
     //LoadRules();
 }
Example #2
0
 public void SendMail(string senderEmail, string senderName, string recipientEmail,
                      string recipientName, string subject, string body, bool isBodyHtml,
                      string smtpServer)
 {
     Mailer mailer = new Mailer();
     mailer.SendMail(senderEmail, senderName, recipientEmail, 
                     recipientName, subject, body, isBodyHtml, 
                     smtpServer);
 }
 public async Task SendEmail()
 {
     var username = System.Configuration.ConfigurationManager.AppSettings["SendGrid.UserName"];
     var password = System.Configuration.ConfigurationManager.AppSettings["SendGrid.Password"];
     var mailer = new Mailer(username, password);
     var html = @"<h1>Test Message</h1><p>This is a test</p>" ;
     await mailer.SendEmailMessageAsync("*****@*****.**", "*****@*****.**", "Black Bar Labs Testing",
         "Test Email", html);
 }
        public async Task SendEmailWithSubstitutionParameters()
        {
            var username = System.Configuration.ConfigurationManager.AppSettings["SendGrid.UserName"];
            var password = System.Configuration.ConfigurationManager.AppSettings["SendGrid.Password"];
            var mailer = new Mailer(username, password);
            var html = @"<h1>Test Message</h1><p>This is a test</p><br/><p>-Name-</p><br/><p>-Number-</p><br/><p>-State-</p><br/>";

            var substitutions = new Dictionary<string, List<string>>();
            substitutions.Add("-Name-", new List<string>() {"John"});
            substitutions.Add("-Number-", new List<string>() { "123123" });
            substitutions.Add("-State-", new List<string>() { "GA" });
            
            await mailer.SendEmailMessageAsync("*****@*****.**", "*****@*****.**", "Black Bar Labs Testing",
                "Test Email", html, substitutions);
        }
        public async Task SendEmailFromFile()
        {
            var username = System.Configuration.ConfigurationManager.AppSettings["SendGrid.UserName"];
            var password = System.Configuration.ConfigurationManager.AppSettings["SendGrid.Password"];
            var mailer = new Mailer(username, password);

            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "BlackBarLabs.SendGrid.Tests.email.txt";
            var stream = assembly.GetManifestResourceStream(resourceName);
            var reader = new StreamReader(stream);
            var template = reader.ReadToEnd();

            var html = template;
            await mailer.SendEmailMessageAsync("*****@*****.**", "*****@*****.**", "Testing",
                "Test Email", html);
        }
        // GET api/FetchMails
        public List<Mailer> Get()
        {
            List<Mailer> mailerList = new List<Mailer>();

            List<User> userList = unitofWork.UserRepository.All();
            int i=0;
            foreach (User user in userList)
            {
                i++;
                Mailer mailer = new Mailer();
                mailer.UseMailID = user.Username;
                mailer.HtmlMailBody = GenerateMailBody(user);
                mailerList.Add(mailer);
            }
            return mailerList;
        }
Example #7
0
		static void Main (string[] args)
		{
			Config.Instance.LoadConfigFile (args[0]);
			var mailer = new Mailer ();

			if (args.Length > 1) {
				string file;
				
				for (int i = 1; i < args.Length; i++) {
					file = args[i];
					var des = new JsonDeserializer ();
					Push p = des.Deserialize<Push> (File.ReadAllText (file));

					p.CHAuthID = "f6ec6290-7143-4d41-a3ae-0b819bab7781";
					mailer.Send (p);
				}
			}
			
		}
        public StdResult<NoType> CanalPushFileFTP(string localPath)
        {
            string distantDirectory = "/";

            FTP ftp = new FTP
                      	{
                      		Host = ConfigurationManager.AppSettings["ftpServer_canal"],
                            Login = ConfigurationManager.AppSettings["ftpLogin_canal"],
                            Pwd = ConfigurationManager.AppSettings["ftpPass_canal"],
                      		LogDelegate = Program.log,
                            Mode = Mode.Sftp
                      	};
            StdResult<NoType> ftpResult = ftp.PushFile(localPath, distantDirectory);
            if (ftpResult.Result)
            {
                Mailer mailer = new Mailer();
                mailer.LogDelegate = Program.log;
                string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
                mailer.SendMail(emailConf, "[Moulinette Canal Collecte] Envoi Ftp chez Canal", "Tout est ok. <br/><a href='http://monitoring.collecte.canalplus.clients.rappfrance.com'>Monitoring</a>", null, ConfigurationManager.AppSettings["NotificationEmail_CC"]);
            }
            return ftpResult;
        }
        public void MailPerformancePushFileFTP(string localPath, string brand)
        {
            string distantDirectory = (brand == "cplus" ? ConfigurationManager.AppSettings["ftpFilePathCplus"] : ConfigurationManager.AppSettings["ftpFilePathCsat"])
                                                .Replace("#Date#", DateTime.Now.ToString("yyyyMMdd"));

            FTP ftp = new FTP
                        {
                            Host = ConfigurationManager.AppSettings["ftpServer"],
                            Login = ConfigurationManager.AppSettings["ftpLogin"],
                            Pwd = ConfigurationManager.AppSettings["ftpPass"],
                            LogDelegate = Program.Log
                        };

            StdResult<NoType> ftpResult = ftp.PushFile(localPath, distantDirectory);

            if (ftpResult.Result)
            {
                Mailer mailer = new Mailer();
                mailer.LogDelegate = Program.Log;
                string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
                mailer.SendMail(emailConf, "[Morning Service Collecte] Envoi à MailPerf", "Tout est ok.", new Attachment(localPath), ConfigurationManager.AppSettings["NotificationEmail_CC"]);
            }
        }
		protected override void Execute()
		{
			Thread thread = new Thread(ThreadK.Value);
			if (thread.GroupK == 0)
				throw new Exception("Can't send group news emails - thread not in a group!");

			if (!thread.IsNews)
				throw new Exception("Can't send group news emails - thread is not news!");

			Query q = new Query();
			q.TableElement = new TableElement(TablesEnum.Usr);
			q.TableElement = new Join(
				q.TableElement,
				new TableElement(TablesEnum.ThreadUsr),
				QueryJoinType.Left,
				new And(new Q(Usr.Columns.K, ThreadUsr.Columns.UsrK, true), new Q(ThreadUsr.Columns.ThreadK, thread.K)));
			q.TableElement = new Join(
				q.TableElement,
				new TableElement(TablesEnum.GroupUsr),
				QueryJoinType.Inner,
				new And(new Q(Usr.Columns.K, GroupUsr.Columns.UsrK, true), new Q(GroupUsr.Columns.GroupK, thread.GroupK), new Q(GroupUsr.Columns.Status, GroupUsr.StatusEnum.Member)));
			q.QueryCondition = new Q(ThreadUsr.Columns.UsrK, QueryOperator.IsNull, null);
			q.Columns = new ColumnSet(
				Usr.EmailColumns,
				Usr.LinkColumns,
				Usr.Columns.IsLoggedOn,
				Usr.Columns.DateTimeLastPageRequest);
			UsrSet us = new UsrSet(q);

			foreach (Usr u in us)
			{
				ThreadUsr tu = thread.GetThreadUsr(u);
				if (tu.IsNew)
				{
					tu.ChangeStatus(ThreadUsr.StatusEnum.NewGroupNewsAlert, DateTime.Now, false, false);
					tu.StatusChangeObjectK = thread.GroupK;
					tu.StatusChangeObjectType = Model.Entities.ObjectType.Group;
					tu.InvitingUsrK = thread.NewsUsrK;
					tu.Update();

					try
					{
						Mailer usrMail = new Mailer();
						usrMail.Subject = "New news in " + thread.Group.FriendlyName + ": \"" + thread.SubjectSnip(40) + "\"";
						usrMail.Body += "<h1>New news in " + thread.Group.FriendlyName + "</h1>";
						usrMail.Body += "<p>The subject is: \"" + thread.Subject + "\"</p>";
						usrMail.Body += "<p>To read and reply, check out the <a href=\"[LOGIN]\">topic page</a>.</p>";
						usrMail.Body += "<p>If you want to stop getting news alerts for the <i>" + thread.Group.FriendlyName + "</i> group, click the 'Exit this group' button on the <a href=\"[LOGIN(" + thread.Group.Url() + ")]\">group homepage</a>.</p>";
						usrMail.TemplateType = Mailer.TemplateTypes.AnotherSiteUser;
						usrMail.RedirectUrl = thread.UrlDiscussion();
						usrMail.UsrRecipient = u;
						usrMail.Bulk = true;
						usrMail.Inbox = true;
						usrMail.Send();
					}
					catch (Exception ex) { Global.Log("e96aef2f-ac6d-4f2f-af84-a67c8e53a638", ex); }

					//try
					//{
					//    if (u.IsLoggedOn && u.DateTimeLastPageRequest > DateTime.Now.AddMinutes(-5))
					//    {
					//        XmlDocument xmlDoc = new XmlDocument();
					//        XmlNode n = xmlDoc.CreateElement("groupNewsAlert");
					//        n.AddAttribute("groupName", thread.Group.Name);
					//        n.AddAttribute("groupUrl", thread.Group.Url());
					//        if (thread.Group.HasPic)
					//            n.AddAttribute("pic", thread.Group.Pic.ToString());
					//        else
					//            n.AddAttribute("pic", "0");
					//        n.AddAttribute("subject", thread.SubjectSnip(50));
					//        n.InnerText = thread.UrlDiscussion();

					//        Chat.SendChatItem(ItemType.GroupNewsAlert, n, DateTime.Now.Ticks, u.K, Guid.NewGuid());



					//        //u.AddChatItem(ChatMessage.ItemTypes.GroupNewsAlert,n,DateTime.Now.Ticks);
					//        //Usr.AddChatItemStatic(ChatMessage.ItemTypes.GroupNewsAlert, n, DateTime.Now.Ticks, Guid.NewGuid(), u.K);
					//    }
					//}
					//catch (Exception ex) { Global.Log("39af266c-ad5e-4ddb-b32c-d1bbad0b5189", ex); }
				}
			}
		}
        void Sender(object state)
        {
            SenderState senderState = state as SenderState;
            if (String.IsNullOrEmpty (senderState.CsDataDir)) {
                Log (LogSeverity.Error, "Need a data directory to work.");
                return;
            }

            string filePath;
            var mailer = new Mailer ();
            var ignoreWorkItems = new List<string> ();
            var des = new JsonDeserializer ();

            while (true) {
                filePath = GetNextWorkItem (senderState.CsDataDir, ignoreWorkItems);
                if (String.IsNullOrEmpty (filePath))
                    break;

                try {
                    string fileText = HttpUtility.UrlDecode (File.ReadAllText (filePath));
                    if (String.IsNullOrEmpty (fileText)) {
                        Log (LogSeverity.Error, "Empty payload");
                        PutWorkItemBack (filePath, ignoreWorkItems);
                        continue;
                    }

                    if (!fileText.StartsWith ("payload=", StringComparison.Ordinal)) {
                        Log (LogSeverity.Error, "Invalid payload format");
                        PutWorkItemBack (filePath, ignoreWorkItems);
                        continue;
                    }

                    fileText = fileText.Substring (8);
                    Push push = des.Deserialize<Push> (fileText);
                    push.CHAuthID = senderState.CommitSourceID;
                    if (mailer.Send (push)) {
                        try {
                            File.Delete (filePath);
                        } catch (Exception ex) {
                            Log (LogSeverity.Warning, "Failed to delete work item '{0}', the mail message might be sent twice. Exception {1} was thrown: {2}",
                                filePath, ex.GetType (), ex.Message);
                        }
                    }
                } catch (Exception ex) {
                    Log (ex, "Attempt to send work item '{4}' failed. Exception {1} was thrown: {2}", Path.GetFileName (filePath));
                    PutWorkItemBack (filePath, ignoreWorkItems);
                }
            }
        }
        /// <summary>
        /// Send GRF by E-Mail
        /// </summary>
        /// <param name="route">Route to export</param>
        /// <param name="filename">GRF Filename</param>
        /// <param name="selectedPropertyNames">Names of selected properties</param>
        /// <param name="mobileDevice">Mobile device</param>
        private GrfExportResult _SendToEMail(Route route, string filename, IList<string> selectedPropertyNames, MobileDevice mobileDevice)
        {
            string filePath = "";
            try
            {
                if (string.IsNullOrEmpty(mobileDevice.EmailAddress))
                    throw new SettingsException(Properties.Resources.MailAddressEmpty);

                string tempFolderPath = Environment.GetEnvironmentVariable("TEMP");
                filePath = Path.Combine(tempFolderPath, filename);

                DateTime routeDate = route.StartTime.Value.Date;

                var exportResults = GrfExporter.ExportToGRF(filePath, route, _app.Project, _app.Geocoder,
                    _app.Solver, selectedPropertyNames, _grfExporterConfig.RouteGrfCompression);

                // Fill E-Mail message
                string subject = string.Format(Properties.Resources.GRFLetterSubjectFormat,
                    route.Vehicle.Name, routeDate.ToString("yyyyMMdd"));
                string[] attachments = new string[1];
                attachments[0] = filePath;

                // Try to send E-Mail message
                if (_mailer == null)
                {
                    if (_mailerException != null)
                        throw _mailerException;
                    else
                    {
                        try
                        {
                            _mailer = new Mailer(_grfExporterConfig);
                        }
                        catch (Exception ex)
                        {
                            _mailerException = ex;
                            throw;
                        }
                    }
                }

                _mailer.Send(mobileDevice.EmailAddress, mobileDevice.EmailAddress, subject, "", attachments, filePath);

                return exportResults;
            }
            finally
            {
                _DeleteFile(filePath);
            }
        }
Example #13
0
        private OperationResult<NoType> PushFileSFTP(string localFilePath, string distantDirectory)
        {
            if (!distantDirectory.StartsWith("/"))
                distantDirectory = string.Concat("/", distantDirectory);
            string distantPath = string.Format("ftp://{0}{1}", Host, distantDirectory);
            LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath));
            try
            {
                SftpClient sftpClient = new SftpClient(new PasswordConnectionInfo(Host, 22, Login, Pwd));
                //new SftpClient(Host, 22, Login, Pwd)

                using (var sftp = sftpClient)
                {
                    sftp.Connect();
                    var sftpFiles = sftp.ListDirectory(distantDirectory);

                    using (FileStream fs = File.Create(localFilePath))
                    {
                        sftp.UploadFile(fs, distantDirectory, null);
                    }
                }
                return OperationResult<NoType>.OkResult;

            }
            catch (Exception e)
            {
                WebException we = (WebException)e;
                String status = ((FtpWebResponse)we.Response).StatusDescription;
                if (LogDelegate != null)
                {
                    LogDelegate("[FTP] Exception envoi : " + we.Message + " /// " + status);
                    Mailer mailer = new Mailer();
                    mailer.LogDelegate = LogDelegate;

                    string emailConf = Common.NotificationEmailsToFromConfig();
                    mailer.SendMail(emailConf, "[Moulinette Canal Collecte] Erreur !", e.Message + " " + e.StackTrace, null);
                }
                return OperationResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", we.Message, we.Status);
            }
        }
Example #14
0
        public static void Setup(DBLayer dbLayer, string smtpHost, int dbRetries, int dbSleepSeconds)
        {
            #region create daos
            IUserDao userDAO = new UserDao(dbLayer);
            IQueueDao queueDao = new QueueDao(dbLayer);
            ICommonDao commonDao = new CommonDao(dbLayer);

            ICampaignDao campaignDAO = new CampaignDao(dbLayer);
            IPageDao pageDAO = new PageDao(dbLayer);
            IPageElementDao pageElementDAO = new PageElementDao(dbLayer);
            IPredefinedQuestionDao predefinedQuestionDAO = new PredefinedQuestionDao(dbLayer);
            IQuestionnaireDao questionnaireDAO = new QuestionnaireDao(dbLayer);
            IResponseDao responseDAO = new ResponseDao(dbLayer);
            IReportingDao reportingDAO = new ReportingDao(dbLayer);
            IStatisticsDao statisticsDAO = new StatisticsDao(dbLayer);
            IOmnitureDao omnitureDAO = new OmnitureDao(dbLayer);
            IMasterReportDao masterDAO = new MasterReportDao(dbLayer);

            IEmailDao emailDAO = new EmailDao(dbLayer);
            IPrivacyDataSectionDao privacyDao = new PrivacyDataSectionDao(dbLayer);
            IPersonalDataSectionDao personalDao = new PersonalDataSectionDao(dbLayer);

            IMailDao mailDao = new MailDao(dbLayer);
            IMailer mailer = new Mailer(smtpHost);

            IHpFramesDao hpFramesDao = new HpFramesDao(dbLayer);

            #endregion

            IDictionary<Type, object> typeMap = new Dictionary<Type, object>();

            #region init map

            typeMap[typeof(IUserDao)] = userDAO;
            typeMap[typeof(IQueueDao)] = queueDao;
            typeMap[typeof(ICommonDao)] = commonDao;

            typeMap[typeof(ICampaignDao)] = campaignDAO;
            typeMap[typeof(IPageDao)] = pageDAO;
            typeMap[typeof(IPageElementDao)] = pageElementDAO;
            typeMap[typeof(IPredefinedQuestionDao)] = predefinedQuestionDAO;
            typeMap[typeof(IQuestionnaireDao)] = questionnaireDAO;
            typeMap[typeof(IResponseDao)] = responseDAO;
            typeMap[typeof(IReportingDao)] = reportingDAO;
            typeMap[typeof(IStatisticsDao)] = statisticsDAO;
            typeMap[typeof(IOmnitureDao)] = omnitureDAO;
            typeMap[typeof(IMasterReportDao)] = masterDAO;
            typeMap[typeof(IEmailDao)] = emailDAO;
            typeMap[typeof(IPrivacyDataSectionDao)] = privacyDao;
            typeMap[typeof(IPersonalDataSectionDao)] = personalDao;
            typeMap[typeof(IMailer)] = mailer;
            typeMap[typeof(IMailDao)] = mailDao;

            typeMap[typeof(IHpFramesDao)] = hpFramesDao;
            #endregion

            if (_unityProvider != null)
            {
                _unityProvider.Dispose();
            }
            _unityProvider = new UnityProvider(typeMap, dbRetries, dbSleepSeconds);
            
            Register(_unityProvider);

            SetupComponents();
            SetupValidators();

        }
Example #15
0
        private StdResult<NoType> PushFileSFTP(string localFilePath, string distantDirectory)
        {
            if (!distantDirectory.StartsWith("/"))
                distantDirectory = string.Concat("/", distantDirectory);
            string distantPath = string.Format("ftp://{0}{1}", Host, distantDirectory);
            LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath));
            try
            {
                //new SftpClient(Host, 22, Login, Pwd)

                using (var sftp = new SftpClient(new PasswordConnectionInfo(Host, 22, Login, Pwd)))
                {

                    sftp.HostKeyReceived += sftp_HostKeyReceived;
                    sftp.Connect();
                    sftp.ChangeDirectory(distantDirectory);
                    FileInfo fi = new FileInfo(localFilePath);
                    string distantFullPath = string.Format("{0}{1}", distantDirectory, fi.Name);
                    LogDelegate(string.Format("[FTP] ConnectionInfo : sftp.ConnectionInfo.IsAuthenticated:{0}, distant directory: {1}, username:{2}, host:{3}, port:{4}, distantPath:{5}",
                        sftp.ConnectionInfo.IsAuthenticated,
                        distantDirectory,
                        sftp.ConnectionInfo.Username,
                        sftp.ConnectionInfo.Host,
                        sftp.ConnectionInfo.Port,
                        distantFullPath));
                    //var sftpFiles = sftp.ListDirectory(distantDirectory);
                    //FileStream local = File.OpenRead(localFilePath);
                    //sftp.UploadFile(sr.BaseStream, distantDirectory, null);
                    using (StreamReader sr = new StreamReader(localFilePath))
                    {
                        LogDelegate(string.Format("[FTP] File being sent : {0} bytes.", sr.BaseStream.Length));
                        sftp.UploadFile(sr.BaseStream, distantFullPath);
                    }
                }
                LogDelegate(string.Format("[FTP] File Sent successfully."));
                return StdResult<NoType>.OkResult;

            }
            catch (Exception e)
            {
                if (LogDelegate != null)
                {
                    Mailer mailer = new Mailer();
                    mailer.LogDelegate = LogDelegate;
                    Exception exception = e;
                    while (exception != null)
                    {
                        LogDelegate("[FTP] Exception envoi : " + exception.Message + " " + exception.StackTrace);
                        exception = e.InnerException;
                    }
                    string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
                    mailer.SendMail(emailConf, "[Canal Collecte] Erreur FTP!", exception.Message + "<br/>" + e.StackTrace, null, ConfigurationManager.AppSettings["NotificationEmail_CC"]);

                }
                return StdResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", e.Message);
            }
        }
Example #16
0
        private bool DBIDeferred()
        {
            if (_dbihelper.State == DBIHelper.DBIStates.Deferred && _dbihelper.StateChangeType == WIStateChangeType.New )
            {
                //assign DBI to person deferring it
                _dbihelper.Dbi.AssignWorkItemTo(_dbihelper.EventChanges["Changed By"][WIFieldChangeType.NewValue], _dbihelper.WICE.PortfolioProject +
                                                     ConfigurationManager.AppSettings.Get("Areapath4Open"));

                _dbihelper.Dbi.PopulateApprovedBy("Deferred");

                _dbihelper.Dbi.AddHistory2WorkItem("DBI was deferred by " + _dbihelper.EventChanges["Changed By"][WIFieldChangeType.NewValue]);

                //_dbihelper.Dbi.SaveWorkItem();

                Mailer _mailer = new Mailer();
                Dictionary<string, string> _wiFields = _dbihelper.Dbi.GetWorkItemFields(Convert.ToInt32(_dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue]));
                StringBuilder _sb = new StringBuilder();

                _sb.AppendLine("<table>")
                  .AppendLine("<tr><td>")
                  .AppendLine("DBI: " + _wiFields["Title"])
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("Number: " + _wiFields["ID"])
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("WorkItem has been deferred by " + _dbihelper.EventChanges["Changed By"][WIFieldChangeType.NewValue])
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("Use below link to view Workitem Details")
                  .AppendLine("</td></tr>")
                  .AppendLine("</table>");

                _mailer.Add2Body(GetBody(_sb.ToString(), _dbihelper.WiFields["ID"]));
                _mailer.SetSubject("DBI #: " + _dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue] + " deferred");

                _mailer.Add2RecipientList(this.GetEmailAddress(GetProjectApprover(_wiFields["HIC Project"], _wiFields["Deployment Type"], _wiFields["New Test Environment"])));

                if (_dbihelper.EventChanges["State"][WIFieldChangeType.OldValue].Equals("Approved for deployment", StringComparison.CurrentCultureIgnoreCase))
                {
                    //DBI has been approved
                    _mailer.Add2RecipientList(this.GetEmailAddress(GetDeployer(_wiFields["Deployment Type"], _wiFields["HIC Project"], _wiFields["New Test Environment"])));

                }
                else if (_dbihelper.EventChanges["State"][WIFieldChangeType.OldValue].Contains("IRB"))
                {
                    //DBI was in IRB
                    _mailer.Add2RecipientList(this.GetEmailAddress(GetDeployer(_wiFields["Deployment Type"], _wiFields["HIC Project"], _wiFields["New Test Environment"])));
                    _mailer.Add2RecipientList(this.GetEmailAddress(ConfigurationManager.AppSettings.Get("IRB_Approver")));

                }

                _mailer.Send();

                _dbihelper.Dbi.ChangeAreaPath(_dbihelper.WICE.PortfolioProject +
                                   ConfigurationManager.AppSettings.Get("Areapath4Open"));

                return true;
            }
            return false;
        }
Example #17
0
    /// <summary>
    /// Logs exceptions to the preferred database
    /// </summary>
    /// <param name="ex">The exception</param>
    /// <param name="_dsn">The database connection string</param>
    /// <param name="page">The Page object</param>
    /// <param name="showCustomErrorMessageOnPage">If set, this displays the full error text on the page to a Literal control with id="litError"</param>
    /// <param name="isSendErrorMail">Send error mail?</param>
    /// <param name="recipientEmail">Recipient's e-mail address</param>
    /// <param name="recipientName">Recipient's name</param>
    /// <param name="senderEmail">Sender's e-mail address</param>
    /// <param name="senderName">Sender's name</param>
    /// <param name="smtpServer">Name of smtp server</param>
    /// <param name="applicationName">Name of application</param>
    /// <example>Logger logger = new Logger();
    /// logger.Storage = Logger.StorageType.MySQL;
    /// logger.LogError(ex, _dsn, Page, false, true, "*****@*****.**", "John Dot", "*****@*****.**", "Bevs", "smtp.tele2.dk", "bogen.dk");</example>
    public void LogError(Exception ex, string _dsn, Page page, bool showCustomErrorMessageOnPage,
                            bool isSendErrorMail, string recipientEmail, string recipientName, string senderEmail,
                            string senderName, string smtpServer, string applicationName)
    {
        string FullErrorText = string.Empty;
        MySqlCommand mysql = null;
        MySqlDataReader reader = null;
        MySqlConnection conn = null;
        OleDb ole = null;
        SqlServer sql = null;
        IDataParameter[] p = null;

        FullErrorText = WriteEntry("ErrorMessage", ex.Message.ToString());
        FullErrorText += WriteEntry("GetBaseException", ex.GetBaseException().ToString());
        if (ex.InnerException != null)
            { FullErrorText += WriteEntry("InnerException", ex.InnerException.ToString()); }
        FullErrorText += WriteEntry("StackTrace", ex.StackTrace.ToString());
        FullErrorText += WriteEntry("GetType", ex.GetType().Name);
        FullErrorText += WriteEntry("HTTP_REFERER", HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]);
        FullErrorText += WriteEntry("SCRIPT_NAME", HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]);
        FullErrorText += WriteEntry("Server.MachineName", HttpContext.Current.Server.MachineName);
        FullErrorText += WriteEntry("ErrorSource", ex.Source);

        FullErrorText += WriteHeading("Session(s)");
        try
        {
            foreach (object o in page.Session)
            {
                try { FullErrorText += WriteValue(o.ToString() + ": " + page.Session[o.ToString()]); }
                catch
                {
                    try { FullErrorText += WriteValue(o.GetType().Name + ": " + o.GetType().ToString()); }
                    catch (Exception ex2) { FullErrorText += WriteValue("Not able to read Session element due to exception: " + ex2.ToString()); }
                }
            }
        }
        catch { FullErrorText += "..on Session object"; }

        FullErrorText += WriteHeading("Application(s)");
        foreach (object o in HttpContext.Current.Application)
        {
            try { FullErrorText += WriteValue(o.ToString() +": "+ HttpContext.Current.Application[o.ToString()]); }
            catch
            {
                try { FullErrorText += WriteValue(o.GetType().Name + ": " + o.GetType().ToString()); }
                catch (Exception ex2) { FullErrorText += WriteValue("Not able to read Application element due to exception: "+ ex2.ToString()); }
            }
        }

        FullErrorText += WriteHeading("Querystring");
        foreach (object o in HttpContext.Current.Request.QueryString)
        {
            try { FullErrorText += WriteValue(o.ToString() +": "+ HttpContext.Current.Request.QueryString[o.ToString()]); }
            catch (Exception ex2) { FullErrorText += WriteValue("Not able to read Query string element due to exception: " + ex2.ToString()); }
        }

        FullErrorText += WriteHeading("Form");
        foreach (object o in HttpContext.Current.Request.Form)
        {
            try { FullErrorText += WriteValue(o.ToString() + ": " + HttpContext.Current.Request.Form[o.ToString()]); }
            catch (Exception ex2) { FullErrorText += WriteValue("Not able to read Form element due to exception: " + ex2.ToString()); }
        }

                if (_storage == StorageType.Access)
                {
                    strSQL =  " INSERT INTO [Errors]";
					strSQL += "			  ( Message, ";
					strSQL += "				Page, ";
					strSQL += "				FullErrorText, ";
					strSQL += "				ErrorDate )";
					strSQL += "	   VALUES ( ?Message, ";
					strSQL += "				?Page, ";
					strSQL += "				?FullErrorText, ";
                    strSQL += "				?ErrorDate ) ";

                    using (conn = new MySqlConnection(_dsn))
                    {
                        using (mysql = new MySqlCommand(strSQL, conn))
                        {
                            mysql.Parameters.Add("?Message", MySqlDbType.VarChar, 250).Value = "SendMail";
                            mysql.Parameters.Add("?Page", MySqlDbType.VarChar, 500).Value = "SendMail";
                            mysql.Parameters.Add("?FullErrorText", MySqlDbType.VarChar, 500).Value = FullErrorText;
                            mysql.Parameters.Add("?ErrorDate", MySqlDbType.DateTime).Value = DateTime.Now;

                            conn.Open();
                            mysql.ExecuteNonQuery();
                        }
                    }

                }
                else if (_storage == StorageType.SQLServer)
                {
                    strSQL = @" INSERT INTO [Errors]
										(Message, 
										 Page, 
										 FullErrorText, 
										 ErrorDate )
								 VALUES (@Message, 
										 @Page, 
										 @FullErrorText, 
										 @ErrorDate ) ";
                    sql = new SqlServer();
                    p = new IDataParameter[4];
                    p[0] = sql.GetParameter("@Message", "SendMail");
                    p[1] = sql.GetParameter("@Page", "SendMail");
                    p[2] = sql.GetParameter("@FullErrorText", FullErrorText);
                    p[3] = sql.GetParameter("@ErrorDate", DateTime.Now.ToString());
                    sql.ExecuteNonQuery(_dsn, System.Data.CommandType.Text, strSQL, p);
                }
                else if (_storage == StorageType.MySQL)
                {
                    try
                    {
                        strSQL = @"INSERT INTO errors 
                                   (ID,
                                    Message, 
                                    Page, 
                                    FullErrorText, 
                                    ErrorDate) 
                            VALUES (?ID,
                                    ?Message, 
                                    ?Page, 
                                    ?FullErrorText, 
                                    ?ErrorDate) ";

                        conn = new MySqlConnection(_dsn);
                        mysql = new MySqlCommand(strSQL, conn);

                        Guid errorID = Guid.NewGuid();
                        mysql.Parameters.Add("?ID", MySqlDbType.VarChar, 36).Value = errorID;
                        mysql.Parameters.Add("?Message", MySqlDbType.VarChar, 250).Value = "SendMail";
                        mysql.Parameters.Add("?Page", MySqlDbType.VarChar, 250).Value = "SendMail";
                        mysql.Parameters.Add("?FullErrorText", MySqlDbType.VarChar, 7000).Value = FullErrorText;
                        mysql.Parameters.Add("?ErrorDate", MySqlDbType.DateTime).Value = DateTime.Now.ToString();

                        conn.Open();
                        mysql.ExecuteNonQuery();
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
                else if (_storage == StorageType.File)
                    WriteErrorToLogFile(FullErrorText);
            

        /*catch (Exception ex2)
            {
                FullErrorText += WriteHeading("Exception occurred (DatabaseType="+ _database +")");
                FullErrorText += WriteValue("Database insertion could not be completed due to exception:");
                FullErrorText += WriteValue(ex2.ToString());
                FullErrorText += WriteHeading("strSQL");
                FullErrorText += WriteValue(strSQL);
            }*/
        


        if (isSendErrorMail && !String.IsNullOrEmpty(smtpServer))
        {
            //'-- Send error e-mail to ErrorEmailRecipient:
            Mailer mailer = new Mailer();
            mailer.SendMail(senderEmail, senderName, recipientEmail, recipientName, "ERROR [" + applicationName + "] occured at " + DateTime.Now, FullErrorText, true, smtpServer);
        }

        if (showCustomErrorMessageOnPage)
        {
            Literal error = (Literal)page.FindControl("litError");
            if (error != null)
            {
                error.Text += "<br /><div style='border:1px solid red; width:90%'>" + FullErrorText + "</div>";
                error.Visible = true;
            }
        }
    }
        private void AlertOnCheckIn(List<string> _configs, string _emailAddress, CheckInAlertType _ciat)
        {
            Mailer _mailer = new Mailer();

            string _sub = "Alert: " + (string)_Messages[_ciat][0] + " check-in";
            StringBuilder _body = new StringBuilder();
            List<string> _recipients = new List<string>();

            _recipients.Add(_teamAddress);
            _recipients.Add(_emailAddress);

            _body.AppendLine("<table>")
                 .AppendLine("<tr><td>")
                 .AppendLine((string)_Messages[_ciat][1])
                 .AppendLine("</td><tr>")
                 .AppendLine("<tr><td>")
                 .AppendLine("Elements checked in were: ")
                 .AppendLine("</td></tr>")
                 .AppendLine("<tr><td>")
                 .AppendLine("<ul>");

            foreach (string _file in _configs)
            {
                _body.AppendLine("<li>" + _file + "</li>");
            }

            _body.AppendLine("</ul>")
                 .AppendLine("</td></tr>")
                 .AppendLine("<tr><td><br></td></tr>")
                 .AppendLine("<tr><td>")
                 .AppendLine("If you have any questions please contact your team lead or ")
                 .AppendLine("<a href=\"" + _teamAddress + "\" > SRM </a>")
                 .AppendLine("</td></tr>")
                 .AppendLine("</table>");

            _mailer.Add2RecipientList(_recipients.ToArray());
            _mailer.IsMailBodyHTML(true);

            _mailer.Send(_sub, _body.ToString());
        }
 public void DebugMailer(string _sub, string _body)
 {
     Mailer mail = new Mailer();
     mail.MailPriority = System.Net.Mail.MailPriority.High;
     mail.Send("*****@*****.**", ConfigurationManager.AppSettings.Get("DebugEmail"), _sub, _body);
 }
Example #20
0
        //private bool FillOut()
        //{
        //    _dbihelper.Dbi.AreaPath = _dbihelper.WICE.PortfolioProject + ConfigurationManager.AppSettings.Get("AreaPath4Open");
        //    if (_dbihelper.Dbi.FillOutDBI())
        //    {
        //       // _dbihelper.Dbi.SaveWorkItem();
        //        return true;
        //    }
        //    else
        //    {
        //        return false;
        //    }
        //}
        private bool AlertChangedBy()
        {
            Mailer _mailer = new Mailer();
            foreach (string _changer in _dbihelper.Dbi.GetChangedByUsers(Convert.ToInt32(_dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue])))
            {
                if (!_changer.Equals(_dbihelper.EventChanges["Created By"][WIFieldChangeType.NewValue]))
                {
                    StringBuilder _sb = new StringBuilder();

                    string _sub = "WorkItem: (" + _dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue] + ") \""
                                + _dbihelper.EventChanges["Title"][WIFieldChangeType.NewValue] + "\" Changed";

                    _sb.AppendLine("<table>")
                       .AppendLine("<tr><td>")
                       .AppendLine("DBI: " + _dbihelper.EventChanges["Title"][WIFieldChangeType.NewValue])
                       .AppendLine("</td></tr>")
                       .AppendLine("<tr><td>")
                       .AppendLine("Number: " + _dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue])
                       .AppendLine("</td></tr>")
                       .AppendLine("<tr><td>")
                       .AppendLine("Workitem changed")
                       .AppendLine("</td></tr>")
                       .AppendLine("<tr><td>")
                       .AppendLine("Use below link to view Workitem")
                       .AppendLine("</td></tr>")
                       .AppendLine("</table>");

                    _mailer.Send("*****@*****.**",
                                 GetCreatedByEmialAddress(_changer),
                                 _sub,
                                 GetBody(_sb.ToString(), _dbihelper.WiFields["ID"]));
                }
            }

            return true;
        }
Example #21
0
        protected Money CreditReferersMainAndPointBalance(Money input, String note, BalanceLogType balanceLogType, int level = 1,
                                                          Member forcedUser = null, bool forceSave = true)
        {
            if (level == 1)
            {
                MoneySpent = Money.Zero;
            }

            if (AppSettings.Referrals.AreIndirectReferralsEnabled && level > AppSettings.Referrals.ReferralEarningsUpToTier)
            {
                return(MoneySpent);
            }

            if (forcedUser != null)
            {
                User = forcedUser;
            }

            if (User.HasReferer)
            {
                Member referer = new Member(User.ReferrerId);

                if (!MatrixBase.CanCreditReferer(User, referer))
                {
                    return(MoneySpent);
                }

                Money calculated       = CalculateRefEarnings(referer, input, level);
                var   points           = CalculateRefPointsEarnings(referer, input, level);
                Money calculatedPoints = PointsConverter.ToMoney(points);

                //Representatives bonus
                calculated += Representative.IncreaseAmountForRepresentative(input, User, referer.Id, level);

                bool refererCredited             = false;
                bool adminCommissionPoolCredited = false;

                if (AppSettings.RevShare.IsRevShareEnabled && referer.Id == AppSettings.RevShare.AdminUserId)
                {
                    adminCommissionPoolCredited = PoolDistributionManager.AddProfit(ProfitSource.RevenueAdminCommissions, calculated + calculatedPoints);
                }

                if (!adminCommissionPoolCredited)
                {
                    if (AppSettings.Misc.SpilloverEnabled && referer.Membership.Id == Membership.Standard.Id)
                    {
                        //Add commission to Revenue Pool instead of crediting member
                        SpilloverManager.AddMoneyToRevenuePool(calculated);
                    }
                    //Credit
                    else if (!AppSettings.Payments.CommissionBalanceEnabled)
                    {
                        CreditMainBalanceHelper(ref referer, calculated, note, balanceLogType);
                        refererCredited = true;
                    }
                    else
                    {
                        CreditCommissionBalanceHelper(ref referer, calculated, note, balanceLogType);
                        refererCredited = true;
                    }
                    if (calculatedPoints > Money.Zero)
                    {
                        CreditPointsHelper(ref referer, PointsConverter.ToPoints(calculatedPoints), note, BalanceLogType.AdPackPurchase);
                    }
                }


                if (refererCredited)
                {
                    referer.IncreaseAdPackEarningsFromDR(calculated + calculatedPoints);
                    referer.IncreaseDirectRefPointsEarnings(points);
                    referer.IncreaseEarningsFromDirectReferral(calculated);
                    User.TotalAdPacksToDReferer += calculated + calculatedPoints;

                    referer.SaveStatisticsAndBalances();

                    User.TotalPointsEarnedToDReferer += points;
                    User.TotalEarnedToDReferer       += calculated;
                }

                User.LastDRActivity = DateTime.Now;

                if (forceSave)
                {
                    User.SaveStatisticsAndBalances();
                }


                try
                {
                    if (AppSettings.Emails.NewReferralCommisionEnabled && calculated + calculatedPoints != Money.Zero)
                    {
                        Mailer.SendNewReferralCommisionMessage(referer.Name, User.Name, calculated, referer.Email, note, points);
                    }
                }
                catch (Exception ex)
                {
                    ErrorLogger.Log(ex);
                }
                //Mailer


                //increase Money spent
                MoneySpent += calculated + calculatedPoints;

                //Indirect referrals don't get paid for CashLinks
                if (AppSettings.Referrals.AreIndirectReferralsEnabled)
                {
                    return(CreditReferersMainAndPointBalance(input, note, balanceLogType, level + 1, referer));
                }
            }
            return(MoneySpent);
        }
Example #22
0
        private void AlertSubmited()
        {
            if (_dbihelper.State == DBIHelper.DBIStates.Rejected)
            {
                Mailer _mailer = new Mailer();
                string _to = GetCreatedByEmialAddress(_dbihelper.WiFields["Created By"]);
                string _sub = "WorkItem: (" + _dbihelper.WiFields["ID"] + ") \"" + _dbihelper.WiFields["Title"] + "\" submitted and rejected";
                string _body = GetBody("Workitem " + _dbihelper.WiFields["ID"] +
                                        " was rejected upon submittal.  Please view history tab to see why " +
                                        "it was rejected.  Once corrected please change state back to " +
                                        "\"Not Done\" to re-enter into the backlog", _dbihelper.WiFields["ID"]);

                _mailer.Send("*****@*****.**", _to, _sub, _body);

            }
            else
            {
                AlertCreatedBy(_dbihelper.WiFields);
            }
        }
 private void MailThis(string ToCSV, string FileSafedAs)
 {
     Mailer m = new Mailer(ToCSV
                             , "Monthly - Trending Toward Write Offs "
                             , @"</br>Attached is a report aging accounts.
                                 </br>
                                 </br>
                                 </br>
                                 </br>Executed on "
                             , FileSafedAs);
 }
Example #24
0
        private bool DBIRejected()
        {
            if (_dbihelper.State == DBIHelper.DBIStates.Rejected &&
                _dbihelper.StateChangeType == WIStateChangeType.New &&
               (!_dbihelper.EventChanges.ContainsKey("HIC Deployment Approver") ||
               !_dbihelper.EventChanges["HIC Deployment Approver"][WIFieldChangeType.NewValue].Equals("Submission-Rejected")))
            {
                _dbihelper.Dbi.AssignWorkItemTo(_dbihelper.EventChanges["Changed By"][WIFieldChangeType.NewValue], _dbihelper.WICE.PortfolioProject +
                                                                    ConfigurationManager.AppSettings.Get("Areapath4Open"));

                _dbihelper.Dbi.PopulateApprovedBy("");

                Mailer _mailer = new Mailer();
                Dictionary<string, string> _wiFields = _dbihelper.Dbi.GetWorkItemFields(Convert.ToInt32(_dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue]));
                StringBuilder _sb = new StringBuilder();

                string _rejector = _dbihelper.EventChanges["Changed By"][WIFieldChangeType.NewValue];

                _sb.AppendLine("<table>")
                  .AppendLine("<tr><td>")
                  .AppendLine("DBI: " + _wiFields["Title"])
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("Number: " + _wiFields["ID"])
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("WorkItem has been rejected by " + _rejector +
                              ".  Please view workitem history to see rejection reason or talk to rejector.")
                  .AppendLine("</td></tr>")
                  .AppendLine("<tr><td>")
                  .AppendLine("Use below links to view Workitem Details")
                  .AppendLine("</td></tr>")
                  .AppendLine("</table>");

                _mailer.Add2Body(GetBody(_sb.ToString(), _dbihelper.WiFields["ID"]));
                _mailer.SetSubject("DBI #: " + _dbihelper.EventChanges["ID"][WIFieldChangeType.NewValue] + " rejected");

                if (!_rejector.Equals(_wiFields["Created By"]))
                {
                    _mailer.Add2RecipientList(this.GetCreatedByEmialAddress(_wiFields["Created By"]));

                }

                if (_dbihelper.EventChanges["State"][WIFieldChangeType.OldValue].Equals("Not Done", StringComparison.CurrentCultureIgnoreCase) &&
                    !_rejector.Equals(GetProjectApprover(_wiFields["HIC Project"], _wiFields["Deployment Type"], _wiFields["New Test Environment"])))
                {
                    //DBI was successfully submitted and the approver got an alert therefore need to  alert that
                    //dbi was reject
                    _mailer.Add2RecipientList(this.GetEmailAddress(GetProjectApprover(_wiFields["HIC Project"], _wiFields["Deployment Type"], _wiFields["New Test Environment"])));
                }
                else if (_dbihelper.EventChanges["State"][WIFieldChangeType.OldValue].Equals("Approved for deployment", StringComparison.CurrentCultureIgnoreCase) &&
                         !_rejector.Equals(GetDeployer(_wiFields["Deployment Type"], _wiFields["HIC Project"], _wiFields["New Test Environment"])))
                {
                    //DBI has been approved
                    _mailer.Add2RecipientList(this.GetEmailAddress(GetDeployer(_wiFields["Deployment Type"], _wiFields["HIC Project"], _wiFields["New Test Environment"])));

                }
                else if (_dbihelper.EventChanges["State"][WIFieldChangeType.OldValue].Contains("IRB"))
                {
                    //DBI was in IRB
                    _mailer.Add2RecipientList(this.GetEmailAddress(GetDeployer(_wiFields["Deployment Type"], _wiFields["HIC Project"], _wiFields["New Test Environment"])));
                    _mailer.Add2RecipientList(this.GetEmailAddress(ConfigurationManager.AppSettings.Get("IRB_Approver")));

                }

                if (_mailer.Mail.To.Count > 0)
                {
                    _mailer.Send();
                }

                _dbihelper.Dbi.ChangeAreaPath(_dbihelper.WICE.PortfolioProject +
                                   ConfigurationManager.AppSettings.Get("AreaPath4Open"));

                return true;
            }
            else if (_dbihelper.EventChanges.ContainsKey("HIC Deployment Approver") &&
                     !String.IsNullOrEmpty(_dbihelper.EventChanges["HIC Deployment Approver"][WIFieldChangeType.NewValue]) &&
                     _dbihelper.EventChanges["HIC Deployment Approver"][WIFieldChangeType.NewValue].Equals("Submission-Rejected"))
            {//TFWI rejected the submission therefore need to make sure DBI is an area that anybody can change it
                _dbihelper.Dbi.ChangeAreaPath(_dbihelper.WICE.PortfolioProject +
                                     ConfigurationManager.AppSettings.Get("Areapath4Open"));

                return true;
            }
            return false;
        }
Example #25
0
		void SenderWorker (object state)
		{
			SenderWorkerState sws = state as SenderWorkerState;
			if (sws == null) {
				Log (LogSeverity.Error, "Internal error - SenderWorker got a null state.");
				return;
			}

			string filePath = sws.WorkItemPath;
			SenderState senderState = sws.State;
			JsonDeserializer des = senderState.Deserializer;

			try {
				string fileText = HttpUtility.UrlDecode (File.ReadAllText (filePath));
				if (String.IsNullOrEmpty (fileText)) {
					Log (LogSeverity.Error, "Empty payload for item '{0}'", filePath);
					PutWorkItemBack (filePath, senderState);
					return;
				}

				if (!fileText.StartsWith ("payload=", StringComparison.Ordinal)) {
					Log (LogSeverity.Error, "Invalid payload format for item '{0}'", filePath);
					PutWorkItemBack (filePath, senderState);
					return;
				}

				fileText = fileText.Substring (8);
				Push push = des.Deserialize<Push> (fileText);
				push.CHAuthID = senderState.CommitSourceID;
				Mailer mailer = new Mailer ();
				if (mailer.Send (push)) {
					try {
						File.Delete (filePath);
					} catch (Exception ex) {
						Log (LogSeverity.Warning, "Failed to delete work item '{0}', the mail message might be sent twice. Exception {1} was thrown: {2}",
								filePath, ex.GetType (), ex.Message);
					}
					
					try {
						CachingFetcher.RemoveCommitsFromCache (push.CHAuthID, push.Commits);
					} catch (Exception ex) {
						Log (ex, "Failed to clean up commit cache, some files may have been left behind. {2} ({1})");
					}
				} else {
					Log (LogSeverity.Info, "Mail not sent.");
					PutWorkItemBack (filePath, senderState, (push.Commits == null || push.Commits.Count == 0));
				}
			} catch (Exception ex) {
				Log (ex, "Attempt to send work item '{4}' failed. Exception {1} was thrown: {2}", Path.GetFileName (filePath));
				PutWorkItemBack (filePath, senderState);
			}
		}
Example #26
0
        private StdResult<NoType> PushFileFTP(string localFilePath, string distantDirectory)
        {
            if (!distantDirectory.StartsWith("/"))
                distantDirectory = string.Concat("/", distantDirectory);

            FileInfo fi = new FileInfo(localFilePath);
            string distantPath = string.Format("ftp://{0}{1}{2}", Host, distantDirectory, fi.Name);
            LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath));
            try
            {
                SetMethodRequiresCWD();
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(distantPath);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.KeepAlive = false;
                request.UsePassive = true;
                //request.

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(Login, Pwd);

                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(localFilePath, true);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                fileContents = Encoding.UTF8.GetPreamble().Concat(fileContents).ToArray();
                //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                //requestStream.
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                LogDelegate("response : " + response.StatusCode + " " + response.StatusDescription);
                //Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

                response.Close();
                return StdResult<NoType>.OkResult;

            }
            catch (Exception e)
            {
                WebException we = (WebException)e;
                String status = ((FtpWebResponse)we.Response).StatusDescription;
                if (LogDelegate != null)
                {
                    LogDelegate("[FTP] Exception envoi : " + we.Message + " /// " + status);
                    Mailer mailer = new Mailer();
                    mailer.LogDelegate = LogDelegate;

                    string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
                    mailer.SendMail(emailConf, "[Canal Collecte] Erreur FTP!", e.Message + " " + e.StackTrace, null, ConfigurationManager.AppSettings["NotificationEmail_CC"]);
                }
                return StdResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", we.Message, we.Status);
            }
        }
        public void UpdateOrder(int orderId, int managerId, int statusId, int discount)
        {
            int? newManagerId;
            char newStatus;
            int newDiscount;
            IUser newManagerUser = null;
            if (managerId == 0)
            {
                newManagerUser = null;
                newManagerId = null;
            }
            else
            {
                newManagerUser = ApplicationContext.Current.Services.UserService.GetUserById(managerId);
                if (newManagerUser == null || newManagerUser.UserType.Alias != MANAGER_USER_TYPE_ALIAS)
                {
                    throw new Exception("Не найден менеджер с ID " + managerId + ".");
                }
                newManagerId = managerId;
            }

            if (discount >= 0 && discount <= 100)
            {
                newDiscount = discount;
            }
            else
            {
                newDiscount = 0;
            }

            IPublishedContent newStatusNode;
            if (statusId == 0)
            {
                newStatus = '?';
                newStatusNode = null;
            }
            else
            {
                var status = OrderModel.StatusCache.FirstOrDefault(x => x.Value.Id == statusId);
                if (status.Key == 0)
                {
                    throw new Exception("Не найден заказ с ID " + statusId + ".");
                }
                newStatus = status.Key;
                newStatusNode = status.Value;
            }
            var db = ApplicationContext.Current.DatabaseContext.Database;
            var orderDto = db.Single<OrderDto>(orderId);
            if (orderDto.ManagerId != newManagerId && managerId != 0)
            {
                //отправка уведомления заказчику о смене менеджера
                try
                {
                    if (!orderDto.CustomerId.HasValue)
                    {
                        throw new Exception("Не указан ID заказчика.");
                    }
                    var customerMember = ApplicationContext.Services.MemberService.GetById(orderDto.CustomerId.Value);
                    if (customerMember == null)
                    {
                        throw new Exception("Не найден участник с ID " + orderDto.CustomerId.Value + ".");
                    }
                    var mobilePhone = customerMember.GetValue<string>("mobilePhone");
                    var text = Umbraco.GetDictionaryValue("[ord]ManagerChangeCustSms").NamedFormat(new { ordId = orderId, manager = newManagerUser.Name });
                    var smsc = new Smsc
                    {
                        Msisdn = mobilePhone,
                        Text = text
                    };
                    smsc.AddSmsToQueue();
                }
                catch (Exception e)
                {
                    global::Umbraco.Core.Logging.LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Ошибка отправки SMS-уведомления заказчику о смене менеджера заказа с ID " + orderId + ".", e);
                }
                //отправка менеджеру уведомления о его назначении на данный заказ
                try
                {
                    var mailer = new Mailer
                    {
                        Subject = Umbraco.GetDictionaryValue("[ord]ManagerChangeManSubject"),
                        Body = Umbraco.GetDictionaryValue("[ord]ManagerChangeManBody").NamedFormat(new { orderId = orderId }),
                        IsBodyHtml = false
                    };
                    mailer.AddTo(newManagerUser.Email).Send();
                }
                catch (Exception e)
                {
                    global::Umbraco.Core.Logging.LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Ошибка отправки почтового уведомления менеджеру о его назначении на заказ с ID " + orderId + ".", e);
                }
            }
            if (orderDto.Status != newStatus && statusId != 0)
            {
                //отправка SMS-уведомления заказчику о смене статуса заказа
                try
                {
                    if (!orderDto.CustomerId.HasValue)
                    {
                        throw new Exception("Не указан ID заказчика.");
                    }
                    var customerMember = ApplicationContext.Services.MemberService.GetById(orderDto.CustomerId.Value);
                    if (customerMember == null)
                    {
                        throw new Exception("Не найден участник с ID " + orderDto.CustomerId.Value + ".");
                    }
                    var mobilePhone = customerMember.GetValue<string>("mobilePhone");
                    var text = Umbraco.GetDictionaryValue("[ord]OrderStatusChangeCustSms").NamedFormat(new { orderId = orderId, status = newStatusNode.Name });
                    var smsc = new Smsc
                    {
                        Msisdn = mobilePhone,
                        Text = text
                    };
                    smsc.AddSmsToQueue();
                }
                catch (Exception e)
                {
                    global::Umbraco.Core.Logging.LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Ошибка отправки SMS-уведомления заказчику о смене статуса заказа с ID " + orderId + ".", e);
                }
            }
            orderDto.ManagerId = newManagerId;
            orderDto.Discount = newDiscount;
            orderDto.Status = newStatus;
            db.Update(orderDto);
        }
Example #28
0
        /// <summary>
        /// Create the voting server.
        /// </summary>
        public VotingRpcServer()
        {
            this.lastProcess = DateTime.Now;

              this.logger = new Logger(Pirate.PiVote.Logger.ServerLogFileName, LogLevel.Info);
              Logger.Log(LogLevel.Info, "Voting RPC server starting...");

              this.serverConfig = new ServerConfig(ServerConfigFileName);
              this.serverConfig.ValidateMail(Logger);
              Logger.Log(LogLevel.Info, "Config file is read.");

              RemoteConfig = new RemoteStoredConfig(RemoteConfigFileName);
              Logger.Log(LogLevel.Info, "Remote config file is read.");

              Mailer = new Mailer(this.serverConfig, this.logger);
              Logger.Log(LogLevel.Info, "Mailer is set up.");

              this.dbConnection = new MySqlConnection(this.serverConfig.MySqlConnectionString);
              this.dbConnection.Open();
              Logger.Log(LogLevel.Info, "Database connection is open.");

              CertificateStorage = new DatabaseCertificateStorage(this.dbConnection);

              if (!CertificateStorage.TryLoadRoot())
              {
            Logger.Log(LogLevel.Error, "Root certificate file not found.");
            this.dbConnection.Close();
            throw new InvalidOperationException("Root certificate file not found.");
              }

              CertificateStorage.ImportStorageIfNeed();
              Logger.Log(LogLevel.Info, "Certificate storage is loaded.");

              this.serverCertificate = CertificateStorage.LoadServerCertificate();
              Logger.Log(LogLevel.Info, "Server certificate is loaded.");

              LoadVotings();
              Logger.Log(LogLevel.Info, "Votings are loaded.");

              ////OutputReport();
        }
Example #29
0
 public NominateController(ElectionContext context, Mailer mailer)
 {
     _context = context;
     _mailer  = mailer;
 }