コード例 #1
0
        public PersonController()
        {
            var permissionRepository = new PermissionRepository();
            var churchRepository = new ChurchRepository();
            _personRepository = new PersonRepository(permissionRepository, churchRepository);
            var emailSender = new EmailSender(new MessageRepository(), new MessageRecepientRepository(), new MessageAttachmentRepository(), _personRepository);
            var churchEmailTemplateRepository = new ChurchEmailTemplatesRepository();
            var emailService = new EmailService(new UsernamePasswordRepository(permissionRepository), _personRepository, new GroupRepository(), emailSender, new EmailContentService(new EmailContentRepository()), churchEmailTemplateRepository, permissionRepository);
            var uploadPhotoRepository = new PhotoRepository();

            _personService = new PersonService(
                _personRepository,
                new PersonGroupRepository(_personRepository),
                permissionRepository,
                new PersonRoleRepository(),
                new PersonOptionalFieldRepository(),
                new RelationshipRepository(_personRepository),
                new ChurchMatcherRepository(),
                new GroupRepository(),
                new FamilyRepository(uploadPhotoRepository),
                emailService,
                new AddressRepository(),
                uploadPhotoRepository
                );
        }
コード例 #2
0
        public void CanGetListOfPersonEventsForAGroup()
        {
            var eventRepository = MockRepository.GenerateStub<IEventRepository>();
            var eventList = new List<PersonEventDto> { new PersonEventDto(), new PersonEventDto(), new PersonEventDto() };
            var currentPerson = new Person {Permissions = new List<int> {57}};
            eventRepository
                .Expect(e => e.GetPersonEventsForGroup(1, currentPerson))
                .Return(eventList);

            var permissionRepository = new PermissionRepository();
            var personRepository = new PersonRepository(permissionRepository, new ChurchRepository());
            var usernamePasswordRepository = new UsernamePasswordRepository(permissionRepository);
            var groupRepository = new GroupRepository();
            var messageRepository = new MessageRepository();
            var messageRecepientRepository = new MessageRecepientRepository();
            var messageAttachmentRepository = new MessageAttachmentRepository();
            var emailSender = new EmailSender(messageRepository, messageRecepientRepository, messageAttachmentRepository, personRepository);
            var churchEmailTemplatesRepository = new ChurchEmailTemplatesRepository();
            var emailContentRepository = new EmailContentRepository();
            var emailContentService = new EmailContentService(emailContentRepository);
            var emailService = new EmailService(usernamePasswordRepository, personRepository, groupRepository, emailSender, emailContentService, churchEmailTemplatesRepository, permissionRepository);
            IEventService eventService = new EventService(eventRepository, emailService, new BirthdayAndAniversaryRepository());

            var sut = eventService.GetPersonEventsForGroup(1, currentPerson);

            Assert.That(sut.Count(), Is.EqualTo(3));
        }
コード例 #3
0
 public void Send_Mail()
 {
     var result = new EmailSender()
                 .FromHost(smtp)
                 .Credential(sender, senderPass)
                 .FromTo(new Message
                 {
                     From = sender,
                     To = toMail
                 })
                 .Subject("Subject")
                 .Attachment(new Attachment(new MemoryStream(), "filename.***", "mediaType"))
                 .Send();
 }
コード例 #4
0
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.Text = "Document Text";

            var blogPoster = new BlogPoster();
            var blogDelegate = new Document.SendDoc(blogPoster.PostToBlog);
            doc.ReportSendingResult(blogDelegate);

            var emailSender = new EmailSender();
            var emailDelegate = new Document.SendDoc(emailSender.SendEmail);
            doc.ReportSendingResult(emailDelegate);

            Console.ReadLine();
        }
コード例 #5
0
        public EmailSenderService()
        {
            _emailSender = new EmailSender();

            Bus.Initialize(sbc =>
                           	{
                                sbc.UseRabbitMqRouting();
                                sbc.ReceiveFrom("rabbitmq://localhost/timesheeter.emailsenderservice");
                                sbc.Subscribe(handler => handler.Handler<ISendTimeSheet>( msg =>
                                    {
                                        Console.WriteLine("Sending email");
                                    }));

                           	});
        }
コード例 #6
0
        public bool Run()
        {
            bool success = false;
            var schwabClient = new SchwabClient();
            var schwabBalance = schwabClient.GetAvailableBalance();

            var citi = new CitiClient();
            var citiBalance = citi.GetCurrentBalance();

            var data = FormatMessage(schwabBalance, citiBalance);

            var emailSender = new EmailSender();
            success = emailSender.SendEmail(data);

            return success;
        }
コード例 #7
0
 void LogicRuleExecutorOnLogicRuleExecute(object sender, LogicRuleExecuteEventArgs logicRuleExecuteEventArgs) {
     var logicRuleInfo = logicRuleExecuteEventArgs.LogicRuleInfo;
     var emailRule = logicRuleInfo.Rule as EmailRule;
     if (emailRule != null && !logicRuleInfo.InvertCustomization) {
         var modelApplicationEmail = (IModelApplicationEmail) Application.Model;
         var emailTemplateObject = EmailTemplateObject(modelApplicationEmail, emailRule, ObjectSpace);
         var modelSmtpClientContext = modelApplicationEmail.Email.SmtpClientContexts.First(emailTemplate => emailTemplate.GetValue<string>("Id") == emailRule.SmtpClientContext);
         var email = CreateEmail(logicRuleInfo, emailRule, modelSmtpClientContext,emailTemplateObject,modelApplicationEmail);
         if (email!=null) {
             var emailSender = new EmailSender{
                 CreateClientFactory =
                     () => new SmtpClientWrapper(CreateSmtpClient(modelSmtpClientContext))
             };
             emailSender.Send(email);
         }
     }
 }
コード例 #8
0
        public void Send_RazorTemplate_Mail()
        {
            const string template = "Hi @Model.Name @Model.Surname <br/>" +
                                    "Cities list: @foreach(var city in Model.Cities) {<p> @city.Name</p> <p> @city.Code</p>}";
            var model = new
            {
                Name = "Name",
                Surname = "Surname",
                Cities = new[]
                {
                    new
                    {
                        Name = "Adana",
                        Code = "01"
                    },
                    new
                    {
                        Name = "Istanbul",
                        Code = "34"
                    },
                    new
                    {
                        Name = "Izmir",
                        Code = "35"
                    }
                }
            };

            var result = new EmailSender()
                    .FromHost(smtp)
                    .Credential(sender, senderPass)
                    .FromTo(new Message
                    {
                        From = sender,
                        To = toMail
                    })
                    .Subject("Subject")
                    .RazorTemplate(template, model)
                    .Send();

            Console.WriteLine(result);
        }
コード例 #9
0
ファイル: DisasterModule.cs プロジェクト: rsiwady29/FireTower
        public DisasterModule(ICommandDispatcher commandDispatcher)
        {
            Post["/Disasters"] =
                Request =>
                    {
                        var req = this.Bind<CreateNewDisasterRequest>();
                        commandDispatcher.Dispatch(this.UserSession(),
                                                   new CreateNewDisaster(req.LocationDescription,
                                                                         req.Latitude, req.Longitude, req.FirstSeverity));
                        return new Response().WithStatusCode(HttpStatusCode.OK);
                    };

            Post["/SendDisasterByEmail"] =
                Request =>
                    {
                        var emailInfo = this.Bind<SendDisasterByEmailRequest>();
                        try
                        {
                            var _model = new Disaster(DateTime.Parse(emailInfo.CreatedDate),
                                                      emailInfo.LocationDescription,
                                                      double.Parse(emailInfo.Latitude),
                                                      double.Parse(emailInfo.Longitude));
                            var sender =
                                new EmailSender(
                                    new EmailBodyRenderer(
                                        new TemplateProvider(new List<IEmailTemplate>
                                                                 {
                                                                     new DisasterEmailTemplate(
                                                                         new DefaultRootPathProvider())
                                                                 }),
                                        new DefaultViewEngine())
                                    , new EmailSubjectProvider(new List<IEmailSubject> {new DisasterEmailSubject()}),
                                    new MailgunSmtpClient());
                            sender.Send(_model, emailInfo.Email);
                            return new Response().WithStatusCode(HttpStatusCode.OK);
                        }
                        catch (Exception ex)
                        {
                            return new Response().WithStatusCode(HttpStatusCode.NotFound);
                        }
                    };
        }
コード例 #10
0
 public MyRewardsController(RewardService rewardService, FileService fileService, EmailSender emailSender,
                            IAuthorizationService authorizationService, IMapper mapper, ILogger <MyRewardsController> logger)
 {
     _rewardService        = rewardService;
     _fileService          = fileService;
     _emailSender          = emailSender;
     _authorizationService = authorizationService;
     _mapper = mapper;
     _logger = logger;
 }
コード例 #11
0
 public ForgotPasswordModel(UserManager <ApplicationUsers> userManager, EmailSender emailSender, IToastNotification toastNotification)
 {
     _userManager       = userManager;
     _emailSender       = emailSender;
     _toastNotification = toastNotification;
 }
コード例 #12
0
        public static string ReadMarketIntradiaryData(string market_name, int market_id, int utc_time_offset, out bool error, params string[] otherParams)
        {
            error = false;
            DateTime date = DateTime.UtcNow.AddHours(utc_time_offset);

            string status     = "O";
            bool   marketOpen = MarketService.IsMarketOpen(market_id, date, out status);

            if (marketOpen)
            {
                try
                {
                    //switch (market_name)
                    //{
                    //    case "NYSE":
                    //        QuotesFromEOD quotesFromEODny = new QuotesFromEOD();
                    //        quotesFromEODny.SaveQuotesToDB(market_name, market_id, utc_time_offset);
                    //        break;
                    //    case "NASDAQ":
                    //        QuotesFromEOD quotesFromEODna = new QuotesFromEOD();
                    //        quotesFromEODna.SaveQuotesToDB(market_name, market_id, utc_time_offset);
                    //        break;
                    //    case "BCBA":
                    //        QuotesFromBOLSAR quotesFromBolsar = new QuotesFromBOLSAR();
                    //        quotesFromBolsar.SaveQuotesToDB(market_name, market_id, utc_time_offset);
                    //        break;
                    //    default:
                    //        return "Quotes for other markets than NYSE, NASDAQ or BCBA are not implemented";
                    //}
                    return("Quotes Updated");
                }
                catch (Exception ex)
                {
                    error = true;
                    EmailSender.SendErrorUpdatingIntradiary("Message: " + ex.Message + Environment.NewLine + "Source: " + ex.Source + Environment.NewLine + "StackTrace: " + ex.StackTrace + Environment.NewLine + ((ex.InnerException != null) ? "Inner Message: " + ex.InnerException.Message + Environment.NewLine + "Inner Source: " + ex.InnerException.Source + Environment.NewLine + "Inner StackTrace: " + ex.InnerException.StackTrace : ""), market_name, date);
                    return("Error Updating Intradiry: " + ex.Message);
                }
            }
            else
            {
                error = true;
                if (date.Hour == 5 && status == "C")
                {
                    try
                    {
                        QuotesService.ClearIntradiaryDataByMarketID(market_name);
                        //EmailSender.DeletingIntradiaryData("Intradiry Deleted", market_name, date);
                        return("Market Close --> Intradiry Deleted");
                    }
                    catch (Exception ex)
                    {
                        EmailSender.SendErrorClearIntradiaryData("Message: " + ex.Message + Environment.NewLine + "Source: " + ex.Source + Environment.NewLine + "StackTrace: " + ex.StackTrace + Environment.NewLine + ((ex.InnerException != null) ? "Inner Message: " + ex.InnerException.Message + Environment.NewLine + "Inner Source: " + ex.InnerException.Source + Environment.NewLine + "Inner StackTrace: " + ex.InnerException.StackTrace : ""), market_name, date);
                        return("Error deleting Intradiry: " + ex.Message);
                    }
                }
                else
                {
                    //EmailSender.SendMarketCloseEmail(market_name, date, status);
                    return("Market Close");
                }
            }
        }
コード例 #13
0
    /// <summary>
    /// Send e-mail to support.
    /// </summary>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        string result = new Validator()
                        .NotEmpty(txtSubject.Text.Trim(), GetString("Support.SubmiIssue.SubjectEmpty"))
                        .NotEmpty(txtEmail.Text.Trim(), GetString("Support.SubmiIssue.EmailEmpty"))
                        .IsEmail(txtEmail.Text.Trim(), GetString("Support.SubmiIssue.EmailFormat"))
                        .Result;

        if (!string.IsNullOrEmpty(result))
        {
            ShowError(result);
            return;
        }

        EmailMessage message = new EmailMessage
        {
            EmailFormat = EmailFormatEnum.Html,
            From        = txtEmail.Text.Trim(),
            Subject     = txtSubject.Text.Trim(),
            Recipients  = "*****@*****.**"
        };

        StringBuilder sb = new StringBuilder();

        sb.Append("<html><head></head><body>");
        sb.Append(htmlTemplateBody.ResolvedValue);
        sb.Append("<br /><div>=============== System information ==================<br />");
        sb.Append(txtSysInfo.Text.Replace("\r", string.Empty).Replace("\n", "<br />"));
        sb.Append("<br />==============================================</div><br />");
        sb.Append("<div>================ Template type ==================<br />");
        sb.Append(GetEngineInfo());
        sb.Append("<br />");
        sb.Append("=============================================</div>");
        sb.Append("</body></html>");

        message.Body = sb.ToString();

        // Add settings attachment
        if (chkSettings.Checked)
        {
            // Get settings data
            string settings = GetSettingsInfo();
            if (!string.IsNullOrEmpty(settings))
            {
                Stream stream = MemoryStream.New();

                // Put the file content in the stream
                StreamWriter writer = StreamWriter.New(stream, UnicodeEncoding.UTF8);
                writer.Write(settings);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                message.Attachments.Add(new Attachment(stream.SystemStream, "settings.txt", MediaTypeNames.Application.Octet));
            }
        }
        // Add uploaded attachment
        if (fileUpload.HasFile)
        {
            Attachment at = new Attachment(fileUpload.PostedFile.InputStream, fileUpload.FileName, MediaTypeNames.Application.Octet);
            if (at != null)
            {
                message.Attachments.Add(at);
            }
        }

        EmailSender.SendEmail(null, message, true);
        ShowInformation(GetString("Support.Success"));

        ClearForm();
    }
コード例 #14
0
		private void SendChangeEmailConfirmation(string to, string confirmationToken)
		{
			EmailSender email = new EmailSender();
			string fullUrl = this.Url.Action("ConfirmEmailChange", "Account", new { token = confirmationToken }, "http");

			string html = ViewRenderer.RenderViewToString(
			"~/views/email/ChangeEmailTemplate.cshtml",
			fullUrl, true);

			email.SendMail(to, "Email Confirmation", html);
		}
コード例 #15
0
        public static void SaveRealTimeQuote(List <IRealTimeQuote> quotes)
        {
            string connectionString = "";

            using (ctaDBEntities entities = new ctaDBEntities())
            {
                connectionString = entities.Configs.Where(c => c.ConfigName == "UpdateQuotesConectionString").Select(c => c.ConfigValue).First();
            }

            SqlConnection     connection         = new SqlConnection(connectionString);
            List <SqlCommand> commands           = new List <SqlCommand>();
            string            queryString        = $@"INSERT INTO [dbo].[Stock_Quote_Intradiary] ([stock_id],[opening],[prev_closing],[ask],[ask_size],[bid],[bid_size],[change],[change_percent],[last_trade_time],[last_trade_price],[last_trade_size],[last_trade_date],[datetime]) VALUES(@stock_id, @opening, @prev_closing, @ask, @ask_size, @bid, @bid_size, @change, @change_percent, @last_trade_time, @last_trade_price, @last_trade_size, @last_trade_date, @datetime);";
            string            errorProcesingData = string.Empty;
            string            errorSavingData    = string.Empty;

            foreach (IRealTimeQuote quote in quotes)
            {
                try
                {
                    if (quote.opening > 0)
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);

                        SqlParameter sqlParameter = new SqlParameter("@stock_id", SqlDbType.Int);
                        sqlParameter.Value = quote.stock_id;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@opening", SqlDbType.Float);
                        sqlParameter.Value = quote.opening;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@prev_closing", SqlDbType.Float);
                        sqlParameter.Value = quote.prev_closing;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@ask", SqlDbType.Float);
                        sqlParameter.Value = quote.ask;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@ask_size", SqlDbType.Float);
                        sqlParameter.Value = quote.ask_size;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@bid", SqlDbType.Float);
                        sqlParameter.Value = quote.bid;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@bid_size", SqlDbType.Float);
                        sqlParameter.Value = quote.bid_size;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@change", SqlDbType.Float);
                        sqlParameter.Value = quote.change;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@change_percent", SqlDbType.Float);
                        sqlParameter.Value = quote.change_percent;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@last_trade_time", SqlDbType.NVarChar, 20);
                        sqlParameter.Value = quote.last_trade_time;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@last_trade_price", SqlDbType.Float);
                        sqlParameter.Value = quote.last_trade_price;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@last_trade_size", SqlDbType.Decimal);
                        sqlParameter.Value = quote.last_trade_size;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@last_trade_date", SqlDbType.DateTime);
                        sqlParameter.Value = quote.last_trade_date;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@datetime", SqlDbType.DateTime);
                        sqlParameter.Value = quote.datetime;
                        command.Parameters.Add(sqlParameter);

                        commands.Add(command);
                    }
                }
                catch (Exception ex)
                {
                    errorProcesingData += $"Error: {ex.Message}{Environment.NewLine}StockID:{quote.stock_id}{Environment.NewLine}opening={quote.opening}|prev_closing={quote.prev_closing}|ask={quote.ask}|ask_size={quote.ask_size}|bid={quote.bid}|bid_size={quote.bid_size}|change={quote.change}|change_percent={quote.change_percent}|last_trade_time={quote.last_trade_time}|last_trade_price={quote.last_trade_price}|last_trade_size={quote.last_trade_size}|last_trade_date={quote.last_trade_date}|datetime={quote.datetime}|";
                }
            }
            if (!string.IsNullOrEmpty(errorProcesingData))
            {
                EmailSender.SendErrorUpdatingIntradiary(errorProcesingData, "Error Processing Intradiary Data", DateTime.Now);
            }

            using (connection)
            {
                connection.Open();
                foreach (SqlCommand command in commands)
                {
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        errorSavingData += $"Error:{ex.Message}{Environment.NewLine}";
                        foreach (SqlParameter param in command.Parameters)
                        {
                            errorSavingData += $"{param.ParameterName}={param.Value}|";
                        }
                    }
                }
                connection.Close();
            }
            if (!string.IsNullOrEmpty(errorSavingData))
            {
                EmailSender.SendErrorUpdatingIntradiary(errorProcesingData, "Error Saving Intradiary Data", DateTime.Now);
            }
        }
コード例 #16
0
        public ActionResult DisqualifyApplication(int?id)
        {
            LocationalClearance clearance = db.LocationalClearance.Find(id);

            if (clearance == null)
            {
                return(HttpNotFound());
            }
            clearance.Status          = "Denied";
            db.Entry(clearance).State = EntityState.Modified;
            db.SaveChanges();
            EmailSender.SendMail(clearance.EmailAddress, "Locational Clearance Application : Denied", EmailSender.LocationalClearanceDeniedTemplate());
            return(RedirectToAction("Index"));
        }
コード例 #17
0
 public void It_should_send_registration_emails_to_the_event_organizer()
 {
     EmailSender.AssertWasCalled(x => x.Send(null),
                                 o => o.Constraints(Is.Matching <EmailTemplate>(t => t.From.Equals("*****@*****.**") &&
                                                                                t.To.Equals("*****@*****.**"))));
 }
コード例 #18
0
        public void SendEmail()
        {
            EmailSender sender = new EmailSender();

            sender.sendEMailThroughGmail(this.Email, this.Topic, this.Content);
        }
コード例 #19
0
        public ActionResult ApproveApplication(int?id)
        {
            LocationalClearance clearance = db.LocationalClearance.Find(id);
            List <Fee>          fees      = db.Fees.Include(p => p.ApplicationType).Where(p => p.ApplicationType.Description.Contains("Locational")).ToList();

            if (clearance == null)
            {
                return(HttpNotFound());
            }

            clearance.Status           = "Approved";
            clearance.TotalPayment     = fees.Sum(f => f.Price);
            clearance.PaymentReference = base.RandomString();
            db.Entry(clearance).State  = EntityState.Modified;
            db.SaveChanges();

            EmailSender.SendMail(clearance.EmailAddress, "Locational Clearance Application : Approved", EmailSender.LocationalClearanceApprovedTemplate(clearance, fees));
            return(RedirectToAction("Index"));
        }
コード例 #20
0
ファイル: Create.cs プロジェクト: cartomatic/MapHive.Server
        /// <summary>
        /// Creates a new user account in both MembershipReboot database and in the MapHive meta database;
        /// sends out a confirmation email if email account and template are provided
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TAccount"></typeparam>
        /// <param name="userAccountService"></param>
        /// <param name="dbCtx"></param>
        /// <param name="emailAccount"></param>
        /// <param name="emailTemplate"></param>
        /// <returns></returns>
        protected internal virtual async Task <T> CreateAsync <T, TAccount>(DbContext dbCtx, UserAccountService <TAccount> userAccountService, IEmailAccount emailAccount = null, IEmailTemplate emailTemplate = null)
            where T : MapHiveUserBase
            where TAccount : RelationalUserAccount
        {
            T output;

            //need to validate the model first
            await ValidateAsync(dbCtx);

            //make sure the email is ALWAYS lower case
            Email = Email.ToLower();

            //check if the email is already used or not; throw validation feedback exception if so
            //Note - could do it in the mh meta, but both dbs must be in sync anyway
            var emailInUse = userAccountService.GetByEmail(Email) != null;

            if (emailInUse)
            {
                throw Validation.Utils.GenerateValidationFailedException(nameof(Email), ValidationErrors.EmailInUse);
            }

            //user account exists in two places - mbr and mh databases. Therefore need to handle them both properly wrapped into transactions

            DbContext mbrDbCtx = GetMembershipRebootDbCtx(userAccountService);

            System.Data.Common.DbTransaction mbrTrans = null;

            System.Data.Common.DbTransaction mhTrans = null;


            //since this method wraps the op on 2 dbs into transactions, it must handle connections manually and take care of closing it aftwerwards
            //it is therefore required to clone contexts with independent conns so the base contexts can be reused
            var clonedMhDbCtx  = dbCtx.Clone(contextOwnsConnection: false);
            var clonedMbrDbCtx = mbrDbCtx.Clone(false);

            try
            {
                //open the connections as otherwise will not be able to begin transaction
                await clonedMbrDbCtx.Database.Connection.OpenAsync();

                await clonedMhDbCtx.Database.Connection.OpenAsync();

                //begin the transaction and set the transaction object back on the db context so it uses it
                mbrTrans = clonedMbrDbCtx.Database.Connection.BeginTransaction();
                clonedMbrDbCtx.Database.UseTransaction(mbrTrans);

                mhTrans = clonedMhDbCtx.Database.Connection.BeginTransaction();
                clonedMhDbCtx.Database.UseTransaction(mhTrans);


                //first create a membership reboot account
                //wire up evt too, to intercept what mbr is trying to say...
                AccountCreatedEvent <TAccount> e = null;

                userAccountService.Configuration.AddEventHandler(new MembershipRebootEventHandlers.AccountCreatedEventHandler <TAccount>(
                                                                     (evt) =>
                {
                    e = evt;
                }));
                var newMbrAccount = userAccountService.CreateAccount(this.Email, Cartomatic.Utils.Crypto.Generator.GenerateRandomString(10), this.Email);

                //so can next pass some data to the mh meta user object
                this.Uuid = newMbrAccount.ID;

                //mbr work done, so can create the user within the mh metadata db
                output = await base.CreateAsync <T>(clonedMhDbCtx);

                //looks like we're good to go, so can commit
                mbrTrans.Commit();
                mhTrans.Commit();


                var opFeedback = new Dictionary <string, object>
                {
                    { nameof(e.InitialPassword), e.InitialPassword },
                    { nameof(e.VerificationKey), e.VerificationKey }
                };

                //if email related objects have been provided, send the account created email
                if (emailAccount != null && emailTemplate != null)
                {
                    EmailSender.Send(
                        emailAccount, emailTemplate.Prepare(opFeedback), Email
                        );
                }

                //finally the user created event
                UserCreated?.Invoke(
                    this,
                    new Events.OpFeedbackEventArgs
                {
                    OperationFeedback = opFeedback
                }
                    );
            }
            catch (Exception ex)
            {
                mbrTrans?.Rollback();
                mhTrans?.Rollback();

                throw Validation.Utils.GenerateValidationFailedException(ex);
            }
            finally
            {
                //try to close the connections as they were opened manually and therefore may not have been closed!
                clonedMhDbCtx.Database.Connection.CloseConnection(dispose: true);
                clonedMbrDbCtx.Database.Connection.CloseConnection(dispose: true);

                mbrTrans?.Dispose();
                mhTrans?.Dispose();
            }

            return(output);
        }
コード例 #21
0
        public async Task <IActionResult> Payment(ShoppingCartVM model)
        {
            if (!ModelState.IsValid)
            {
                return(NotFound());
            }

            List <CartVM> carts          = model.Cart;
            List <String> aankomststeden = new List <String>();
            List <Hotel>  hotels         = new List <Hotel>();

            // opvragen UserId en email
            string userID    = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            string userEmail = User.FindFirst(ClaimTypes.Name).Value;

            // opvragen cartlist
            ShoppingCartVM cartList = HttpContext.Session.GetObject <ShoppingCartVM>("ShoppingCart");

            try
            {
                Boeking boeking;
                var     amount  = cartList.Cart.Count();
                var     begin   = "<h2>Hallo " + userEmail + "</h2>" + "<p>U heeft " + amount + " reizen besteld.</p>"; // begin string voor email
                var     tickets = "<b>Your tickets:</b>";                                                               // begin voor alle tickets

                foreach (CartVM cart in carts)
                {
                    // create order object
                    boeking             = new Boeking();
                    boeking.UserId      = userID;
                    boeking.ReisId      = cart.ReisId;
                    boeking.Status      = "Betaald";
                    boeking.Datecreated = DateTime.UtcNow;

                    boekingService.Create(boeking);

                    aankomststeden.Add(cart.AankomstStad);

                    // reis in email steken
                    tickets += "<p>Ticket: " + cart.ReisId + " voor " + cart.Naam + " van " + cart.VertrekStad + " naar " + cart.AankomstStad + "</p>";
                }


                // send email
                var         body = string.Format(begin + tickets);
                EmailSender mail = new EmailSender();
                await mail.SendEmailAsync(userEmail, "VivesTrein - Ticket(s)", body);


                // zoek hotels voor aankomststad
                foreach (String stadnaam in aankomststeden)
                {
                    IList <Hotel> foundHotels = hotelService.GetHotelsByStadName(stadnaam);
                    foreach (Hotel hotel in foundHotels)
                    {
                        hotels.Add(hotel);
                    }
                }

                // empty shoppingcart
                cartList = null;
                HttpContext.Session.SetObject("ShoppingCart", cartList);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }

            return(View(hotels));
        }
コード例 #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ArrayList products = new ArrayList();
            int otcSiteMemberId = Convert.ToInt32(Request.Form["user1"]);
            int otcSalesOrderId = Convert.ToInt32(Request.Form["user2"]);
            int result = 0;
            string authCode = "111111";
            string responseMessage = "Denied";
            string avsData = "YYY";
            string pnrRef = "VPCE3F1D15B1";
            //string cardNumber       = Request.Form["CARDNUM"];

            OTCVerisignTransaction tran = new OTCVerisignTransaction();
            OTCSalesOrder order = new OTCSalesOrder(otcSalesOrderId);

            tran.AuthCode = authCode.ToString();
            tran.OTCSalesOrderId = otcSalesOrderId;
            tran.OTCSiteMemberId = otcSiteMemberId;
            tran.AVSData = avsData;
            tran.Cost = order.TotalCost;
            tran.PNRRef = pnrRef;
            tran.ResponseMessage = responseMessage;
            tran.Result = result;
            tran.Add();

            if (responseMessage.ToLower() == "approved")
            {
                string mailBody = OTCSalesOrder.GetEmailProductString(order.OTCSalesOrderId);

                EmailSender mail = new EmailSender();

                String subject = "Order Confirmation - Interceuticals Order " + order.OTCSalesOrderId;
                String notifyEmails = "*****@*****.**";

                mail.AddEmailAddresses(notifyEmails);
                String error = mail.SendEmail(subject, mailBody);

                if (error == "")
                    Response.Write("Successfully sent email.<br>");
                else
                    Response.Write("Error in sending email.  " + error);

                OTC.Web.Promotion.OTCPromotion pr = new OTC.Web.Promotion.OTCPromotion(order.OTCPromotionId);
                pr.AddPromotionUsage(order.OTCSiteMemberId, order.OTCSalesOrderId);

                try
                {
                    //HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("https://loc1.hitsprocessor.com/confirmation.asp?acct=interceut1&type=60682&s=1&uniqueId=" + order.OTCSalesOrderId + "&orderAmount=" + order.OrderCost);
                    //HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    //Response.Write("hit processesor o.k. <br>");
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("http://*****:*****@cox.net";

                    mail.AddEmailAddresses(notifyEmails);
                    mail.SendEmail(subject, mailBody);

                }
            }
            else
                setAbandoned(tran.OTCSiteMemberId);
        }
コード例 #23
0
        public async Task <IActionResult> AddUser(RemotelyUser currentUser)
        {
            if (!currentUser.IsAdministrator)
            {
                return(RedirectToPage("Index"));
            }

            if (ModelState.IsValid)
            {
                if (!DataService.DoesUserExist(Input.UserEmail))
                {
                    var result = await DataService.CreateUser(Input.UserEmail, Input.IsAdmin, currentUser.OrganizationID);

                    if (result)
                    {
                        var user = DataService.GetUserByName(Input.UserEmail);

                        await UserManager.ConfirmEmailAsync(user, await UserManager.GenerateEmailConfirmationTokenAsync(user));

                        StatusMessage = "User account created.";
                        return(RedirectToPage());
                    }
                    else
                    {
                        ModelState.AddModelError("CreateUser", "Failed to create user account.");
                        return(Page());
                    }
                }
                else
                {
                    var invite = new Invite()
                    {
                        InvitedUser = Input.UserEmail,
                        IsAdmin     = Input.IsAdmin
                    };
                    var newInvite = DataService.AddInvite(currentUser.OrganizationID, invite);

                    var inviteURL   = $"{Request.Scheme}://{Request.Host}/Invite?id={newInvite.ID}";
                    var emailResult = await EmailSender.SendEmailAsync(invite.InvitedUser, "Invitation to Organization in Remotely",
                                                                       $@"<img src='https://remotely.one/media/Remotely_Logo.png'/>
                            <br><br>
                            Hello!
                            <br><br>
                            You've been invited to join an organization in Remotely.
                            <br><br>
                            You can join the organization by <a href='{HtmlEncoder.Default.Encode(inviteURL)}'>clicking here</a>.",
                                                                       currentUser.OrganizationID);

                    if (emailResult)
                    {
                        StatusMessage = "Invitation sent.";
                    }
                    else
                    {
                        StatusMessage = "Error sending invititation email.";
                    }

                    return(RedirectToPage());
                }
            }
            return(Page());
        }
コード例 #24
0
 private void OnSend()
 {
     EmailSender.Send(Trader.email, Trader.pass, Recipient, Subject, Content, AttachedFiles);
 }
コード例 #25
0
ファイル: MyPageCommon.cs プロジェクト: kin0428/Splg
        public static void SendMail(long memberID, string title, string body)
        {
            var com = new ComEntities();
            using (var transaction = com.Database.BeginTransaction())
            {

                //send mail
                var emailSender = new EmailSender();

                try
                {
                    string email = (from m in com.Member where m.MemberId == memberID select m.Mail).FirstOrDefault();

                    string result = emailSender.SendEmail2(email, body, title, null);

                    if (result.Equals(Constants.EMAIL_SEND))
                    {
                        List<MailDeliverCond> mailTypeList = new List<MailDeliverCond>();
                        foreach (var item in com.MailDeliverCondMaster)
                        {
                            // Set value for new row in MailDeliverCond table
                            var newMailCondRow = new MailDeliverCond
                            {
                                MemberID = memberID,
                                MailDelivCondID = item.MailDelivCondID,
                                CreatedDate = System.DateTime.Now
                            };
                            mailTypeList.Add(newMailCondRow);
                        }
                        //Insert to MailDeliverCond table
                        com.MailDeliverCond.AddRange(mailTypeList);
                        com.SaveChanges();

                    }
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                }
            }
        }
コード例 #26
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        // Validate form entries
        string errorMessage = ValidateForm();

        if (!String.IsNullOrEmpty(errorMessage))
        {
            // Display error message
            ShowError(errorMessage);
            return;
        }

        try
        {
            GroupInfo group = new GroupInfo();
            group.GroupDisplayName    = txtDisplayName.Text;
            group.GroupDescription    = txtDescription.Text;
            group.GroupAccess         = GetGroupAccess();
            group.GroupSiteID         = mSiteId;
            group.GroupApproveMembers = GetGroupApproveMembers();
            // Automatic code name can be set after display name + site id is set
            group.Generalized.EnsureCodeName();

            // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
            var user = MembershipContext.AuthenticatedUser;

            if (user != null)
            {
                group.GroupCreatedByUserID = user.UserID;

                if ((!RequireApproval) || (CurrentUserIsAdmin()))
                {
                    group.GroupApprovedByUserID = user.UserID;
                    group.GroupApproved         = true;
                }
            }

            // Save Group in the database
            GroupInfoProvider.SetGroupInfo(group);

            // Create group admin role
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.RoleDisplayName          = "Group admin";
            roleInfo.RoleName                 = group.GroupName + "_groupadmin";
            roleInfo.RoleGroupID              = group.GroupID;
            roleInfo.RoleIsGroupAdministrator = true;
            roleInfo.SiteID = mSiteId;
            // Save group admin role
            RoleInfoProvider.SetRoleInfo(roleInfo);

            if (user != null)
            {
                // Set user as member of group
                GroupMemberInfo gmi = new GroupMemberInfo();
                gmi.MemberUserID           = user.UserID;
                gmi.MemberGroupID          = group.GroupID;
                gmi.MemberJoined           = DateTime.Now;
                gmi.MemberStatus           = GroupMemberStatus.Approved;
                gmi.MemberApprovedWhen     = DateTime.Now;
                gmi.MemberApprovedByUserID = user.UserID;

                // Save user as member of group
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                // Set user as member of admin group role
                UserRoleInfo userRole = new UserRoleInfo();
                userRole.UserID = user.UserID;
                userRole.RoleID = roleInfo.RoleID;

                // Save user as member of admin group role
                UserRoleInfoProvider.SetUserRoleInfo(userRole);
            }

            // Clear user session a request
            MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);
            MembershipContext.AuthenticatedUser = null;

            string culture = CultureHelper.EnglishCulture.ToString();
            if (DocumentContext.CurrentDocument != null)
            {
                culture = DocumentContext.CurrentDocument.DocumentCulture;
            }

            // Copy document
            errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                // Display error message
                ShowError(errorMessage);
                return;
            }

            // Create group forum
            if (CreateForum)
            {
                CreateGroupForum(group);

                // Create group forum search index
                if (CreateSearchIndexes)
                {
                    CreateGroupForumSearchIndex(group);
                }
            }

            // Create group media library
            if (CreateMediaLibrary)
            {
                CreateGroupMediaLibrary(group);
            }

            // Create search index for group documents
            if (CreateSearchIndexes)
            {
                CreateGroupContentSearchIndex(group);
            }

            // Display information on success
            ShowConfirmation(GetString("group.group.createdinfo"));

            // If URL is set, redirect user to specified page
            if (!String.IsNullOrEmpty(RedirectToURL))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL))));
            }

            // After registration message
            if ((RequireApproval) && (!CurrentUserIsAdmin()))
            {
                ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText);

                // Send approval email to admin
                if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                {
                    var siteName = SiteContext.CurrentSiteName;

                    // Create the message
                    EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", siteName);
                    if (eti != null)
                    {
                        MacroResolver resolver = MacroContext.CurrentResolver;
                        resolver.SetAnonymousSourceData(group);
                        resolver.SetNamedSourceData("Group", group);

                        EmailMessage message = new EmailMessage
                        {
                            From       = SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendEmailNotificationsFrom"),
                            Recipients = SendWaitingForApprovalEmailTo
                        };

                        // Send the message using email engine
                        EmailSender.SendEmailWithTemplateText(siteName, message, eti, resolver, false);
                    }
                }
            }
            else
            {
                string groupPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                string url       = String.Empty;

                if (!String.IsNullOrEmpty(groupPath))
                {
                    url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                }
                ShowConfirmation(String.Format(SuccessfullRegistrationText, url));
            }

            // Hide form
            if (HideFormAfterRegistration)
            {
                plcForm.Visible = false;
            }
            else
            {
                ClearForm();
            }
        }
        catch (Exception ex)
        {
            // Display error message
            ShowError(GetString("general.saveerror"), ex.Message);
        }
    }
コード例 #27
0
 public void Handle(DispatchOrderCommand order)
 {
     Logger.InfoFormat("Order received! To address: {0}", order.AddressTo);
     EmailSender.SendEmailToDispatch(order);
     bus.Reply <IOrderDispatchedMessage>(e => {});
 }
コード例 #28
0
        public ActionResult CreateOrder(CreateOrderViewModel model)
        {
            ResponseModel <OrderSimpleViewModel> response = null;

            var orderService = this.Service <IOrderService>();

            var fieldService = this.Service <IFieldService>();

            var userService = this.Service <IAspNetUserService>();

            DateTime startTime = new DateTime();

            DateTime endTime = new DateTime();

            DateTime playDate = new DateTime();

            try
            {
                startTime = DateTime.ParseExact(model.StartTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

                endTime = DateTime.ParseExact(model.EndTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

                playDate = DateTime.ParseExact(model.PlayDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }
            catch (Exception)
            {
                response = ResponseModel <OrderSimpleViewModel> .CreateErrorResponse("Đặt sân thất bại", "Lỗi định dạng thời gian");

                return(Json(response));
            }

            if (!CheckTimeValid(model.FieldId, startTime.TimeOfDay, endTime.TimeOfDay))
            {
                response = ResponseModel <OrderSimpleViewModel> .CreateErrorResponse("Đặt sân thất bại", "Thời gian không nằm trong các khung giờ");

                return(Json(response));
            }
            else if (!CheckOrderTime(model.FieldId, startTime.TimeOfDay, endTime.TimeOfDay, playDate, playDate))
            {
                response = ResponseModel <OrderSimpleViewModel> .CreateErrorResponse("Đặt sân thất bại", "Sân đặt được đặt vào thời gian này");

                return(Json(response));
            }
            double price = CalculatePrice(model.FieldId, startTime.TimeOfDay, endTime.TimeOfDay);

            try
            {
                //Get current user info
                var user = userService.FindUser(model.UserId);

                //Create order info
                String orderCode = DateTime.Now.ToString("yyyyMMddHHmmss");

                Order order = new Order();

                order.FieldId    = model.FieldId;
                order.UserId     = model.UserId;
                order.StartTime  = startTime;
                order.EndTime    = endTime;
                order.CreateDate = DateTime.Now;
                order.Price      = price;
                order.Note       = model.Note;
                order.PayerName  = model.PayerName;
                order.PayerEmail = model.PayerEmail;
                order.PayerPhone = model.PayerPhone;
                order.Status     = (int)OrderStatus.Pending;
                order.OrderCode  = orderCode;
                order.QRCodeUrl  = Utils.GenerateQRCode(orderCode, QRCodeGenerator.ECCLevel.Q);
                var transdate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                order.TransactionTime = DateTime.Parse(transdate);

                if (model.PaidType == (int)OrderPaidType.ChosePayOnline)
                {
                    order.PaidType = (int)OrderPaidType.ChosePayOnline;
                }
                if (model.PaidType == (int)OrderPaidType.ChosePayByCash)
                {
                    order.PaidType = (int)OrderPaidType.ChosePayByCash;
                }


                //Create Noti
                var field = fieldService.FirstOrDefaultActive(p => p.Id == order.FieldId);
                var noti  = new Notification();
                noti.UserId  = field.Place.UserId;
                noti.Message = user.UserName + " đã đặt sân tại " + field.Name;
                noti.Title   = "Đơn hàng mới";
                noti.Type    = (int)NotificationType.Order;
                noti.Active  = true;
                order.Notifications.Add(noti);


                //Save Order
                order = orderService.CreateOrder(order);


                //Send Email
                string subject = "[SSN] - Thông tin đặt sân";
                string body    = "Hi <strong>" + user.UserName + "</strong>" +
                                 ",<br/><br/>Bạn đã đặt sân: " + field.Name + "<br/> Thời gian: " + order.StartTime.ToString("HH:mm") + " - " +
                                 order.EndTime.ToString("HH:mm") + ", ngày " + order.StartTime.ToString("dd/MM/yyyy") +
                                 "<br/> Giá tiền : " + order.Price + " đồng" +
                                 "<br/> <strong>Mã đặt sân của bạn : " + order.OrderCode + "</strong>" +
                                 "<br/><img src='" + Utils.GetHostName() + order.QRCodeUrl + "'>" +
                                 "<br/> Cảm ơn bạn đã sử dụng dịch vụ của SSN. Chúc bạn có những giờ phút thoải mái chơi thể thao!";
                EmailSender.Send(Setting.CREDENTIAL_EMAIL, new string[] { user.Email }, null, null, subject, body, true);

                OrderSimpleViewModel result = PrepareOrderSimpleViewModel(order);

                response = new ResponseModel <OrderSimpleViewModel>(true, "Đặt sân thành công", null, result);


                //Fire base noti
                List <string> registrationIds = GetToken(noti.UserId);

                //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ");

                NotificationModel Amodel = Mapper.Map <NotificationModel>(PrepareNotificationCustomViewModel(noti));

                if (registrationIds != null && registrationIds.Count != 0)
                {
                    Android.Notify(registrationIds, null, Amodel);
                }

                //SignalR Noti
                var notiService = this.Service <INotificationService>();
                NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(noti));

                // Get the context for the Pusher hub
                IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>();

                // Notify clients in the group
                hubContext.Clients.User(notiModelR.UserId).send(notiModelR);
            }
            catch (Exception)
            {
                response = ResponseModel <OrderSimpleViewModel> .CreateErrorResponse("Đặt sân thất bại", systemError);
            }

            return(Json(response));
        }
コード例 #29
0
        public static void SaveHistoricalQuote(List <IHistoricalQuote> quotes)
        {
            string connectionString = "";

            using (ctaDBEntities entities = new ctaDBEntities())
            {
                connectionString = entities.Configs.Where(c => c.ConfigName == "UpdateQuotesConectionString").Select(c => c.ConfigValue).First();
            }

            SqlConnection     connection         = new SqlConnection(connectionString);
            List <SqlCommand> commands           = new List <SqlCommand>();
            string            queryString        = $@"IF NOT EXISTS(SELECT 1 FROM Stock_Quote WHERE stock_id = @stock_id AND date_round = CONVERT(date,@date_round)) BEGIN INSERT INTO [dbo].[Stock_Quote] ([stock_id],[opening],[closing],[minimun],[maximun],[volume],[date_round],[adj_close])VALUES(@stock_id, @opening, @closing, @minimun, @maximun, @volume, @date_round, @adj_close); END ELSE BEGIN UPDATE [dbo].[Stock_Quote] SET [opening] = @opening, [closing] = @closing, [minimun] = @minimun, [maximun] = @maximun, [volume] = @volume, [date_round] = @date_round, [adj_close] = @adj_close WHERE [stock_id] = @stock_id AND date_round = CONVERT(date, @date_round); END";
            string            errorProcesingData = string.Empty;
            string            errorSavingData    = string.Empty;

            foreach (IHistoricalQuote quote in quotes)
            {
                try
                {
                    if (quote.opening > 0 && quote.closing > 0 && quote.maximun > 0 && quote.minimun > 0)
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);

                        SqlParameter sqlParameter = new SqlParameter("@stock_id", SqlDbType.Int);
                        sqlParameter.Value = quote.stock_id;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@opening", SqlDbType.Float);
                        sqlParameter.Value = quote.opening;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@closing", SqlDbType.Float);
                        sqlParameter.Value = quote.closing;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@minimun", SqlDbType.Float);
                        sqlParameter.Value = quote.minimun;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@maximun", SqlDbType.Float);
                        sqlParameter.Value = quote.maximun;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@volume", SqlDbType.Decimal);
                        sqlParameter.Value = quote.volume;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@date_round", SqlDbType.DateTime);
                        sqlParameter.Value = quote.date_round;
                        command.Parameters.Add(sqlParameter);

                        sqlParameter       = new SqlParameter("@adj_close", SqlDbType.Float);
                        sqlParameter.Value = quote.adj_close;
                        command.Parameters.Add(sqlParameter);

                        commands.Add(command);
                    }
                }
                catch (Exception ex)
                {
                    errorProcesingData += $"Error: {ex.Message}{Environment.NewLine}StockID:{quote.stock_id}{Environment.NewLine}opening={quote.opening}|closing={quote.closing}|minimun={quote.minimun}|maximun={quote.maximun}|volume={quote.volume}|date_round={quote.date_round}|adj_close={quote.adj_close}|";
                }
            }
            if (!string.IsNullOrEmpty(errorProcesingData))
            {
                EmailSender.SendErrorUpdatingIntradiary(errorProcesingData, "Error Processing Historical Data", DateTime.Now);
            }

            using (connection)
            {
                connection.Open();
                foreach (SqlCommand command in commands)
                {
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        errorSavingData += $"Error:{ex.Message}{Environment.NewLine}";
                        foreach (SqlParameter param in command.Parameters)
                        {
                            errorSavingData += $"{param.ParameterName}={param.Value}|";
                        }
                    }
                }
                connection.Close();
            }
            if (!string.IsNullOrEmpty(errorSavingData))
            {
                EmailSender.SendErrorUpdatingIntradiary(errorProcesingData, "Error Saving Historical Data", DateTime.Now);
            }
        }
コード例 #30
0
ファイル: HomeController.cs プロジェクト: syeremy/nservicebus
 public ActionResult Confirm(Order order)
 {
     EmailSender.SendEmailToDispatch(order);
     return(View());
 }
コード例 #31
0
 public DeliveryService(IUnitOfWork unitOfWork, IMapper mapper, EmailSender emailSender)
 {
     _unitOfWork  = unitOfWork;
     _mapper      = mapper;
     _emailSender = emailSender;
 }
コード例 #32
0
 public ContactModel(EmailSender emailSender)
 {
     EmailSender = emailSender;
 }
コード例 #33
0
    /// <summary>
    /// Sends new registration notification e-mail to administrator.
    /// </summary>
    private void SendRegistrationNotification(UserInfo ui)
    {
        SiteInfo currentSite = CMSContext.CurrentSite;

        // Notify administrator
        if ((ui != null) && (currentSite != null) && (this.ShoppingCartControl.SendNewRegistrationNotificationToAddress != ""))
        {
            EmailTemplateInfo mEmailTemplate = null;
            if (!ui.UserEnabled)
            {
                mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSite.SiteName);
            }
            else
            {
                mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSite.SiteName);
            }

            EventLogProvider ev = new EventLogProvider();

            if (mEmailTemplate == null)
            {
                // Email template not exist
                ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
            }

            // Initialize email message
            EmailMessage message = new EmailMessage();
            message.EmailFormat = EmailFormatEnum.Default;

            message.From    = ECommerceSettings.SendEmailsFrom(currentSite.SiteName);
            message.Subject = GetString("RegistrationForm.EmailSubject");

            message.Recipients = this.ShoppingCartControl.SendNewRegistrationNotificationToAddress;
            message.Body       = mEmailTemplate.TemplateText;

            // Init macro resolving
            string[,] replacements = new string[4, 2];
            replacements[0, 0]     = "firstname";
            replacements[0, 1]     = ui.FirstName;
            replacements[1, 0]     = "lastname";
            replacements[1, 1]     = ui.LastName;
            replacements[2, 0]     = "email";
            replacements[2, 1]     = ui.Email;
            replacements[3, 0]     = "username";
            replacements[3, 1]     = ui.UserName;

            ContextResolver resolver = CMSContext.CurrentResolver;
            resolver.SourceParameters = replacements;

            try
            {
                // Add template metafiles to e-mail
                MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                // Send e-mail
                EmailSender.SendEmailWithTemplateText(currentSite.SiteName, message, mEmailTemplate, resolver, false);
            }
            catch
            {
                // Email sending failed
                ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
            }
        }
    }
コード例 #34
0
        private ApplicationDbContext _context; // databasen

        public ChatController(ApplicationDbContext context)
        {
            _context    = context;
            emailSender = new EmailSender();
        }
コード例 #35
0
 private void SendEmailToRequester()
 {
     EmailSender.Send(_presenter.GetUser(_presenter.CurrentMaintenanceRequest.AppUser.Id).Email, "Maintenance Request ", "Your Maintenance Request with Maintenance Request No. - '" + (_presenter.CurrentMaintenanceRequest.RequestNo).ToUpper() + "' was Completed.");
 }
コード例 #36
0
    /// <summary>
    /// Takes all of the data filled out for the study and either inserts or updates it into the database.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnFinished_Click(object sender, EventArgs e)
    {
        //Check that the name and description are filled in.
        if (tbName.Text.Equals(string.Empty) || tbDescription.Text.Equals(string.Empty)) {
            lblError.Text = "Please fill out the necessary fields.";
            lblError.Visible = true;
            return;
        }
        lblError.Visible = false;

        int expired = Convert.ToInt32(cbStdExpired.Checked);
        Researcher res = (Researcher)Session["user"];
        int studyID = -1; //-1 means that it hasn't been set yet. Only a new study should have the value of -1, otherwise it should be the ID of the study in the database

        //check to see if we are editing or creating a study
        if (isEdit) {
            studyID = Convert.ToInt32(Request.QueryString["study_id"]);
        }

        //Create a study object with all of its attributes filled out from the forms that the user entered
        study = new Study(studyID, tbName.Text, tbDescription.Text, tbIncentive.Text, DateTime.Now, Convert.ToBoolean(expired), res.UserID, study.Qualifiers);

        finishStudy(study);

        //Send an email A notification email out to all the participants that a new study is ready
        if (!isEdit) {
            EmailSender mailSender = new EmailSender();
            List<string> recipients = DAL.GetRecipientEmails();
            string subject = "New research studies are available!";
            StringBuilder body = new StringBuilder("Please log on to the Study Participant Portal to check out new studies!");
            mailSender.sendEmail("*****@*****.**", recipients, subject, body);

            mailSender = null;
            body = null;
        }

        Response.Redirect("StudyForm.aspx?study_id=" + study.StudyID);
    }
コード例 #37
0
        public IActionResult InvoiceComplete()
        {
            try
            {
                PurchaseForm purchaseForm = JsonConvert.DeserializeObject <PurchaseForm>(TempData["purchaseForm"].ToString());
                EmailSender  email        = new EmailSender(_smtpSettings);

                if (purchaseForm.PersonalInformation.PaymentMethod == "Paypal")
                {
                    PayPalV2.captureOrder(purchaseForm.PayPalCapture);
                }

                purchaseForm = PurchaseOrderRepository.Add(purchaseForm);
                if (purchaseForm.Discount != null && purchaseForm.Discount.SingleUse)
                {
                    DiscountModelRepository.SetNotInUse(purchaseForm.Discount);
                }

                var bot = new DiscordBot();
                bot.RunAsync(purchaseForm).GetAwaiter().GetResult();


                string emailbody = string.Empty;
                switch (purchaseForm.PurchaseType)
                {
                case PurchaseTypeEnum.PurchaseType.SoloBoosting:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderSoloEmail", purchaseForm).Result;
                    break;

                case PurchaseTypeEnum.PurchaseType.DuoBoosting:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderDuoEmail", purchaseForm).Result;
                    break;

                case PurchaseTypeEnum.PurchaseType.WinBoosting:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderWinBoostEmail", purchaseForm).Result;
                    break;

                case PurchaseTypeEnum.PurchaseType.PlacementMatches:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderPlacementMatchesEmail", purchaseForm).Result;
                    break;

                case PurchaseTypeEnum.PurchaseType.TFTPlacement:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderTFTPlacementMatchesEmail", purchaseForm).Result;
                    break;

                case PurchaseTypeEnum.PurchaseType.TFTBoosting:
                    emailbody = RenderPartialViewToString("EmailTemplates/PurchaseOrderTFTSoloBoostEmail", purchaseForm).Result;
                    break;

                default:
                    emailbody = JsonConvert.SerializeObject(purchaseForm);
                    break;
                }
                email.SendEmailAsync(purchaseForm.PersonalInformation.Email, $"Purchase Order", emailbody);

                if (User.Identity.IsAuthenticated)
                {
                    return(RedirectToAction("OrderDetails", "ClientArea", new { hash = EncryptionHelper.Encrypt(purchaseForm.Id) }));
                }
                else
                {
                    TempData.Put("completePurchaseForm", purchaseForm);
                    return(RedirectToAction("InvoiceDetails", "Invoice"));
                }
            }
            catch (Exception e)
            {
            }

            return(View());
        }
コード例 #38
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            ArrayList products      = new ArrayList();
            int otcSiteMemberId     = Convert.ToInt32(Request.Form["user1"]);
            int otcSalesOrderId     = Convert.ToInt32(Request.Form["user2"]);
            SiteName                = Request.Form["user3"];
            CrossDomainTracking     = Request.Form["user4"];
            int result			    = Convert.ToInt32(Request.Form["RESULT"]);
            string authCode			= Request.Form["AUTHCODE"];
            string responseMessage	= Request.Form["RESPMSG"];
            string avsData          = Request.Form["AVSDATA"];
            string pnrRef           = Request.Form["PNREF"];
            //string cardNumber       = Request.Form["CARDNUM"];
            OTCVerisignTransaction tran = null;
            OTCSalesOrder order = null;

            try
            {
                Log.Info("Received post from paypal.");
                Log.InfoFormat("MemberID = {0} SalesOrderID = {1} Result = {2} AuthCode = {3} ResponseMessage = {4}", otcSiteMemberId.ToString(), otcSalesOrderId.ToString(), result.ToString(), authCode, responseMessage);
                tran = new OTCVerisignTransaction();
                order = new OTCSalesOrder(otcSalesOrderId);
                //OTCCreditCard card   = new OTCCreditCard(10181);
                //card.CardNumber      = cardNumber;
                ////card.ExpirationMonth = 7.ToString();
                //card.ExpirationYear  = 2007.ToString();
                //card.OTCSiteMemberId = otcSiteMemberId;
                //card.Add();
                //FFTProduct product   = new FFTProduct(productId);
                //UNCOMMENT ALL THIS
                tran.AuthCode = authCode.ToString();
                tran.OTCSalesOrderId = otcSalesOrderId;
                tran.OTCSiteMemberId = otcSiteMemberId;
                tran.AVSData = avsData;
                tran.Cost = order.TotalCost;
                tran.PNRRef = pnrRef;
                tran.ResponseMessage = responseMessage;
                tran.Result = result;
                tran.Add();

                m_order = order;

            }
            catch (Exception error)
            {
                Log.Error("Unable to complete Paypal transaction.", error);
            }

            if (responseMessage.ToLower() == "approved")
            {

                string mailBody = OTCSalesOrder.GetEmailProductString(order.OTCSalesOrderId);

                EmailSender mail = new EmailSender("*****@*****.**", "BetterMAN.BetterWOMAN");

                String subject = "Order Confirmation - Interceuticals Order " + order.OTCSalesOrderId;
                String notifyEmails = order.EmailAddress;

                mail.AddEmailAddresses(order.EmailAddress);
                mail.AddBccEmailAddresses(AppLookup.RecipientsOrders);
                String error = mail.SendEmail(subject, mailBody);

                if (error == "")
                    Response.Write("Successfully sent email.<br>");
                else
                {
                    Response.Write("Error in sending email.  " + error);
                    Log.Error(error);
                }

                OTC.Web.Promotion.OTCPromotion pr = new OTC.Web.Promotion.OTCPromotion(order.OTCPromotionId);
                pr.AddPromotionUsage(order.OTCSiteMemberId, order.OTCSalesOrderId);

                try
                {
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("https://loc1.hitsprocessor.com/confirmation.asp?acct=interceut1&type=60682&s=1&uniqueId=" + order.OTCSalesOrderId + "&orderAmount=" + order.OrderCost);

                    HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    Response.Write("hit processesor o.k. <br>");
                    /*
                    webreq = (HttpWebRequest)WebRequest.Create("http://www.betterwomannow.com/Interceuticals/Common/Marketing/BetterWoman.aspx?OID=" + order.OTCSalesOrderId);
                    webresp = (HttpWebResponse)webreq.GetResponse();
                    webreq = (HttpWebRequest)WebRequest.Create("http://www.bettermannow.com/Interceuticals/Common/Marketing/BetterMan.aspx?OID=" + order.OTCSalesOrderId);
                    webresp = (HttpWebResponse)webreq.GetResponse();
                    Response.Write("mailsent o.k. <br>"); */
                }
                catch (Exception ex)
                {

                    if (mail == null)
                        mail = new EmailSender();

                    subject = "ERROR: Order Confirmation - Interceuticals Order " + order.OTCSalesOrderId;
                    mailBody = ex.Message;
                    notifyEmails = "*****@*****.**";

                    mail.AddEmailAddresses(notifyEmails);
                    mail.SendEmail(subject, mailBody);

                }
            }
            else
                setAbandoned(tran.OTCSiteMemberId);
        }
コード例 #39
0
        public async Task <ActionResult> ApproveManpower(string mrfid, string Remarks, string oic_recruiter_id = "", string recruiter_id = "", string recruitment_supervisor_id = "")
        {
            var    detail          = db.sp_manpower_detail(mrfid).FirstOrDefault();
            var    userid          = User.Identity.GetUserId();
            var    role            = Users.Role(userid);
            var    user_involved   = db.sp_get_mrf_user_involved(mrfid).FirstOrDefault();
            var    adminlist       = db.sp_admin_list().ToList();
            string approvedmessage = "";
            List <ManpowerViewModel.ManpowerNotification> Notification = new List <ManpowerViewModel.ManpowerNotification>();

            //approved accountmanager
            if (detail.am_approved == false && role == "Account Manager")
            {
                approvedmessage = mrfid + " Has been approved and assigned to " + Users.Fullname(recruitment_supervisor_id);
                db.sp_approved_manpower_accountmanager(mrfid, recruitment_supervisor_id);
                db.ExecuteCommand("update tbl_manpower_request set remarks={0} where mrfid={1}", Remarks, mrfid);
                foreach (var m in new string[] { user_involved.coordinator_id, recruitment_supervisor_id })
                {
                    Notification.Add(new ManpowerViewModel.ManpowerNotification()
                    {
                        from = userid, to = m, notification_message = approvedmessage, mrfid = mrfid
                    });
                }

                //send email to supervisor
                await Task.Run(new Action(() =>
                {
                    EmailSender email = new EmailSender();
                    email.EmailNotification(generateurl(Users.EmailAddress(recruitment_supervisor_id), mrfid), mrfid, recruitment_supervisor_id);
                }));
            }
            //approved supervisor
            else if (detail.am_approved == true && detail.recruitment_supervisor_approved == false && User.IsInRole("Recruitment Supervisor"))
            {
                approvedmessage = mrfid + " Has been assigned to " + Users.Fullname(recruiter_id) + " for Recruiter allocation";
                db.sp_approved_manpower_recruitment_supervisor(mrfid, recruiter_id);
                foreach (var m in new string[] { user_involved.coordinator_id, user_involved.am_1_id, user_involved.am_2_id, recruiter_id })
                {
                    Notification.Add(new ManpowerViewModel.ManpowerNotification()
                    {
                        from = userid, to = m, notification_message = approvedmessage, mrfid = mrfid
                    });
                }
                //email send to oic
                await Task.Run(new Action(() =>
                {
                    EmailSender email = new EmailSender();
                    email.EmailNotification(generateurl(Users.EmailAddress(recruiter_id), mrfid), mrfid, recruiter_id);
                }));
            }

            //notification loop all added in list of notification
            foreach (var m in Notification)
            {
                db.sp_add_notification(m.from, m.to, m.notification_message, m.mrfid);
            }
            //notify admin
            foreach (var i in adminlist)
            {
                db.sp_add_notification(userid, i.UserId, approvedmessage, mrfid);
            }

            Manpower.AddAuditTrail(User.Identity.GetUserId(), Users.Fullname(User.Identity.GetUserId()) + " Approved the Manpower Request", mrfid);

            await Task.Run(new Action(() =>
            {
                new EmailSender().EmailNotificationRejectCancelled(mrfid, string.Format("{0} Has been approved.", mrfid), string.Format("{0} Has been approved.", mrfid), "", Recruitment.Class.Users.EmailAddress(user_involved.coordinator_id), Url.Action("ManpowerRequestDetail", "manpower", new { mrfid = mrfid }));
            }));

            return(RedirectToAction("dashboard", "RecruitmentProcess", new { mrfid = mrfid, approved = approvedmessage }));
        }
コード例 #40
0
        public void UpdateMyPassword(UpdatePasswordModel model)
        {
            IValidator validator = new FluentValidator <UpdatePasswordModel, UpdatePasswordModelValidationRules>(model);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var identity = (AnkaCMSIdentity)Thread.CurrentPrincipal.Identity;
            var user     = _repositoryUser.Get(e => e.Id == identity.UserId);

            if (user == null)
            {
                throw new NotFoundException(Messages.DangerRecordNotFound);
            }

            if (model.OldPassword.ToSha512() != user.Password)
            {
                throw new NotFoundException(Messages.DangerIncorrectOldPassword);
            }

            var versionHistory = _repositoryUserHistory.Get().Where(e => e.ReferenceId == user.Id).Max(t => t.Version);

            var userHistory = user.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = user.Id;
            userHistory.CreatorId      = user.Creator.Id;
            userHistory.IsDeleted      = false;
            userHistory.Version        = versionHistory + 1;
            userHistory.RestoreVersion = 0;
            _repositoryUserHistory.Add(userHistory, true);


            var password = model.Password;

            user.Password             = password.ToSha512();
            user.LastModificationTime = DateTime.Now;
            user.LastModifier         = user;
            var version = user.Version;

            user.Version = version + 1;
            var affectedUser = _repositoryUser.Update(user, true);

            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserPassword)
            {
                return;
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.UpdateMyPassword);
        }
コード例 #41
0
        public AddModel <UserModel> Add(AddModel <UserModel> addModel)
        {
            var validator = new FluentValidator <UserModel, UserValidationRules>(addModel.Item);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var language = _serviceMain.DefaultLanguage;


            var item = addModel.Item.CreateMapped <UserModel, User>();

            if (_repositoryUser.Get().FirstOrDefault(e => e.Username == item.Username) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
            }

            if (_repositoryUser.Get(e => e.Email == item.Email) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
            }

            var password = addModel.Item.Password.ToSha512();

            Person person;

            var maxDisplayOrderPerson = _repositoryPerson.Get().Max(e => e.DisplayOrder);
            var maxDisplayOrderUser   = _repositoryUser.Get().Max(e => e.DisplayOrder);

            if (addModel.Item.IdentityCode != null)
            {
                if (_repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode) != null)
                {
                    person = _repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode);
                }
                else
                {
                    person = new Person
                    {
                        Id                   = GuidHelper.NewGuid(),
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        DisplayOrder         = maxDisplayOrderPerson + 1,
                        Version              = 1,
                        IsApproved           = false,
                        IdentityCode         = addModel.Item.IdentityCode.Trim().Length > 0 ? addModel.Item.IdentityCode : GuidHelper.NewGuid().ToString(),
                        FirstName            = addModel.Item.FirstName,
                        LastName             = addModel.Item.LastName,
                    };
                }
            }

            else
            {
                person = new Person
                {
                    Id                   = GuidHelper.NewGuid(),
                    CreationTime         = DateTime.Now,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = maxDisplayOrderPerson + 1,
                    Version              = 1,
                    IsApproved           = false,
                    IdentityCode         = GuidHelper.NewGuid().ToString(),
                    FirstName            = addModel.Item.FirstName,
                    LastName             = addModel.Item.LastName,
                };
            }


            person.CreatorId      = _serviceMain.IdentityUser.Id;
            person.LastModifierId = _serviceMain.IdentityUser.Id;

            _repositoryPerson.Add(person, true);
            item.Id           = GuidHelper.NewGuid();
            item.Creator      = _serviceMain.IdentityUser;
            item.CreationTime = DateTime.Now;

            item.LastModificationTime = DateTime.Now;
            item.LastModifier         = _serviceMain.IdentityUser;

            item.DisplayOrder = maxDisplayOrderUser + 1;
            item.Person       = person;
            item.Language     = language;
            item.Version      = 1;

            var affectedUser = _repositoryUser.Add(item, true);

            var role = _repositoryRole.Get(x => x.Code == RoleConstants.Default.Item1);

            if (role == null)
            {
                throw new NotFoundException();
            }

            _repositoryRoleUserLine.Add(new RoleUserLine
            {
                Id                   = GuidHelper.NewGuid(),
                User                 = affectedUser,
                Role                 = role,
                Creator              = _serviceMain.IdentityUser,
                CreationTime         = DateTime.Now,
                DisplayOrder         = 1,
                LastModifier         = _serviceMain.IdentityUser,
                LastModificationTime = DateTime.Now,
                Version              = 1
            }, true);

            addModel.Item = affectedUser.CreateMapped <User, UserModel>();

            addModel.Item.Creator      = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);
            addModel.Item.LastModifier = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);
            addModel.Item.Language     = new IdName(affectedUser.Language.Id, affectedUser.Language.Name);

            addModel.Item.IdentityCode = affectedUser.Person.IdentityCode;
            addModel.Item.FirstName    = affectedUser.Person.FirstName;
            addModel.Item.LastName     = affectedUser.Person.LastName;

            if (!_serviceMain.ApplicationSettings.SendMailAfterAddUser)
            {
                return(addModel);
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_serviceMain, _smtp);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Add);
            return(addModel);
        }
コード例 #42
0
        public void UpdateMyInformation(UpdateInformationModel model)
        {
            IValidator validator = new FluentValidator <UpdateInformationModel, UpdateInformationModelValidationRules>(model);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var identity = (AnkaCMSIdentity)Thread.CurrentPrincipal.Identity;
            var user     = _repositoryUser
                           .Join(x => x.Person)
                           .FirstOrDefault(e => e.Id == identity.UserId);

            if (user == null)
            {
                throw new NotFoundException(Messages.DangerRecordNotFound);
            }


            var person = user.Person;

            if (model.Username != user.Username)
            {
                if (_repositoryUser.Get().Any(p => p.Username == model.Username))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
                }
            }
            if (model.Email != user.Email)
            {
                if (_repositoryUser.Get().Any(p => p.Email == model.Email))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
                }
            }


            var versionHistoryPerson = _repositoryPersonHistory.Get().Where(e => e.ReferenceId == person.Id).Max(t => t.Version);

            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id             = GuidHelper.NewGuid();
            personHistory.ReferenceId    = user.Id;
            personHistory.CreatorId      = user.Creator.Id;
            personHistory.IsDeleted      = false;
            personHistory.Version        = versionHistoryPerson + 1;
            personHistory.RestoreVersion = 0;
            _repositoryPersonHistory.Add(personHistory, true);

            person.FirstName = model.FirstName;
            person.LastName  = model.LastName;
            person.Biography = model.Biography;


            person.LastModificationTime = DateTime.Now;
            person.LastModifierId       = user.Id;
            var versionPerson = user.Version;

            person.Version = versionPerson + 1;
            _repositoryPerson.Update(person, true);

            var versionHistoryUser = _repositoryUserHistory.Get().Where(e => e.ReferenceId == user.Id).Max(t => t.Version);

            var userHistory = user.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = user.Id;
            userHistory.CreatorId      = user.Creator.Id;
            userHistory.IsDeleted      = false;
            userHistory.Version        = versionHistoryUser + 1;
            userHistory.RestoreVersion = 0;
            _repositoryUserHistory.Add(userHistory, true);

            user.Username = model.Username;
            user.Email    = model.Email;


            user.LastModificationTime = DateTime.Now;
            user.LastModifier         = user;
            var version = user.Version;

            user.Version = version + 1;
            var affectedUser = _repositoryUser.Update(user, true);

            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserInformation)
            {
                return;
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = string.Empty,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.UpdateMyInformation);
        }
コード例 #43
0
ファイル: ExtractInterface.cs プロジェクト: nbstrat/aout1
 public Storage(EmailSender email)
 {
     m_email = email;
 }
コード例 #44
0
ファイル: Home.aspx.cs プロジェクト: majurans/Dial4Cheap
 protected void Page_Load(object sender, EventArgs e)
 {
     EmailSender mailSender = new EmailSender();
     //mailSender.SendEmail();
 }
コード例 #45
0
        public AddModel <UserModel> Add(AddModel <UserModel> addModel)
        {
            IValidator validator         = new FluentValidator <UserModel, UserValidationRules>(addModel.Item);
            var        validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var item = addModel.Item.CreateMapped <UserModel, User>();

            if (_repositoryUser.Get(e => e.Username == item.Username) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
            }

            if (_repositoryUser.Get(e => e.Email == item.Email) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
            }

            if (addModel.Item.BirthDate == DateTime.MinValue)
            {
                addModel.Item.BirthDate = DateTime.Now;
            }

            var password = addModel.Item.Password.ToSha512();

            // kişi bilgisi veritabanında var mı?
            // Kişi bilgisi yoksa yeni kişi bilgisi oluşturuluyor
            Person person;

            var maxDisplayOrderPerson = _repositoryPerson.Get().Max(e => e.DisplayOrder);
            var maxDisplayOrderUser   = _repositoryUser.Get().Max(e => e.DisplayOrder);

            if (addModel.Item.IdentityCode != null)
            {
                if (_repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode) != null)
                {
                    person = _repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode);
                }
                else
                {
                    person = new Person
                    {
                        Id                   = GuidHelper.NewGuid(),
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        DisplayOrder         = maxDisplayOrderPerson + 1,
                        Version              = 1,
                        IsApproved           = false,
                        IdentityCode         = addModel.Item.IdentityCode.Trim().Length > 0 ? addModel.Item.IdentityCode : GuidHelper.NewGuid().ToString(),
                        FirstName            = addModel.Item.FirstName,
                        LastName             = addModel.Item.LastName,
                        Biography            = addModel.Item.Biography,
                        BirthDate            = addModel.Item.BirthDate
                    };
                }
            }

            else
            {
                person = new Person
                {
                    Id                   = GuidHelper.NewGuid(),
                    CreationTime         = DateTime.Now,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = maxDisplayOrderPerson + 1,
                    Version              = 1,
                    IsApproved           = false,
                    IdentityCode         = GuidHelper.NewGuid().ToString(),
                    FirstName            = addModel.Item.FirstName,
                    LastName             = addModel.Item.LastName,
                    BirthDate            = addModel.Item.BirthDate,
                    Biography            = addModel.Item.Biography
                };
            }



            person.CreatorId      = IdentityUser.Id;
            person.LastModifierId = IdentityUser.Id;

            _repositoryPerson.Add(person, true);
            item.Id           = GuidHelper.NewGuid();
            item.Creator      = IdentityUser;
            item.CreationTime = DateTime.Now;

            item.LastModificationTime = DateTime.Now;
            item.LastModifier         = IdentityUser;
            item.DisplayOrder         = maxDisplayOrderUser + 1;
            item.Person  = person;
            item.Version = 1;

            var affectedUser = _repositoryUser.Add(item, true);

            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id             = GuidHelper.NewGuid();
            personHistory.ReferenceId    = person.Id;
            personHistory.IsDeleted      = false;
            personHistory.RestoreVersion = 0;
            _repositoryPersonHistory.Add(personHistory, true);

            var userHistory = affectedUser.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = affectedUser.Id;
            userHistory.PersonId       = affectedUser.Person.Id;
            userHistory.CreatorId      = IdentityUser.Id;
            userHistory.IsDeleted      = false;
            userHistory.RestoreVersion = 0;

            _repositoryUserHistory.Add(userHistory, true);

            var role = _repositoryRole.Get(x => x.Code == "DEFAULTROLE");

            if (role == null)
            {
                throw new NotFoundException(Messages.DangerRecordNotFound);
            }

            var affectedRoleUserLine = _repositoryRoleUserLine.Add(new RoleUserLine
            {
                Id                   = GuidHelper.NewGuid(),
                User                 = affectedUser,
                Role                 = role,
                Creator              = IdentityUser,
                CreationTime         = DateTime.Now,
                DisplayOrder         = 1,
                LastModifier         = IdentityUser,
                LastModificationTime = DateTime.Now,
                Version              = 1
            }, true);

            var roleUserLineHistory = affectedRoleUserLine.CreateMapped <RoleUserLine, RoleUserLineHistory>();

            roleUserLineHistory.Id          = GuidHelper.NewGuid();
            roleUserLineHistory.ReferenceId = roleUserLineHistory.Id;
            roleUserLineHistory.RoleId      = affectedRoleUserLine.Role.Id;
            roleUserLineHistory.UserId      = affectedRoleUserLine.User.Id;
            roleUserLineHistory.CreatorId   = affectedRoleUserLine.Creator.Id;

            _repositoryRoleUserLineHistory.Add(roleUserLineHistory, true);

            addModel.Item.Creator      = new IdCodeName(IdentityUser.Id, IdentityUser.Username, IdentityUser.Person.DisplayName);
            addModel.Item.LastModifier = new IdCodeName(IdentityUser.Id, IdentityUser.Username, IdentityUser.Person.DisplayName);


            addModel.Item.BirthDate    = affectedUser.Person.BirthDate;
            addModel.Item.IdentityCode = affectedUser.Person.IdentityCode;
            addModel.Item.FirstName    = affectedUser.Person.FirstName;
            addModel.Item.LastName     = affectedUser.Person.LastName;
            addModel.Item.Biography    = affectedUser.Person.Biography;

            if (!_serviceMain.ApplicationSettings.SendMailAfterAddUser)
            {
                return(addModel);
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Add);
            return(addModel);
        }
コード例 #46
0
ファイル: MessageQueueModule.cs プロジェクト: gowhy/LoveBank
        private void SendMailMessage(MsgQueue msg)
        {
            var config = SettingManager.Get<EmailConfig>();

            IEmailSender sender = new EmailSender(config.SmtpServer, config.SmtpPort, config.Name, config.SmtpUserName, config.SmtpPassword, config.IsSSL);

            sender.SendMail(msg.Dest, msg.Title, msg.Content, msg.ID, (o, e) => {
                                                                          var m = DbProvider().GetByID<MsgQueue>(e.UserState);
                                                                          if (e.Error != null) {
                                                                              m.IsSuccess = false;
                                                                              m.Result = e.Error.Message;
                                                                          } else {
                                                                              m.IsSuccess = true;
                                                                          }
                                                                          DbProvider().SaveChanges();
                                                                      });
        }
コード例 #47
0
        // POST api/RequestForm/SendChangeRequest
        public HttpResponseMessage SendChangeRequest(JObject json)
        {
            int managerID = GetIDFromName((string)json["current"]["bazookaInfo"]["managerId"]);
            int f_managerID = GetIDFromName((string)json["future"]["bazookaInfo"]["managerId"]);

            HttpResponseMessage useForFailure = new HttpResponseMessage(HttpStatusCode.NotFound);
            if ((managerID == -1) && (f_managerID == -1))
            {
                useForFailure.Content = new StringContent("Both current and future managers were not found.");
                return useForFailure;
            }
            else if (managerID == -1)
            {
                useForFailure.Content = new StringContent("Current manager was not found.");
                return useForFailure;
            }
            else if (f_managerID == -1)
            {
                useForFailure.Content = new StringContent("Future manager was not found.");
                return useForFailure;
            }

            RequestForm obj = makeRequestForm(json);

            Collection<string> to = new Collection<string>();
            to.Add("*****@*****.**");
            EmailSender emailer = new EmailSender("Coyote Moves Request ", to, "*****@*****.**", "", HttpContext.Current.Server.MapPath("/CoyoteMoves/CoyoteMovesTemplate.pdf"));
            emailer.sendMovesRequest(obj);

            RequestFormDB formDB = new RequestFormDB();
            formDB.StoreRequestFormInDatabaseAsPending(obj);

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
コード例 #48
0
        public UpdateModel <UserModel> Update(UpdateModel <UserModel> updateModel)
        {
            IValidator validator         = new FluentValidator <UserModel, UserValidationRules>(updateModel.Item);
            var        validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var identityUserMinRoleLevel = IdentityUser.RoleUserLines.Select(x => x.Role.Level).Min();


            var item = _repositoryUser
                       .Join(x => x.Person)
                       .Join(x => x.Creator.Person)
                       .Join(x => x.LastModifier.Person)
                       .FirstOrDefault(x => x.Id == updateModel.Item.Id && x.RoleUserLines.All(t => t.Role.Level > identityUserMinRoleLevel));

            if (item == null)
            {
                throw new NotFoundException(Messages.DangerRecordNotFound);
            }

            var person = item.Person;

            if (updateModel.Item.Username != item.Username)
            {
                if (_repositoryUser.Get().Any(p => p.Username == updateModel.Item.Username))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
                }
            }

            if (updateModel.Item.Email != item.Email)
            {
                if (_repositoryUser.Get().Any(p => p.Email == updateModel.Item.Email))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
                }
            }


            var versionHistoryPerson = _repositoryPersonHistory.Get().Where(e => e.ReferenceId == person.Id).Max(t => t.Version);

            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id             = GuidHelper.NewGuid();
            personHistory.ReferenceId    = item.Id;
            personHistory.CreatorId      = IdentityUser.Id;
            personHistory.CreationTime   = DateTime.Now;
            personHistory.IsDeleted      = false;
            personHistory.Version        = versionHistoryPerson + 1;
            personHistory.RestoreVersion = 0;
            _repositoryPersonHistory.Add(personHistory, true);

            person.FirstName = updateModel.Item.FirstName;
            person.LastName  = updateModel.Item.LastName;
            person.Biography = updateModel.Item.Biography;



            person.LastModificationTime = DateTime.Now;
            person.LastModifierId       = IdentityUser.Id;
            var versionPerson = person.Version;

            person.Version = versionPerson + 1;
            _repositoryPerson.Update(person, true);

            var versionHistoryUser = _repositoryUserHistory.Get().Where(e => e.ReferenceId == item.Id).Max(t => t.Version);

            var userHistory = item.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = item.Id;
            userHistory.CreatorId      = IdentityUser.Id;
            userHistory.CreationTime   = DateTime.Now;
            userHistory.IsDeleted      = false;
            userHistory.Version        = versionHistoryUser + 1;
            userHistory.RestoreVersion = 0;
            _repositoryUserHistory.Add(userHistory, true);

            item.Username   = updateModel.Item.Username;
            item.Email      = updateModel.Item.Email;
            item.IsApproved = updateModel.Item.IsApproved;

            item.LastModificationTime = DateTime.Now;
            item.LastModifier         = IdentityUser;
            var version = item.Version;

            item.Version = version + 1;
            var affectedUser = _repositoryUser.Update(item, true);

            foreach (var line in _repositoryRoleUserLine

                     .Join(x => x.Role)
                     .Join(x => x.User)
                     .Where(x => x.User.Id == affectedUser.Id).ToList())
            {
                var lineHistory = line.CreateMapped <RoleUserLine, RoleUserLineHistory>();
                lineHistory.Id           = GuidHelper.NewGuid();
                lineHistory.ReferenceId  = line.Id;
                lineHistory.RoleId       = line.Role.Id;
                lineHistory.UserId       = line.User.Id;
                lineHistory.CreationTime = DateTime.Now;
                lineHistory.CreatorId    = IdentityUser.Id;
                _repositoryRoleUserLineHistory.Add(lineHistory, true);
                _repositoryRoleUserLine.Delete(line, true);
            }

            foreach (var idCodeNameSelected in updateModel.Item.Roles)
            {
                var itemRole = _repositoryRole.Get(x => x.Id == idCodeNameSelected.Id);

                var affectedLine = _repositoryRoleUserLine.Add(new RoleUserLine
                {
                    Id                   = GuidHelper.NewGuid(),
                    User                 = affectedUser,
                    Role                 = itemRole,
                    Creator              = IdentityUser,
                    CreationTime         = DateTime.Now,
                    DisplayOrder         = 1,
                    LastModifier         = IdentityUser,
                    LastModificationTime = DateTime.Now,
                    Version              = 1
                }, true);

                var lineHistory = affectedLine.CreateMapped <RoleUserLine, RoleUserLineHistory>();
                lineHistory.Id          = GuidHelper.NewGuid();
                lineHistory.ReferenceId = affectedLine.Id;
                lineHistory.RoleId      = affectedLine.Role.Id;
                lineHistory.UserId      = affectedLine.User.Id;
                lineHistory.CreatorId   = affectedLine.Creator.Id;

                _repositoryRoleUserLineHistory.Add(lineHistory, true);
            }

            updateModel.Item = affectedUser.CreateMapped <User, UserModel>();

            updateModel.Item.Creator      = new IdCodeName(item.Creator.Id, item.Creator.Username, item.Creator.Person.DisplayName);
            updateModel.Item.LastModifier = new IdCodeName(IdentityUser.Id, IdentityUser.Username, IdentityUser.Person.DisplayName);


            updateModel.Item.BirthDate    = item.Person.BirthDate;
            updateModel.Item.IdentityCode = item.Person.IdentityCode;
            updateModel.Item.FirstName    = item.Person.FirstName;
            updateModel.Item.LastName     = item.Person.LastName;
            updateModel.Item.Biography    = item.Person.Biography;



            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserInformation)
            {
                return(updateModel);
            }
            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = string.Empty,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Update);
            return(updateModel);
        }