Beispiel #1
0
        public async Task <ActionResult> SupprimerEven(Evenements evenement)
        {
            var idUSer = GetIdUtilisateurConnecte();

            //Controle que l'évènement appartiennent à la personne qui le supprime
            if (Db.Evenements.Count(x => x.Id == evenement.Id && x.CreateurId == idUSer) > 0)
            {
                //préparation du mail
                var mail         = Db.Mails.First(x => x.NomUnique == ContexteStatic.EnvoiDesactivationEvenement);
                var corpsMessage = StringUtils.CopyString(mail.Corps);
                corpsMessage = corpsMessage.Replace("%NOMEVEN%", evenement.Titre);

                //suppression des liens évènements et utilisateur
                var listeEvenUser = Db.EvenementsUtilisateurs.Where(x => x.EvenementsId == evenement.Id).Include(x => x.Utilisateurs).ToList();
                foreach (var evenementsUtilisateurs in listeEvenUser)
                {
                    await MailUtils.SendMail(evenementsUtilisateurs.Utilisateurs.Email, mail.Objet, corpsMessage);

                    Db.EvenementsUtilisateurs.Remove(evenementsUtilisateurs);
                }

                var ev = Db.Evenements.Find(evenement.Id);
                //supression de l'évènement
                Db.Evenements.Remove(ev);
                Db.SaveChanges();

                return(RedirectToAction("MesEvenements"));
            }
            return(View(evenement));
        }
Beispiel #2
0
        public async Task SendContactMessage(Guid chapterId, string fromAddress, string message)
        {
            if (string.IsNullOrWhiteSpace(fromAddress) || string.IsNullOrWhiteSpace(message))
            {
                throw new OdkServiceException("Email address and message must be provided");
            }

            if (!MailUtils.ValidEmailAddress(fromAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }

            VersionedServiceResult <Chapter> chapter = await GetChapter(null, chapterId);

            ContactRequest contactRequest = new ContactRequest(Guid.Empty, chapter.Value.Id, DateTime.UtcNow, fromAddress, message, false);
            await _chapterRepository.AddContactRequest(contactRequest);

            IDictionary <string, string> parameters = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "from", fromAddress },
                { "message", HttpUtility.HtmlEncode(message) }
            };

            await _emailService.SendContactEmail(chapter.Value, fromAddress, message, parameters);
        }
Beispiel #3
0
        public virtual MailLogDTO SendMail(Domain.Entity.Client currentClient, MailModel entity, object param)
        {
            List <string>   recipients = new List <string>();
            List <Document> documents  = new List <Document>();
            MailLog         mailLog;

            ValidateNull(entity);
            if (!validation.PreValidatePost(validationDictionnary, currentClient, entity, param, repo, recipients, documents))
            {
                throw new ManahostValidationException(validationDictionnary);
            }
            IHomeRepository homeRepo   = ((MailController.AdditionalRepositories)param).HomeRepo;
            MailConfig      mailconfig = repo.GetMailConfigById(entity.MailConfigId, currentClient.Id);

            Mailling.SendMailBcc(new InfosMailling(mailconfig.Smtp, (int)mailconfig.SmtpPort, mailconfig.Email, homeRepo.GetHomeById(mailconfig.HomeId, currentClient.Id).Title,
                                                   Encoding.UTF8.GetString(Convert.FromBase64String(entity.Password)))
            {
                body        = entity.Body,
                prio        = System.Net.Mail.MailPriority.Normal,
                subject     = entity.Subject,
                toPeople    = recipients,
                ssl         = (bool)mailconfig.IsSSL,
                attachments = MailUtils.GetAttachments(documents, mailconfig.Home)
            }, mailLog = new MailLog()
            {
                DateSended = DateTime.UtcNow,
                To         = String.Join(",", recipients.ToArray()),
                Successful = true,
                HomeId     = mailconfig.HomeId
            });
            repo.Add <MailLog>(mailLog);
            return(GetMapper.Map <MailLog, MailLogDTO>(mailLog));
        }
Beispiel #4
0
        private static void SendDataDrivenEmail(MySqlConnection con)
        {
            Dictionary <string, string> dictFlareSystemConfigurationEntries = SystemConfigurationEntry.GetDictionary(con);

            if (!dictFlareSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerAddress))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server address is specified");
            }

            if (!dictFlareSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerUserName))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server user name is specified");
            }

            if (!dictFlareSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerPassword))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server password is specified");
            }

            string       strSMTPServerAddress  = dictFlareSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerAddress];
            string       strSMTPServerUserName = dictFlareSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerUserName];
            string       strSMTPServerPassword = dictFlareSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerPassword];
            const string strFrom    = @"*****@*****.**";
            const string strTo      = @"*****@*****.**";
            const string strSubject = @"Data-driven e-mail test";
            string       strBody    = string.Format(@"Hello Tom; It is now {0} Universal Time.",
                                                    MySqlUtils.DateTimeToString(DateTime.UtcNow));

            Console.WriteLine(@"About to send data-driven e-mail to {0}...", strTo);
            MailUtils.SendMail(strSMTPServerAddress, strSMTPServerUserName, strSMTPServerPassword,
                               strFrom, strTo, null, null, strSubject, strBody);
            Console.WriteLine(@"E-mail sent.");
        }
        public async Task <IActionResult> ActiveAccount(int?id)
        {
            var buyerAccount = await _context.Account.FindAsync(id);



            if (buyerAccount.IsActive == 1)
            {
                buyerAccount.IsActive = 0;
                _context.Account.Attach(buyerAccount).Property(x => x.IsActive).IsModified = true;
                await MailUtils.SendMailGoogleSmtp("*****@*****.**", buyerAccount.Email, "Wasted Food thông báo", "Tài khoản của bạn đã bị khóa, vui lòng liên hệ lại với admin thông qua địa chỉ email này: [email protected] để được hỗ trợ ",
                                                   "*****@*****.**", "fall2020@WastedFoodSystem");

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Account)));
            }
            else if (buyerAccount.IsActive == 0)
            {
                buyerAccount.IsActive = 1;
                _context.Account.Attach(buyerAccount).Property(x => x.IsActive).IsModified = true;
                await MailUtils.SendMailGoogleSmtp("*****@*****.**", buyerAccount.Email, "Wasted Food thông báo", "Tài khoản của bạn đã được mở khóa, vui lòng liên hệ lại với admin thông qua địa chỉ email này: [email protected] để được hỗ trợ ",
                                                   "*****@*****.**", "fall2020@WastedFoodSystem");

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Account)));
            }
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #6
0
        public static void ProcessException(string message, string stacktrace)
        {
            int msgnum = MailUtils.SendErrorMessage(message, stacktrace);

            MessageBox.Show("Ошибка. Следующая информация об ошибке отправлена разработчикам под сообщением №"
                            + msgnum.ToString() + ":" + "\n\n" + message,
                            "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        public bool SendMail(string to, string subject, string message)
        {
            email.Subject = (subject == String.Empty) ? "[OSJ] NUEVO Curso de Astronomía Observacional" : subject;
            email.Message = message;

            sendCount++;
            return(MailUtils.SendEmail(email, to));
        }
Beispiel #8
0
        public async Task <IActionResult> Register(RegisterViewModel registerVm)
        {
            HttpContext.Session.SetString("user_name", "");
            HttpContext.Session.SetString("id", "");
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("Error", "Complet all fields.");
                return(View(registerVm));
            }
            var exist = await _context.Persons
                        .SingleOrDefaultAsync(m => m.EmailAddress == registerVm.Email);

            if (exist != null)
            {
                ModelState.AddModelError("Error", "Email address is used.");
                return(View(registerVm));
            }
            exist = await _context.Persons
                    .SingleOrDefaultAsync(m => m.Username == registerVm.UserName);

            if (exist != null)
            {
                ModelState.AddModelError("Error", "Username is used.");
                return(View(registerVm));
            }
            exist = await _context.Persons
                    .SingleOrDefaultAsync(m => m.Cnp == registerVm.Cnp);

            if (exist != null)
            {
                ModelState.AddModelError("Error", "Cnp is used.");
                return(View(registerVm));
            }
            var user = new Person
            {
                Id           = new Guid(),
                Cnp          = registerVm.Cnp,
                FirstName    = registerVm.FirstName,
                LastName     = registerVm.LastName,
                Username     = registerVm.UserName,
                EmailAddress = registerVm.Email,
                Password     = CryptingUtils.Encode(registerVm.Password),
                Gender       = registerVm.Gender,
                Birthday     = registerVm.Birthday,
                Role         = "Patient"
            };

            _context.Add(user);
            await _context.SaveChangesAsync();

            MailUtils email;

            email = new MailUtils(user.EmailAddress, "Account Confirmation.",
                                  "Your account has been successfully created. You can login.\nA beautiful day!\nMedicore team.");

            email.Send();
            return(RedirectToAction("Login", "Persons"));
        }
        public void SendEmailTest()
        {
            MailUtils target      = new MailUtils();   // TODO: Initialize to an appropriate value
            string    mailUrl     = "*****@*****.**"; // TODO: Initialize to an appropriate value
            string    title       = "test";            // TODO: Initialize to an appropriate value
            string    mailContent = "测试邮件服务器-Config";  // TODO: Initialize to an appropriate value
            bool      expected    = true;              // TODO: Initialize to an appropriate value
            bool      actual;

            actual = target.SendEmail(mailUrl, title, mailContent);
            Assert.AreEqual(expected, actual);
            //Assert.Inconclusive("Verify the correctness of this test method.");
        }
Beispiel #10
0
        // Send an e-mail to each of the target's account's contacts.

        private void SendFailureNotificationEmails(Target target, TargetLogRecord tlr)
        {
            if (!m_dictSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerAddress))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server address is specified");
            }

            if (!m_dictSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerUserName))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server user name is specified");
            }

            if (!m_dictSystemConfigurationEntries.ContainsKey(SystemConfigurationEntryKeys.SMTPServerPassword))
            {
                throw new Exception(@"Flare system configuration error: No SMTP server password is specified");
            }

            string       strSMTPServerAddress  = m_dictSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerAddress];
            string       strSMTPServerUserName = m_dictSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerUserName];
            string       strSMTPServerPassword = m_dictSystemConfigurationEntries[SystemConfigurationEntryKeys.SMTPServerPassword];
            const string strFrom    = @"Flare Server Monitoring";
            const string strSubject = @"Server monitoring failure notification";

            foreach (Contact contact in m_lstAllContacts)
            {
                if (contact.AccountID != target.AccountID || !contact.Enabled)  // We could filter out disabled contacts at the SQL level
                {
                    continue;
                }

                string strBody = string.Format(@"Hello {0} {1}; Your server '{2}' was unreachable at {3} Universal Time.",
                                               contact.FirstName, contact.LastName, target.Name, MySqlUtils.DateTimeToString(tlr.TimeStamp));

#if DO_NOT_SEND_EMAILS
                LogToConsole(@"**** Simulating the sending of e-mail ****");
                LogToConsole(string.Format(@"SMTP Server Address : {0}", strSMTPServerAddress));
                LogToConsole(string.Format(@"SMTP Server User Name : {0}", strSMTPServerUserName));
                LogToConsole(string.Format(@"SMTP Server Password : {0}", strSMTPServerPassword));
                LogToConsole(string.Format(@"From : {0}", strFrom));
                LogToConsole(string.Format(@"To : {0}", contact.EmailAddress));
                LogToConsole(string.Format(@"Subject : {0}", strSubject));
                LogToConsole(string.Format(@"Body : {0}", strBody));
                LogToConsole(@"**** End of e-mail ****");
#else
                MailUtils.SendMail(strSMTPServerAddress, strSMTPServerUserName, strSMTPServerPassword,
                                   strFrom, contact.EmailAddress, null, null, strSubject, strBody);
#endif
            }
        }
Beispiel #11
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            String email        = txtEmail.Value;
            string smtpUserName = "******";
            string smtpPassword = "******";
            string smtpHost     = "smtp.gmail.com";
            int    smtpPort     = 25;

            string emailTo = email;
            string subject = "Vương quốc son môi";
            string body    = string.Format("Chúng tôi sẽ sớm liên lạc với bạn! Cảm ơn bạn đã ghé thăm shop!");

            MailUtils service = new MailUtils();
            bool      kq      = service.Send(smtpUserName, smtpPassword, smtpHost, smtpPort, emailTo, subject, body);
        }
Beispiel #12
0
        public virtual MailLog MailSteps(Client currentClient, MailBookingModel model, object param)
        {
            ValidateNull <MailBookingModel>(model);

            MailLog         log             = new MailLog();
            HomeConfig      hc              = null;
            Document        body            = null;
            List <Document> listAttachments = null;

            BookingStepBookingRepository.includes.Add("CurrentStep");
            BookingStepBookingRepository.includes.Add("CurrentStep.Documents");
            BookingStepBookingRepository.includes.Add("CurrentStep.MailTemplate");
            BookingStepBookingRepository.includes.Add("Booking");
            BookingStepBookingRepository.includes.Add("Booking.People");
            BookingStepBooking b = BookingStepBookingRepository.GetBookingStepBookingById(model.BookingId, currentClient.Id);

            if (b == null)
            {
                validationDictionnary.AddModelError(TypeOfName.GetNameFromType <Booking>(), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                throw new ManahostValidationException(validationDictionnary);
            }
            HomeConfigRepository.includes.Add("DefaultMailConfig");
            hc = HomeConfigRepository.GetHomeConfigById(b.HomeId, currentClient.Id);
            if (!((BookingStepBookingValidation)validation).MailStepValidation(validationDictionnary, currentClient, hc, b, model, param))
            {
                throw new ManahostValidationException(validationDictionnary);
            }
            if (b.CurrentStep.MailTemplate == null)
            {
                validationDictionnary.AddModelError("CurrentStep.MailTemplate", GenericError.CANNOT_BE_NULL_OR_EMPTY);
                throw new ManahostValidationException(validationDictionnary);
            }
            body            = DocumentRepository.GetDocumentById(b.CurrentStep.MailTemplate.Id, currentClient.Id);
            listAttachments = b.CurrentStep.Documents;
            if (hc.DefaultMailConfig != null)
            {
                SendMailUsingCustomMailAccount(hc.DefaultMailConfig, b, log, model.Password,
                                               GetMailBody(body, b.Home), MailUtils.GetAttachments(listAttachments, b.Home));
            }
            else
            {
                SendMailUsingManahostMailAccount(b, log, GetMailBody(body, b.Home), MailUtils.GetAttachments(listAttachments, b.Home));
            }
            repo.Add <MailLog>(log);
            repo.Update(b);
            repo.Save();
            return(log);
        }
Beispiel #13
0
        private async Task ValidateMemberProfile(Guid chapterId, CreateMemberProfile profile)
        {
            IReadOnlyCollection <ChapterProperty> chapterProperties = await _chapterRepository.GetChapterProperties(chapterId);

            IReadOnlyCollection <string> missingProperties = GetMissingMemberProfileProperties(profile, chapterProperties, profile.Properties).ToArray();

            if (missingProperties.Count > 0)
            {
                throw new OdkServiceException($"The following properties are required: {string.Join(", ", missingProperties)}");
            }

            if (!MailUtils.ValidEmailAddress(profile.EmailAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }
        }
 /// <summary>
 /// Метод для потока, выполняющего сканирование электронной почты на наличие новых сообщений.
 /// </summary>
 private void ScanMessages()
 {
     try
     {
         while (true)
         {
             MailUtils.ReceiveMess(_receivingManager, _logger);
             if (_stopWaitHandle.WaitOne(_settings.MailScanPeriod))
             {
                 return;
             }
         }
     }
     catch (Exception e)
     {
         _logger.LogUnhandledException(e);
     }
 }
Beispiel #15
0
        public bool CheckNewPublicIPAdress()
        {
            string auxPublicIP = IPUtils.GetPublicIP();

            if ((auxPublicIP != PublicIP) ||
                (String.IsNullOrEmpty(PublicIP) && String.IsNullOrEmpty(LocalIP)))
            {
                PublicIP = auxPublicIP;
                LocalIP  = IPUtils.GetLocalIP();

                email.Subject  = "[WhatsMyIP] Se cambió la IP pública a " + PublicIP;
                email.Message  = "<b>IP pública:</b> " + PublicIP + "\n <br />" + "<b>IP local:</b> " + LocalIP;
                email.Message += "\n <br /> \n <br /> <b><u>NETSTAT</u></b> \n <br />" + IPUtils.GetNetStat();
                email.Message += "\n <br /> \n <br /> <b><u>GEOLOCALIZACION</u></b> \n <br />" + IPUtils.GetGeoLocationWithIP(this.PublicIP);
                MailUtils.SendEmail(email);

                return(true);
            }
            return(false);
        }
Beispiel #16
0
        public async Task <IActionResult> SendEmail(EmailSenderViewModel emailSenderVm)
        {
            if (!ModelState.IsValid)
            {
                return(View(emailSenderVm));
            }
            var isOk = await _context.Persons
                       .SingleOrDefaultAsync(m => m.Username == emailSenderVm.ToUsername);

            if (isOk == null)
            {
                return(View(emailSenderVm));
            }
            MailUtils email;

            email = new MailUtils(isOk.EmailAddress, emailSenderVm.Subject,
                                  emailSenderVm.Body);

            email.Send();
            return(RedirectToAction("Index", "Persons"));
        }
Beispiel #17
0
        public async Task <IActionResult> ActiveAccount(int?id)
        {
            var sellerAccount = await _context.Account.FindAsync(id);


            if (sellerAccount.IsActive == 2)
            {
                sellerAccount.IsActive = 1;
                _context.Account.Attach(sellerAccount).Property(x => x.IsActive).IsModified = true;
                await MailUtils.SendMailGoogleSmtp("*****@*****.**", sellerAccount.Email, "Chào mừng bạn đến với Wasted Food", "Tài khoản của bạn đã được thông qua xét duyệt và trở thành thành viên của chúng tôi dưới đây là thông tin tài khoản của bạn \n " + "Tên tài khoản : " + sellerAccount.Username + "\n",
                                                   "*****@*****.**", "fall2020@WastedFoodSystem");

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(WaitForActive)));
            }
            else if (sellerAccount.IsActive == 1)
            {
                sellerAccount.IsActive = 0;
                _context.Account.Attach(sellerAccount).Property(x => x.IsActive).IsModified = true;
                await MailUtils.SendMailGoogleSmtp("*****@*****.**", sellerAccount.Email, "Wasted Food thông báo", "Tài khoản của bạn đã bị khóa, vui lòng liên hệ lại với admin thông qua địa chỉ email này: [email protected] để được hỗ trợ ",
                                                   "*****@*****.**", "fall2020@WastedFoodSystem");

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Account)));
            }
            else if (sellerAccount.IsActive == 0)
            {
                sellerAccount.IsActive = 1;
                _context.Account.Attach(sellerAccount).Property(x => x.IsActive).IsModified = true;
                await MailUtils.SendMailGoogleSmtp("*****@*****.**", sellerAccount.Email, "Wasted Food thông báo", "Tài khoản của bạn đã được mở khóa, vui lòng liên hệ lại với admin thông qua địa chỉ email này: [email protected] để được hỗ trợ ",
                                                   "*****@*****.**", "fall2020@WastedFoodSystem");

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Account)));
            }
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #18
0
        public async Task RequestMemberEmailAddressUpdate(Guid memberId, string newEmailAddress)
        {
            Member member = await GetMember(memberId, memberId);

            if (member.EmailAddress.Equals(newEmailAddress, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!MailUtils.ValidEmailAddress(newEmailAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }

            MemberEmailAddressUpdateToken existingToken = await _memberRepository.GetMemberEmailAddressUpdateToken(member.Id);

            if (existingToken != null)
            {
                await _memberRepository.DeleteEmailAddressUpdateToken(member.Id);
            }

            string activationToken = RandomStringGenerator.Generate(64);

            MemberEmailAddressUpdateToken token = new MemberEmailAddressUpdateToken(member.Id, newEmailAddress, activationToken);
            await _memberRepository.AddEmailAddressUpdateToken(token);

            Chapter chapter = await _chapterRepository.GetChapter(member.ChapterId);

            string url = _settings.ConfirmEmailAddressUpdateUrl.Interpolate(new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "token", HttpUtility.UrlEncode(activationToken) }
            });

            await _emailService.SendEmail(chapter, newEmailAddress, EmailType.EmailAddressUpdate, new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "url", url }
            });
        }
Beispiel #19
0
 private void SendMail(List <string> files)
 {
     try
     {
         MailUtils.Send("Inserimente Note Geisp.",
                        "Inserimente Note Geisp.",
                        files,
                        ConfigUtils.GetCaricoAddress(), ConfigUtils.GetPostAddress());
     }
     catch
     {
         try
         {
             MailUtils.Send("IImpossibile inviare la posta. È possibile trovare il file excel all'indirizzo: " + files.FirstOrDefault(),
                            "PRESTITEMPO ESITI: errori nell’inserimento degli esiti su sito committente",
                            new List <string>(),
                            ConfigUtils.GetCaricoAddress(), ConfigUtils.GetPostAddress());
         }
         catch { }
         Logger.Log("Impossibile inviare la posta. È possibile che le credenziali di posta non sono buone. È possibile trovare il file excel all'indirizzo: " + files.FirstOrDefault(), LogType.Error);
     }
 }
Beispiel #20
0
        public void SendMailTest()
        {
            SMTPEmail email = new SMTPEmail();

            email.From       = ConfigurationManager.AppSettings["FromAddress"];
            email.To         = ConfigurationManager.AppSettings["ToAddress"];
            email.SMTPClient = ConfigurationManager.AppSettings["SMTP"];
            email.SMTPServer = ConfigurationManager.AppSettings["SMTP"];
            email.SMTPPort   = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            email.Password = ConfigurationManager.AppSettings["Password"];
            email.Domain   = ConfigurationManager.AppSettings["Domain"];
            email.IsSSL    = bool.Parse(!String.IsNullOrEmpty(ConfigurationManager.AppSettings["EnableSSL"])? ConfigurationManager.AppSettings["EnableSSL"] :"false");
            email.UseDefaultCredentials = bool.Parse(!String.IsNullOrEmpty(ConfigurationManager.AppSettings["UseDefaultCredentials"]) ? ConfigurationManager.AppSettings["UseDefaultCredentials"] : "false");

            email.Subject = "[OSJ] SendMailTest ";
            email.Message = "Amigos de la Torre<br /><br />El viernes 21/03/14 comienza el curso de <b>'Astronomía Observacional'</b>, el objeto de este curso es que el alumno adquiera un conocimiento integral del cielo nocturno y aprenda paulatinamente conceptos como: sistemas de coordenadas, constelaciones, movimientos de los planetas, principales estrellas y lectura e interpretación de diferentes cartas celestes. El curso está basado principalmente en observaciones prácticas, con diferentes instrumentos, a fin de que los participantes logren familiarizarse rápidamente con el firmamento. Las observaciones con los instrumentos del observatorio se harán de acuerdo a las efemérides y a las condiciones meteorológicas."
                            + "<br /><br /><b>Dados los contenidos y metodologías aplicadas en el curso, el mismo es para adultos y chicos de 12 años en adelante y no se necesitan conocimientos previos de matemática, física o astronomía.</b>"
                            + "<b><br /><br /><ul><li>Comienzo: viernes 21/03/14</li><li>Duración: 4 clases</li><li>Horario: viernes de 20 a 22 hs</li><li>Arancel: $300 (se abonan el mismo día del inicio del curso) - Alumnos del Colegio San José gratis - Todo lo recaudado se destina al mantenimiento del observatorio</li><li>Dirección: Bartolomé Mitre 2455, Capital Federal (Colegio San José)</li><li>Informes e inscripción:<br />www.observatoriosanjose.com.ar<br />[email protected]<br />[email protected]</b></li></ul>";

            Assert.IsTrue(MailUtils.SendEmail(email));
        }
Beispiel #21
0
        public async Task RequestPasswordReset(string emailAddress)
        {
            if (!MailUtils.ValidEmailAddress(emailAddress))
            {
                throw new OdkServiceException("Invalid email address format");
            }

            Member member = await _memberRepository.FindMemberByEmailAddress(emailAddress);

            DateTime created = DateTime.UtcNow;
            DateTime expires = created.AddMinutes(_settings.PasswordResetTokenLifetimeMinutes);
            string   token   = RandomStringGenerator.Generate(64);

            try
            {
                _authorizationService.AssertMemberIsCurrent(member);
            }
            catch
            {
                return;
            }

            Chapter chapter = await _chapterRepository.GetChapter(member.ChapterId);

            await _memberRepository.AddPasswordResetRequest(member.Id, created, expires, token);

            string url = _settings.PasswordResetUrl.Interpolate(new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "token", HttpUtility.UrlEncode(token) }
            });

            await _emailService.SendEmail(chapter, member.EmailAddress, EmailType.PasswordReset, new Dictionary <string, string>
            {
                { "chapter.name", chapter.Name },
                { "url", url }
            });
        }
Beispiel #22
0
        public void ProcessFile(string fileNameAndPath, string outputDir, string failedDir, string processedDir, string callerRef, string sentTo)
        {
            DocConverterFactory factory = new DocConverterFactory();

            factory._logFile = _logFile;
            factory.StartConverter();
            FileInfo file = new FileInfo(fileNameAndPath);

            try
            {
                IDocConverter converter = factory.GetDocConverter(file.FullName);
                converter.Convert(file.FullName, file.FullName, outputDir, processedDir, callerRef, sentTo);
            }
            catch (Exception e)
            {
                string mailMsg = "The file ''" + file.FullName + "'' has been moved to the directory " + failedDir + @"\" + Properties.Settings.Default.FailedSubDirConvert + ";" + Environment.NewLine + Environment.NewLine +
                                 "Reason:" + Environment.NewLine + "There was an issue converting this file to TIF format.  " + Environment.NewLine + e.Message;
                MailUtils.SendEmail("Error", "Converting File", mailMsg, fileNameAndPath);
                FileUtils.MoveToDir(file, failedDir + @"\" + Properties.Settings.Default.FailedSubDirConvert);
                throw new FormatConversionException("Error: ''" + file.FullName + "'' has been moved to the directory " + failedDir + "; " + Environment.NewLine + e.Message);
            }

            factory.ShutdownConverter();
        }
Beispiel #23
0
        public async Task <ActionResult> Create(Utilisateurs utilisateurs)
        {
            if (Db.Utilisateurs.Count(x => x.Email == utilisateurs.Email && x.Etat == EtatEnum.ACTIF) > 0)
            {
                ModelState.AddModelError("Email", "Cette adresse est déjà présente!");
            }

            if (ModelState.IsValid)
            {
                Utilisateurs user;
                var          isAjout = false;
                //si l'adresse existe en base c'est que c'est un utilisateur périmé, donc on le réactive
                if (Db.Utilisateurs.Count(x => x.Email == utilisateurs.Email) > 0)
                {
                    user = Db.Utilisateurs.First(x => x.Email == utilisateurs.Email);
                }
                else
                {
                    user    = Db.Utilisateurs.Create();
                    isAjout = true;
                }

                var motDePasse = CryptUtils.GeneratePassword(9, true, true, true);
                user.MotDePasse = CryptUtils.GenerateHashPassword(motDePasse);
                user.Email      = utilisateurs.Email.ToLower();
                user.Nom        = StringUtils.FirstLetterUpper(utilisateurs.Nom.ToLower());
                user.Prenom     = StringUtils.FirstLetterUpper(utilisateurs.Prenom.ToLower());
                user.Nid        = utilisateurs.Nid;
                user.Pnia       = utilisateurs.Pnia;
                user.Role       = utilisateurs.Role;
                user.GradesId   = utilisateurs.GradesId;
                user.PolesId    = utilisateurs.PolesId;
                user.Etat       = EtatEnum.ACTIF;

                if (isAjout)
                {
                    Db.Entry(user).State = EntityState.Added;
                    Db.Utilisateurs.Add(user);
                }
                else
                {
                    Db.Entry(user).State = EntityState.Modified;
                }
                Db.SaveChanges();

                //envoi du mail
                var mail         = Db.Mails.First(x => x.NomUnique == ContexteStatic.EnvoiCreationCompte);
                var corpsMessage = StringUtils.CopyString(mail.Corps);
                corpsMessage = corpsMessage.Replace("%NOMAPPLI%", ContexteApplication.Application.NomAppli);
                corpsMessage = corpsMessage.Replace("%LOGIN%", user.Email);
                corpsMessage = corpsMessage.Replace("%MOTDEPASSE%", motDePasse);
                await MailUtils.SendMail(user.Email, mail.Objet, corpsMessage);

                return(RedirectToAction("Index"));
            }

            ViewBag.GradesId = new SelectList(Db.Grades.Where(x => x.Etat == EtatEnum.ACTIF && x.ArmesId == utilisateurs.ArmesId).ToList(), "Id", "Nom");
            ViewBag.ArmesId  = new SelectList(Db.Armes.Where(x => x.Etat == EtatEnum.ACTIF).ToList(), "Id", "Nom");
            ViewBag.PolesId  = new SelectList(Db.Poles.Where(x => x.Etat == EtatEnum.ACTIF).ToList(), "Id", "Nom");
            return(View(utilisateurs));
        }
Beispiel #24
0
        public async Task <ActionResult> Create(EvenementViewModel evenementCreer)
        {
            if (ModelState.IsValid)
            {
                //controle de la dateA
                if (evenementCreer.EvenementsCre.Date < DateUtils.GetAujourdhui())
                {
                    ModelState.AddModelError("EvenementsCre.Date", "La date doit être supérieur à la date du jour");
                }

                if (evenementCreer.EvenementsCre.DemiJournee != DemiJourneeEnum.APRESMIDI && evenementCreer.EvenementsCre.DemiJournee != DemiJourneeEnum.MATIN)
                {
                    ModelState.AddModelError("EvenementsCre.DemiJournee", "Il est nécéssaire de préciser la demi journée");
                }

                //controle de la dateB
                if (evenementCreer.EvenementsCre.DateB != null)
                {
                    if (evenementCreer.EvenementsCre.DemiJourneeB != DemiJourneeEnum.APRESMIDI && evenementCreer.EvenementsCre.DemiJourneeB != DemiJourneeEnum.MATIN)
                    {
                        ModelState.AddModelError("EvenementsCre.DemiJourneeB", "Il est nécéssaire de préciser la demi journée");
                    }

                    if (evenementCreer.EvenementsCre.DateB < DateUtils.GetAujourdhui())
                    {
                        ModelState.AddModelError("EvenementsCre.DateB", "La date doit être supérieur à la date du jour");
                    }

                    if (evenementCreer.EvenementsCre.DateB == evenementCreer.EvenementsCre.Date &&
                        evenementCreer.EvenementsCre.DemiJourneeB == evenementCreer.EvenementsCre.DemiJournee)
                    {
                        ModelState.AddModelError("EvenementsCre.DateB", "cette date est identique à la première date");
                    }
                }

                //controle de la dateC
                if (evenementCreer.EvenementsCre.DateC != null)
                {
                    if (evenementCreer.EvenementsCre.DemiJourneeC != DemiJourneeEnum.APRESMIDI && evenementCreer.EvenementsCre.DemiJourneeC != DemiJourneeEnum.MATIN)
                    {
                        ModelState.AddModelError("EvenementsCre.DemiJourneeC", "Il est nécéssaire de préciser la demi journée");
                    }

                    if (evenementCreer.EvenementsCre.DateC < DateUtils.GetAujourdhui())
                    {
                        ModelState.AddModelError("EvenementsCre.DateC", "La date doit être supérieur à la date du jour");
                    }

                    if ((evenementCreer.EvenementsCre.DateC == evenementCreer.EvenementsCre.Date && evenementCreer.EvenementsCre.DemiJourneeC == evenementCreer.EvenementsCre.DemiJournee) ||
                        (evenementCreer.EvenementsCre.DateB != null && evenementCreer.EvenementsCre.DemiJourneeB != null &&
                         evenementCreer.EvenementsCre.DateC == evenementCreer.EvenementsCre.DateB && evenementCreer.EvenementsCre.DemiJourneeC == evenementCreer.EvenementsCre.DemiJourneeB))
                    {
                        ModelState.AddModelError("EvenementsCre.DateC", "cette date est identique à une des dates ci dessus");
                    }
                }


                //control de la date de verrouillage
                if (evenementCreer.EvenementsCre.DateVerrou != null)
                {
                    if (evenementCreer.EvenementsCre.DateVerrou <= DateUtils.GetAujourdhui() ||
                        evenementCreer.EvenementsCre.DateVerrou > evenementCreer.EvenementsCre.Date ||
                        (evenementCreer.EvenementsCre.DateB != null && evenementCreer.EvenementsCre.DateVerrou > evenementCreer.EvenementsCre.DateB) ||
                        (evenementCreer.EvenementsCre.DateC != null && evenementCreer.EvenementsCre.DateVerrou > evenementCreer.EvenementsCre.DateC))
                    {
                        ModelState.AddModelError("EvenementsCre.DateVerrou", "La date limite est incorrecte");
                    }
                }

                //recup des utilisateurs / poles sélectionnés
                var selectedIdsPole = Request.Form.GetValues("PolesIdChecked");
                var selectedIdsUser = Request.Form.GetValues("UtilisateursIdChecked");

                //control de la sélection du personnel
                if (!StringUtils.CheckStringArrayContainsInt(selectedIdsPole) && !StringUtils.CheckStringArrayContainsInt(selectedIdsUser))
                {
                    ModelState.AddModelError("selectionError", "Aucune personne de sélectionné");
                }

                if (ModelState.IsValid)
                {
                    var selectedUserToSend = Request.Form["radioSelect"] == "0";
                    //si la date de verrouillage est null c'est que c'est la meme que la date de l'évènement (la plus grande des trois possibles)
                    evenementCreer.EvenementsCre.DateVerrou = (evenementCreer.EvenementsCre.DateVerrou.HasValue)
                         ? evenementCreer.EvenementsCre.DateVerrou
                         : DateUtils.GetPlusGrandeDate(evenementCreer.EvenementsCre.Date, evenementCreer.EvenementsCre.DateB, evenementCreer.EvenementsCre.DateC);

                    //récup de l'évènement
                    var even = evenementCreer.EvenementsCre;
                    even.CreateurId = GetIdUtilisateurConnecte();
                    Db.Evenements.Add(even);

                    //récup des utilisateurs à inviter
                    List <Utilisateurs> listeUser;
                    if (selectedUserToSend)
                    {
                        //récup de la lsite des utilisateurs sélectionné
                        var listeInt = new List <int>();
                        foreach (var value in selectedIdsUser)
                        {
                            int i;
                            if (int.TryParse(value, out i))
                            {
                                listeInt.Add(i);
                            }
                        }

                        listeUser = Db.Utilisateurs.Where(
                            x => listeInt.Contains(x.Id)).ToList();
                    }
                    else
                    {
                        //récup de la lsite des utilisateurs sélectionné par poles
                        var listeInt = new List <int>();
                        foreach (var value in selectedIdsPole)
                        {
                            int i;
                            if (int.TryParse(value, out i))
                            {
                                listeInt.Add(i);
                            }
                        }
                        listeUser = Db.Utilisateurs.Where(x => listeInt.Contains(x.PolesId)).ToList();
                    }

                    //si l'utilisateur qui le crée n'est pas dedans, il est rajouté automatiquement
                    if (listeUser.Count(x => x.Id == GetIdUtilisateurConnecte()) == 0)
                    {
                        listeUser.Add(Db.Utilisateurs.Find(GetIdUtilisateurConnecte()));
                    }

                    //pour chaque invité, envoi d'un mail
                    var mail         = Db.Mails.First(x => x.NomUnique == ContexteStatic.EnvoiInvitEvenement);
                    var corpsMessage = StringUtils.CopyString(mail.Corps);
                    foreach (var user in listeUser)
                    {
                        var evenUser = new EvenementsUtilisateurs()
                        {
                            Utilisateurs = user,
                            Evenements   = even,
                            Commentaire  = null,
                            IsPresent    = null
                        };
                        Db.EvenementsUtilisateurs.Add(evenUser);

                        var id      = GetIdUtilisateurConnecte();
                        var userCre = Db.Utilisateurs.Find(id);
                        corpsMessage = corpsMessage.Replace("%TITRE_EVEN%", even.Titre);
                        corpsMessage = corpsMessage.Replace("%ADRESSE%",
                                                            $"{Request.Url.Scheme}://{Request.Url.Authority}{Url.Content("~")}" +
                                                            "Evenements/MesEvenements");
                        corpsMessage = corpsMessage.Replace("%APPLI%", ContexteApplication.Application.NomAppli);
                        corpsMessage = corpsMessage.Replace("%NOM_CREATEUR%", userCre.Grades.Diminutif + " " + userCre.Nom + " " + userCre.Prenom);
                        corpsMessage = corpsMessage.Replace("%DATELIM%", DateUtils.GetDateFormat((even.DateVerrou.HasValue)? even.DateVerrou.Value:even.Date, "yyyy-MM-dd"));

                        //envoi du mail
                        await MailUtils.SendMail(user.Email, mail.Objet, corpsMessage);
                    }
                    Db.SaveChanges();
                    return(RedirectToAction("MesEvenements", "Evenements"));
                }
            }
            return(View(GenerateViewModelCreate(evenementCreer)));
        }
        public override async Task <IActionResult> Result()
        {
            var currentStep = Storage.GetCurrentStep(MsgId);

            //Switch to next step = currentStep + 1
            switch (currentStep + 1)
            {
                #region step 1
            case 1:
            {
                Storage.AddOrUpdateToStorage(MsgId, 1, null);
                using (var petTypeDAO = new PetTypeDAO())
                {
                    return(Receiver.Json(new
                        {
                            speech = "",
                            messages = new[]
                            {
                                new
                                {
                                    type = 2,
                                    platform = "facebook",
                                    title = "Bạn muốn sản phẩm cho thú cưng nào ạ?",
                                    replies = (await petTypeDAO.ReadAll(false))
                                              .Select(x => x.Name)
                                              .ToArray()
                                }
                            }
                        }));
                }
            }

                #endregion
                #region Step 2
            case 2:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var petTypeDAO = new PetTypeDAO())
                    {
                        if (await(await petTypeDAO.ReadAll(false))
                            .Select(x => x.Name)
                            .AllAsync(x => x != MsgReply))
                        {
                            _isSkipValidation = true;
                            goto case 1;
                        }
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 2, null);
                Storage.AddOrUpdateToStorage(MsgId, 1, MsgReply);
                return(Receiver.Json(new
                    {
                        speech = "",
                        messages = new[]
                        {
                            new
                            {
                                type = 2,
                                platform = "facebook",
                                title = "Bạn muốn mua gì cho bé ạ?",
                                replies = new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }
                            }
                        }
                    }));
            }

                #endregion
                #region Step 3
            case 3:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 2;
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 3, null);
                Storage.AddOrUpdateToStorage(MsgId, 2, MsgReply);
                return(Receiver.Json(new
                    {
                        speech = "",
                        messages = new[]
                        {
                            new
                            {
                                type = 2,
                                platform = "facebook",
                                title = "Bạn có thể cho mình biết mức giá bạn muốn tìm kiếm?",
                                replies = new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }
                            }
                        }
                    }));
            }
                #endregion
                #region Step 4

            case 4:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }.All(x =>
                                                                                                  x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 3;
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 4, null);
                Storage.AddOrUpdateToStorage(MsgId, 3, MsgReply);

                //Find minimum and maximum price from step 3
                int minimumPrice, maximumPrice;

                switch (Storage[MsgId, 3])
                {
                case "<100000":
                    minimumPrice = 0;
                    maximumPrice = 99999;
                    break;

                case "100000 - 300000":
                    minimumPrice = 100000;
                    maximumPrice = 300000;
                    break;

                case ">300000 - 500000":
                    minimumPrice = 300001;
                    maximumPrice = 500000;
                    break;

                default:
                    minimumPrice = 500001;
                    maximumPrice = int.MaxValue;
                    break;
                }

                //Find product in step 2, for pet in step 1
                return(await MessengerProductListResult(GetProductType(), minimumPrice, maximumPrice));
            }

                #endregion
                #region Step 5
            case 5:
            {
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var productDAO = new ProductDAO())
                    {
                        if (await productDAO.Read(MsgQuery, false) == null)
                        {
                            _isSkipValidation = true;
                            goto case 4;
                        }
                    }
                }

                Storage.AddOrUpdateToStorage(MsgId, 5, null);
                Storage.AddOrUpdateToStorage(MsgId, 4, MsgQuery);
                return(Receiver.Json(new
                    {
                        speech = "Bạn có thể cho mình biết tên đăng nhập trên hệ thống Cutieshop được không ạ?\nNếu chưa có, bạn có thể gõ tên đăng nhập mới để chúng mình tạo tài khoản cho bạn"
                    }));
            }
                #endregion
                #region Step 6

            case 6:
            {
                //This step receive username first, then the email and address. So we need to keep the username to the storage for further uses, email will be used once in this step and can be queried by DAO easily in the future.
                //Checking null will prevent email from being overwritten to username in Storage
                if (Storage[MsgId, 5] == null)
                {
                    Storage.AddOrUpdateToStorage(MsgId, 5, MsgReply);
                }

                using (var userDAO = new UserDAO())
                {
                    var user = await userDAO.ReadChild(Storage[MsgId, 5], true);

                    //If user is null, create a user, then ask customer their email
                    if (user == null)
                    {
                        Storage.AddOrUpdateToStorage(MsgId, 6, "userPassword", new GuidHelper().CreateGuid());
                        await userDAO.Create(new Auth
                            {
                                Username = Storage[MsgId, 5],
                                Password = Storage[MsgId, 6, "userPassword"]
                            });

                        await userDAO.CreateChild(new User
                            {
                                Username = Storage[MsgId, 5],
                                Email    = string.Empty,
                                Address  = string.Empty
                            });

                        await userDAO.Context.SaveChangesAsync();
                    }

                    user = await userDAO.ReadChild(Storage[MsgId, 5], true);

                    //If email is empty, as for email
                    if (user.Email == string.Empty)
                    {
                        if (Storage[MsgId, 6, "isAskForEmail"] == null)
                        {
                            Storage.AddOrUpdateToStorage(MsgId, 6, "isAskForEmail", "1");
                            return(Receiver.Json(new
                                {
                                    speech = "Bạn hãy cho mình biết email nhé"
                                }));
                        }

                        //Validate email
                        var atInd = MsgReply.IndexOf("@", StringComparison.OrdinalIgnoreCase);
                        if (atInd < 1 || atInd == MsgReply.Length - 1)
                        {
                            return(Receiver.Json(new
                                {
                                    speech = "Email không hợp lệ\nVui lòng nhập lại email"
                                }));
                        }

                        user.Email = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //If address is empty but email is not, MsgReply must be address
                    if (user.Address == string.Empty)
                    {
                        if (Storage[MsgId, 6, "isAskForAddress"] == null)
                        {
                            Storage.AddOrUpdateToStorage(MsgId, 6, "isAskForAddress", "1");
                            return(Receiver.Json(new
                                {
                                    speech = "Bạn cho mình xin địa chỉ"
                                }));
                        }

                        user.Address = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //Ready to jump into step 7 after this
                    Storage.AddOrUpdateToStorage(MsgId, 6, null);

                    using (var onlineOrderProductDAO = new OnlineOrderProductDAO(userDAO.Context))
                    {
                        var orderId = new GuidHelper().CreateGuid();
                        await onlineOrderProductDAO.Create(new OnlineOrder
                            {
                                OnlineOrderId = orderId,
                                FirstName     = user.FirstName,
                                LastName      = user.LastName,
                                Address       = user.Address,
                                PostCode      = "10000",
                                City          = user.City,
                                PhoneNo       = "12345678",
                                Email         = user.Email,
                                Date          = DateTime.Now,
                                Username      = user.Username,
                                StatusId      = 0
                            });

                        await onlineOrderProductDAO.CreateChild(new OnlineOrderProduct
                            {
                                ProductId     = Storage[MsgId, 4],
                                OnlineOrderId = orderId,
                                Quantity      = 1
                            });

                        Product buyProduct;
                        using (var productDAO = new ProductDAO())
                        {
                            buyProduct = await productDAO.Read(Storage[MsgId, 4], false);
                        }
                        var mailProductTable = _mailContent.BuyReq.TableRow.
                                               Replace("{0}", buyProduct.Name)
                                               .Replace("{1}", buyProduct.Description)
                                               .Replace("{2}", "1");

                        var mailBody = _mailContent.BuyReq.Body
                                       .Replace("{0}", user.Username)
                                       .Replace("{1}", mailProductTable)
                                       .Replace("{2}", "http://cutieshopapi.azurewebsites.net/verify?id=" + orderId);

                        MailUtils.Send(user.Email, _mailContent.BuyReq.Subject, mailBody);

                        var reply =
                            $"Mail xác nhận đã được gửi đến {user.Email}. Hãy xác nhận qua mail để hoàn tất đặt hàng nhé!";

                        //Send temporary password if customer create new account
                        if (Storage[MsgId, 6, "userPassword"] != null)
                        {
                            reply = $"Password tạm thời của bạn là {Storage[MsgId, 6, "userPassword"]}. Bạn nên vào trang chủ để thay đổi mật khẩu mặc định\n" + reply;
                        }

                        //Remove data in storage
                        Storage.RemoveId(MsgId);

                        return(Receiver.Json(new
                            {
                                speech = reply
                            }));
                    }
                }
            }

                #endregion
            }

            Storage.RemoveId(MsgId);
            throw new UnhandledChatException();
        }
 public string[] GetMailsFromFile(string file)
 {
     return(MailUtils.GetMailsFromFile(file));
 }
Beispiel #27
0
        public void ProcessFile(string fileNameAndPath)
        {
            try
            {
                writeToDebugLog("ProcessFile", "----------------------------------------------------------");
                writeToDebugLog("ProcessFile", "Processing: " + fileNameAndPath);
                string extWithPeriod = Path.GetExtension(fileNameAndPath);
                string ext           = extWithPeriod.Replace(".", "");

                string callerRef = getCallerRef(fileNameAndPath);
                //writeToDebugLog("ProcessFile", "callerRef=" + callerRef);

                string sentTo = getSentTo(fileNameAndPath);
                //writeToDebugLog("ProcessFile", "sentTo=" + sentTo);

                if (fileNameAndPath.Contains(THUMBS_DB))
                {
                    return;
                }
                else if (_validExtList.Contains(ext, StringComparer.OrdinalIgnoreCase))
                {
                    writeToDebugLog("ProcessFile", "ext=" + ext + " is a valid extension. Processing...");

                    writeToDebugLog("ProcessFile", "DocConverter - Initializing.");
                    Controller controller = new Controller();
                    controller._logFile = _debugLog;
                    writeToDebugLog("ProcessFile", "DocConverter - Sending sourceFile=" + fileNameAndPath + "; failedDir=" + this._failedDir + "; processedDir=" + this._processedDir);
                    controller.ProcessFile(fileNameAndPath, this._outputDir, this._failedDir, "", callerRef, sentTo);
                    writeToDebugLog("ProcessFile", "DocConverter - Completed.");

                    //Move original data file to processed dir
                    string origNameOnly = Path.GetFileName(fileNameAndPath);
                    string datafileProcessedNameAndPath = Path.Combine(_processedDir, origNameOnly);
                    bool   processedFileExists          = File.Exists(datafileProcessedNameAndPath);
                    writeToDebugLog("ProcessFile", "Processed sourceFile(" + datafileProcessedNameAndPath + ") exists=" + processedFileExists);
                    if (File.Exists(fileNameAndPath)) //jvc make sure not already moved due to fail
                    {
                        writeToDebugLog("ProcessFile", "Moving sourcefile to processedDir: " + datafileProcessedNameAndPath);
                        FileUtils.MoveToDir(new FileInfo(fileNameAndPath), _processedDir);
                        writeToDebugLog("ProcessFile", "Move file complete.");
                    }

                    writeToDebugLog("ProcessFile", "Processing Complete: " + fileNameAndPath);
                    _EventLog.WriteToLog("--> ProcessFile - Complete: " + fileNameAndPath);
                }
                else
                {
                    writeToDebugLog("ProcessFile", "Skipped File: " + fileNameAndPath);
                    _EventLog.WriteToLog("-->** Skipped File: " + fileNameAndPath);
                    string mailMsg = "The file ''" + fileNameAndPath + "'' was skipped because it is not in a supported format (" + Properties.Settings.Default.ValidFileExt + ")." + Environment.NewLine +
                                     "It has been moved to the directory " + _failedDir + @"\" + Properties.Settings.Default.FailedSubDirUnsupported + ".";
                    MailUtils.SendEmail("Warning", "Unsupported File Format", mailMsg, fileNameAndPath);
                    FileUtils.MoveToDir(new FileInfo(fileNameAndPath), _failedDir + @"\" + Properties.Settings.Default.FailedSubDirUnsupported);
                }

                //Israel 5/13/2015 -- address generated name collision.
                int milliseconds = 2000;
                Thread.Sleep(milliseconds);
            }
            catch (FormatConversionException ex) {
                writeToDebugLog("ProcessFile", "ERROR: " + ex.Message);
                _EventLog.WriteToLog("ERROR Processing: " + fileNameAndPath + "; " + ex.Message);
            }
            catch (Exception e)
            {
                string erMsg = "ERROR Processing: " + fileNameAndPath + "; " + Environment.NewLine + e.Message + "." + Environment.NewLine + Environment.NewLine +
                               "Stack Trace:" + Environment.NewLine + e.StackTrace;
                writeToDebugLog("ProcessFile", erMsg);
                _EventLog.WriteToLog(erMsg);
                if (File.Exists(fileNameAndPath))
                {
                    string mailMsg = "The file ''" + fileNameAndPath + "'' has been moved to the directory " + this._failedDir + ";" + Environment.NewLine + Environment.NewLine +
                                     "Reason:" + Environment.NewLine + "There was an issue while processing this file.  " + e.Message + "." + Environment.NewLine + Environment.NewLine +
                                     "Stack Trace:" + Environment.NewLine + e.StackTrace;
                    MailUtils.SendEmail("Error", "Exception Processing Inbound File", mailMsg, fileNameAndPath);
                    writeToDebugLog("ProcessFile", "Moving sourcefile to failedDir: " + fileNameAndPath);
                    FileUtils.MoveToDir(new FileInfo(fileNameAndPath), this._failedDir);
                    writeToDebugLog("ProcessFile", "Move file complete.");
                }
                else
                {
                    string mailMsg = "There was an exception processing file ''" + fileNameAndPath + "'';" + Environment.NewLine + Environment.NewLine + "Reason:" + Environment.NewLine + e.Message + "." + Environment.NewLine + Environment.NewLine + "Stack Trace:" + Environment.NewLine + e.StackTrace;
                    MailUtils.SendEmail("Error", "Exception Processing Inbound File", mailMsg, "");
                }
            }
        }
Beispiel #28
0
        public override async Task <IActionResult> Result()
        {
            var currentStep = Storage.GetCurrentStep(MsgId);

            //Switch to next step = currentStep + 1
            switch (currentStep + 1)
            {
                #region step 1
            case 1:
                Storage.AddOrUpdate(MsgId, 1, null);
                using (var petTypeDAO = new PetTypeDAO())
                {
                    var allPetTypes = (await petTypeDAO
                                       .ReadAll(false))
                                      .Select(x => x.Name)
                                      .ToArray();

                    return(Recv.Json(RespObj(RespType.QuickReplies,
                                             "Bạn muốn sản phẩm cho thú cưng nào ạ?", allPetTypes)));
                }

                #endregion
                #region Step 2
            case 2:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var petTypeDAO = new PetTypeDAO())
                    {
                        if (await(await petTypeDAO.ReadAll(false))
                            .Select(x => x.Name)
                            .AllAsync(x => x != MsgReply))
                        {
                            _isSkipValidation = true;
                            goto case 1;
                        }
                    }
                }

                Storage.AddOrUpdate(MsgId, 2, null);
                Storage.AddOrUpdate(MsgId, 1, MsgReply);
                return(Recv.Json(RespObj(RespType.QuickReplies, "Bạn muốn mua gì cho bé ạ?",
                                         new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" })));

                #endregion
                #region Step 3
            case 3:
                //Check if answer is valid
                // ReSharper disable once InvertIf
                if (!_isSkipValidation)
                {
                    if (new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 2;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                return(Recv.Json(RespObj(RespType.QuickReplies,
                                         "Bạn có thể cho mình biết mức giá bạn muốn tìm kiếm?",
                                         new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" })));

                #endregion
                #region Step 4
            case 4:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 3;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                //Find minimum and maximum price from step 3
                int minimumPrice, maximumPrice;

                switch (Storage[MsgId, 3])
                {
                case "<100000":
                    minimumPrice = 0;
                    maximumPrice = 99999;
                    break;

                case "100000 - 300000":
                    minimumPrice = 100000;
                    maximumPrice = 300000;
                    break;

                case ">300000 - 500000":
                    minimumPrice = 300001;
                    maximumPrice = 500000;
                    break;

                default:
                    minimumPrice = 500001;
                    maximumPrice = int.MaxValue;
                    break;
                }

                //Find product in step 2, for pet in step 1
                return(await MessengerProductListResult(GetProductType(), minimumPrice, maximumPrice));

                #endregion
                #region Step 5
            case 5:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var productDAO = new ProductDAO())
                        if (await productDAO.Read(MsgQuery, false) == null)
                        {
                            _isSkipValidation = true;
                            goto case 4;
                        }
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));

                #endregion
                #region Step 6
            case 6:
                if (!int.TryParse(MsgReply, out var res) || res < 1)
                {
                    return(Recv.Json(RespObj(RespType.Text,
                                             "Số lượng nhập vào không hợp lệ. Vui lòng nhập lại")));
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(MultiResp(RespObj(RespType.Text,
                                                   "Bạn có thể cho mình biết tên đăng nhập trên hệ thống Cutieshop được không ạ?\nNếu chưa có, bạn có thể gõ tên đăng nhập mới để chúng mình tạo tài khoản cho bạn"),
                                           RespUndo())));

                #endregion
                #region Step 7
            case 7:
                if (_isUndoRequested && Storage[MsgId, 6] == null)
                {
                    Storage.StepBack(MsgId);
                    return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));
                }

                //This step receive username first, then the email and address. So we need to keep the username to the storage for further uses, email will be used once in this step and can be queried by DAO easily in the future.
                //Checking null will prevent email from being overwritten to username in Storage

                if (Storage[MsgId, 6] == null)
                {
                    if (!MsgReply.IsPureAscii() || MsgReply.Contains(' '))
                    {
                        return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập tên đăng nhập hợp lệ (không dấu, khoảng cách)")));
                    }
                    Storage.AddOrUpdate(MsgId, 6, MsgReply);
                }

                using (var userDAO = new UserDAO())
                {
                    var user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    //If user is null, create a user, then ask customer their email
                    if (user == null)
                    {
                        Storage.AddOrUpdate(MsgId, 7, "userPassword", NewGuid().ToString().Substring(0, 6));
                        await userDAO.Create(new Auth
                        {
                            Username = Storage[MsgId, 6],
                            Password = Storage[MsgId, 7, "userPassword"]
                        });

                        await userDAO.CreateChild(new User
                        {
                            Username = Storage[MsgId, 6],
                            Email    = string.Empty,
                            Address  = string.Empty
                        });

                        await userDAO.Context.SaveChangesAsync();
                    }

                    user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    if (Storage[MsgId, 7, "fullName"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskFullName"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskFullName", "1");
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (MsgReply.Trim().Count(x => x == ' ') == 0)
                        {
                            return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập đầy đủ họ tên")));
                        }

                        Storage.AddOrUpdate(MsgId, 7, "fullName", MsgReply);
                    }

                    //If email is empty, ask for email
                    if (user.Email == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForEmail"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                        }

                        //Undo handling
                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        //Validate email
                        if (!MsgReply.IsEmail())
                        {
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Email không hợp lệ\nVui lòng nhập lại email"), RespUndo())));
                        }

                        user.Email = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    if (Storage[MsgId, 7, "phoneNo"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                        }

                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", null);

                            if (Storage[MsgId, 7, "isAskForEmail"] != null)
                            {
                                user.Email = "";
                                await userDAO.Context.SaveChangesAsync();

                                return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                            }

                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == "1")
                        {
                            Storage.AddOrUpdate(MsgId, 7, "phoneNo", MsgReply);
                        }
                    }

                    if (_isUndoRequested)
                    {
                        user.Address = "";
                        await userDAO.Context.SaveChangesAsync();

                        Storage.AddOrUpdate(MsgId, 7, "phoneNo", null);
                        Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", null);
                        return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                    }

                    if (user.Address == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForAddress"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", "1");
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin địa chỉ"), RespUndo())));
                        }

                        user.Address = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //Ready to jump into step 8 (if exists) after this
                    Storage.AddOrUpdate(MsgId, 7, null);

                    using (var orderDAO = new OnlineOrderProductDAO(userDAO.Context))
                    {
                        var orderId = NewGuid().ToString();
                        await orderDAO.Create(orderId, Storage[MsgId, 7, "fullName"], user.Address, "10000", user.City, Storage[MsgId, 7, "phoneNo"], user.Email, user.Username, 0);

                        await orderDAO.CreateChild(Storage[MsgId, 4], orderId, int.Parse(Storage[MsgId, 5]));

                        Product buyProd;
                        using (var prdctDAO = new ProductDAO())
                            buyProd = await prdctDAO.Read(Storage[MsgId, 4], false);

                        var mailPrdctTbl = _mailContent.BuyReq.TableRow
                                           .MultiReplace(("{0}", buyProd.Name), ("{1}", buyProd.Description), ("{2}", Storage[MsgId, 5]));

                        var mailBody = _mailContent.BuyReq.Body
                                       .MultiReplace(
                            ("{0}", user.Username),
                            ("{1}", mailPrdctTbl),
                            ("{2}", orderId),
                            ("{3}", (buyProd.Price * int.Parse(Storage[MsgId, 5])).ToString()));

                        MailUtils.Send(user.Email, _mailContent.BuyReq.Subject, mailBody);

                        var reply = $"Mail xác nhận đã được gửi đến {user.Email}. Hãy xác nhận qua mail để hoàn tất đặt hàng nhé!";

                        //Send temporary password if customer create new account
                        if (Storage[MsgId, 7, "userPassword"] != null)
                        {
                            reply = $"Password tạm thời của bạn là {Storage[MsgId, 7, "userPassword"]}. Bạn nên vào trang chủ để thay đổi mật khẩu mặc định\n" + reply;
                        }

                        //Remove data in storage
                        Storage.RemoveId(MsgId);
                        return(Recv.Json(RespObj(RespType.Text, reply)));
                    }
                }
                #endregion
            }

            Storage.RemoveId(MsgId);
            throw new UnhandledChatException();
        }
Beispiel #29
0
        public void procesar(TipoProceso tipoProceso)
        {
            logger.info(string.Format("Ejecutando proceso: {0} ", tipoProceso));
            var          utilSession = new UtilSession();
            classSession session     = null;
            string       cuerpoSMS   = "";

            try
            {
                var fecha = getFechaPorTipoProceso(tipoProceso);

                // Crea una instancia de Service Boleto con la configuración según el proceso
                var service = new ServiceBoleto(tipoProceso, fecha);

                // Obtener todos los boletos Emitidos en el DQB
                var boletosEmitidosDQB = service.ObtenerListaBoletosDQB(tipoProceso);

                // Filtra los boletos que no se encuentren VOID
                var boletosAProcesar = boletosEmitidosDQB.Where(boleto => !boleto.Estado.Equals("VOID")).ToList();

                // Obtener todos los boletos Registrados en el PTA
                var boletosRegistradosPTA = service.obtenerBoletoRegistradosPTA(Configuracion.EsquemaDB.Actual);

                // Consolida los boletos en DQB Activos con los boletos en PTA
                var boletosConsolidados = service.consolidarBoletos(boletosAProcesar, boletosRegistradosPTA);

                session = utilSession.getSession();

                // Crea una instancia del Gestor e inyectar session
                GestorProceso gestorProceso = new GestorProceso(session);

                if (boletosConsolidados.Any())
                {
                    if (tipoProceso == TipoProceso.AVISO_NO_FACTURADOS || tipoProceso == TipoProceso.AVISO_NO_FACTURADOS_AYER)
                    {
                        gestorProceso.ejecutarProceso(new ProcesoAvisoNoFacturado(), boletosConsolidados, fecha);
                        gestorProceso.ejecutarProceso(new ProcesoAvisoNoEnPTA(), boletosConsolidados, fecha);
                    }
                    else if (tipoProceso == TipoProceso.AVISO_ANULACION)
                    {
                        gestorProceso.ejecutarProceso(new ProcesoAvisoAnulacion(), boletosConsolidados);
                    }
                    else if (tipoProceso == TipoProceso.ANULACION && "NM".Equals(Configuracion.empresa))
                    {
                        gestorProceso.ejecutarProceso(new ProcesoAnulacion(), boletosConsolidados);
                    }
                    else if (tipoProceso == TipoProceso.AVISO_VOID_DQB_NO_EN_PTA)
                    {
                        boletosAProcesar = boletosEmitidosDQB.Where(boleto => boleto.Estado.Equals("VOID")).ToList();
                        if (boletosAProcesar.Any())
                        {
                        }
                    }
                }
                cuerpoSMS = string.Format("{0} - {1} - Se ejecuto correctamente el proceso {2} del Robot de Anulaciones", Configuracion.Gds, Configuracion.empresa, tipoProceso);
            }
            catch (Exception ex)
            {
                cuerpoSMS = string.Format("{0} - {1} - Ocurrió un error en el proceso {2} del Robot de Anulaciones, Por favor revisar su mail para más detalles.", Configuracion.Gds, Configuracion.empresa, tipoProceso);
                MailUtils.getInstance().sendMailError(ex, tipoProceso);
                logger.info(string.Format("Ocurrió un error inesperado: {0}", ex.ToString()));
            }
            finally
            {
                utilSession.closeSession(session);
                if (tipoProceso == TipoProceso.AVISO_ANULACION || tipoProceso == TipoProceso.ANULACION)
                {
                    new Utilitario().envioSMS(cuerpoSMS, "ROBOT_AVISO_SABRE", Configuracion.contactosEnvioSMS);
                }
            }
        }
Beispiel #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string SECURE_SECRET      = OnepayCode.SECURE_SECRET;//Hòa: cần thay bằng mã thật từ app_code
            string hashvalidateResult = "";
            // Khoi tao lop thu vien
            VPCRequest conn = new VPCRequest("http://onepay.vn");

            conn.SetSecureSecret(SECURE_SECRET);
            // Xu ly tham so tra ve va kiem tra chuoi du lieu ma hoa
            hashvalidateResult = conn.Process3PartyResponse(Request.QueryString);

            // Lay gia tri tham so tra ve tu cong thanh toan
            String vpc_TxnResponseCode = conn.GetResultField("vpc_TxnResponseCode", "Unknown");
            string amount          = conn.GetResultField("vpc_Amount", "Unknown");
            string localed         = conn.GetResultField("vpc_Locale", "Unknown");
            string command         = conn.GetResultField("vpc_Command", "Unknown");
            string version         = conn.GetResultField("vpc_Version", "Unknown");
            string cardBin         = conn.GetResultField("vpc_Card", "Unknown");
            string orderInfo       = conn.GetResultField("vpc_OrderInfo", "Unknown");
            string merchantID      = conn.GetResultField("vpc_Merchant", "Unknown");
            string authorizeID     = conn.GetResultField("vpc_AuthorizeId", "Unknown");
            string merchTxnRef     = conn.GetResultField("vpc_MerchTxnRef", "Unknown");
            string transactionNo   = conn.GetResultField("vpc_TransactionNo", "Unknown");
            string txnResponseCode = vpc_TxnResponseCode;
            string message         = conn.GetResultField("vpc_Message", "Unknown");

            System.Decimal TongThanhTien = 0;
            String         hoten, sdt, diachi, tinh, quan, maDH, datetime, email;

            DataTable dt = new DataTable();
            DataTable info = new DataTable();

            // Sua lai ham check chuoi ma hoa du lieu
            if (hashvalidateResult == "CORRECTED" && txnResponseCode.Trim() == "0")
            {
                //vpc_Result.Text = "Transaction was paid successful";
                dt            = (DataTable)Session["GioHang"];
                info          = (DataTable)Session["info"];
                hoten         = info.Rows[0]["hoten"].ToString();
                sdt           = info.Rows[0]["sdt"].ToString();
                maDH          = info.Rows[0]["maDH"].ToString();
                TongThanhTien = int.Parse(info.Rows[0]["TongThanhTien"].ToString());
                datetime      = info.Rows[0]["datetime"].ToString();
                email         = info.Rows[0]["email"].ToString();
                diachi        = info.Rows[0]["diachi"].ToString();

                XuLyDonHang.getDonDatHang(2, sdt, hoten, maDH, TongThanhTien, datetime, dt, email, diachi, 0);

                #region xử lý mail

                string smtpUserName = "******";
                string smtpPassword = "******";
                string smtpHost     = "smtp.gmail.com";
                int    smtpPort     = 25;

                string emailTo = email;
                string subject = "Vương quốc son môi - thanh toán quốc tế";
                string body    = string.Format("Xin chào, " + email + Environment.NewLine +
                                               "\n Số tiền bạn đã thanh toán: " + String.Format("{0:0,00}₫", TongThanhTien) + ":" + Environment.NewLine +
                                               "\n Bạn đã thanh toán đơn hàng bằng hình thức thanh toán quốc tế thành công! Đơn hàng đang chờ được duyệt" + Environment.NewLine +
                                               "\n Cảm ơn bạn đã sử dụng dịch vụ của Vương quốc son môi!" + Environment.NewLine +
                                               "\n Chúc bạn có thêm nhiều niềm vui với bưu phẩm của mình <3");

                MailUtils service = new MailUtils();
                bool      kq      = service.Send(smtpUserName, smtpPassword, smtpHost, smtpPort, emailTo, subject, body);
                #endregion

                Session["Giohang"] = null;
                Session["info"]    = null;
                Response.Write("<div class='result'>Đã thanh toán thành công</div>");
            }
            else if (hashvalidateResult == "INVALIDATED" && txnResponseCode.Trim() == "0")
            {
                //vpc_Result.Text = "Transaction is pending";
                //Response.Write("Error description : " + message + "<br/>");
                Response.Write("<div class='result'>Thanh toán đang chờ</div>");
            }
            else
            {
                //vpc_Result.Text = "Transaction was not paid successful";
                //Response.Write("Error description : " + message + "<br/>");
                Response.Write("<div class='result'>Thanh toán không thành công</div>");
            }
        }