Exemplo n.º 1
0
        public ActionResult Add(Ticket ticket)
        {
            if (ModelState.IsValid)
            {
                ticket.CompanyId    = OperatingUser.CompanyId;
                ticket.CreatedById  = OperatingUser.Id;
                ticket.ModifiedById = OperatingUser.Id;
                _ticketService.Add(ticket);

                var userIds = ticket.NotifyTo?.Split(',').ToList() ?? new List <string>();
                userIds.Add(ticket.RequestorId);
                userIds.Add(ticket.AssignedToId);
                userIds.Add(ticket.CreatedById);
                List <string> contributors = _userService.GetEmailsById(userIds.ToArray());

                ticket.LinkToTicketDetails =
                    $"{Request.Url.Scheme}://{Request.Url.Host}{Url.Action("Edit", "Ticket", new {id = ticket.Id})}";
                string emailMessage = _ticketService.ComposeTicketCreatedEmail(ticket);
                _emailService.SendEmail(emailMessage, $"New Ticket: {ticket.Title}", contributors.Distinct().ToArray());
                if (ticket.Id > 0)
                {
                    return(RedirectToAction("Edit", "Ticket", new { id = ticket.Id }));
                }
            }
            else
            {
                ReadModelStateError(ModelState);
            }
            return(View(ticket));
        }
Exemplo n.º 2
0
        public async Task <JsonResult> Register(User user)
        {
            if (ModelState.IsValid)
            {
                user.UserRegisteredIp     = UserSession.IpAddress;
                user.RegisteredMacAddress = UserSession.MacAddress;
                user.LastActivityIp       = UserSession.IpAddress;
                user.LastActiveMacAddress = UserSession.MacAddress;
                user.EmploymentTypeId     = (int)EmploymentType.ContractHourly; // this is default employemnt type at registration. later admin can set the type
                user.DateCreatedUtc       = DateTimeOffset.UtcNow;
                user.LastActivityDateUtc  = DateTimeOffset.UtcNow;
                user.LastUpdatedUtc       = DateTimeOffset.UtcNow;
                user.PasswordLastChanged  = DateTime.UtcNow;

                Company company = _companyService.Get(code: user.RegistrationCode);
                if (company == null || company.Id < 1)
                {
                    user.ErrorMessage =
                        $"Registration code {user.RegistrationCode} doesn't match with any  Company in the system";
                    ModelState.AddModelError("", user.ErrorMessage);
                    SetRegistrationContext(user);
                    return(Json(user));
                }
                user.CompanyId = company.Id;
                user.IsActive  = true;

                var result = await UserManager.CreateAsync(user, user.Password);

                if (result.Succeeded)
                {
                    user.RegistrationAddress.UserId = user.Id;
                    _userService.AddAddress(user.RegistrationAddress);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //return RedirectToAction("Index", "Home");

                    string emailMessage = _userService.ComposeRegisteredEmail(user);
                    _emailService.SendEmail(emailMessage, "Successfully Registered", new[] { user.Email });

                    return(Json(user));
                }
                user.Uid          = -5;
                user.ErrorMessage = string.Join("<br/>", result.Errors.Select(x => x));
                AddIdentityErrors(result);
            }
            else
            {
                ReadModelStateError(modelState: ModelState);
                user.ErrorMessage = ViewData["ModelError"] as string;
            }
            SetRegistrationContext(user);
            // If we got this far, something failed, redisplay form
            return(Json(user));
        }
Exemplo n.º 3
0
            public async Task <bool> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
            {
                ApplicationUser user;
                IdentityResult  result;

                user = await _userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    //return Request.CreateResponse(HttpStatusCode.NotFound, "User not found");
                    throw new NotFoundException("User not found", user);
                }

                result = await _userManager.ResetPasswordAsync(user, request.Code, request.Password);

                if (result.Succeeded)
                {
                    _email.SendEmail(request.Email, "Password is been reset",
                                     "Your password is succefully reset");
                    return(true);
                }
                else
                {
                    throw new ApplicationException("Token is invalid.");
                }
            }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null)
                {
                    return(RedirectToPage("Register"));
                }

                ModelState.Clear();

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: Request.Scheme);

                _emailSender.SendEmail(
                    Input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return(Page());
            }

            return(Page());
        }
        public static void Send <T>(PrintPayrollBase printPayrollBase, IEmail <T> email, T payroll)
        {
            bool error = false;

            if (payroll is model.PayrollLeaseCompany)
            {
                ((PrintPayrollLeaseCompany)printPayrollBase).Print(false);
            }
            else
            {
                printPayrollBase.Print(false);
            }

            INotification notification = new Email("Pay Stub");

            ((Email)notification).File = new Attachment(File.Open(printPayrollBase.Fullname, FileMode.Open), printPayrollBase.Filename);

            try
            {
                email.SendEmail(notification, payroll);
            }
            catch
            {
                error = true;
            }

            if (error)
            {
                MessageBox.Show("Email not sent!", "Notification", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                MessageBox.Show("Email sent!", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        //public async Task<string> Validate(NotificationEventInput input) {
        //    string errors = string.Empty;
        //    if (!string.IsNullOrWhiteSpace(input.Id)) {  //PUT
        //        var existsId = await existElement.ExistsById<NotificationEvent>(input.Id, false);
        //        if (!existsId)
        //            errors += $"No existe notificación con id {input.Id}.";
        //    }
        //    var existsBarrack = await existElement.ExistsById<Barrack>(input.IdBarrack, false);
        //    if (!existsBarrack)
        //        errors += $"No existe cuartel con id {input.IdBarrack}.";
        //    if (input.NotificationType == NotificationType.Phenological) {
        //        var existsPhenologicalEvent = await existElement.ExistsById<PhenologicalEvent>(input.IdPhenologicalEvent, false);
        //        if (!existsPhenologicalEvent)
        //            errors += $"No existe evento fenológico con id {input.IdPhenologicalEvent}.";
        //    }
        //    return errors.Replace(".",".\r\n");
        //}

        public async Task <ExtPostContainer <string> > Save(NotificationEvent notificationEvent)
        {
            //TODO: Revisar
            var picturePath = await uploadImage.UploadImageBase64(notificationEvent.PicturePath);

            notificationEvent.PicturePath = picturePath;
            await repo.CreateUpdate(notificationEvent);

            search.AddDocument(notificationEvent);

            //TODO: Definir el origen de la lista de idsRoles
            var usersEmails = await commonQueries.GetUsersMailsFromRoles(new List <string> {
                "24beac75d4bb4f8d8fae8373426af780"
            });

            email.SendEmail(usersEmails, "Notificacion",
                            $@"<html>
                    <body>
                        <p> Estimado(a), </p>
                        <p> Llego una notificacion </p>
                        <img src='{picturePath}' style='width:50%;height:auto;'>
                        <p> Atentamente,<br> -Aresa </br></p>
                    </body>
                </html>");
            return(new ExtPostContainer <string> {
                IdRelated = notificationEvent.Id,
                MessageResult = ExtMessageResult.Ok
            });
        }
Exemplo n.º 7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        _logging = IoC.IoC.Get<ILog>();
        _date = IoC.IoC.Get<IDate>();
        _settings = IoC.IoC.Get<ISettings>();
        _emailNotificationItems = IoC.IoC.Get<IEmailNotificationItems>();
        _sendEmail = IoC.IoC.Get<IEmail>();
        _status = IoC.IoC.Get<IStatus>();

        var url = Request.Url.AbsoluteUri;

        if (Request.QueryString["csvfile"] == null)
        {
            numberOfRun += 1;
            _logging.Msg("CroneJob startet, " + numberOfRun);
            if (DateTime.Now.Hour == 8)
            {
                _sendEmail.SendEmail("*****@*****.**", "*****@*****.**", "Cronejob startet kl. 8:00, antal gange det er kørt siden sidst: " + numberOfRun, "");
                numberOfRun = 0;
            }
            url = null;
        }

        Run(url);
    }
Exemplo n.º 8
0
            public async Task <bool> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
            {
                ApplicationUser user;
                string          code;
                string          callbackUrl;

                user = await _userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    return(true);
                }

                code = await _userManager.GeneratePasswordResetTokenAsync(user);

                // We replace the char / for prevent getting multiple params to our front end
                var cide = code;

                code = code.Replace("/", "{");

                callbackUrl = GlobalVar.FrontendBaseUrl + "User/ResetPassword/" + code;

                _email.SendEmail(request.Email, "Reset Password",
                                 "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a><p>" + cide + "</p>");

                return(true);
            }
            public async Task <int> Handle(ResetEmployeePasswordCommand request, CancellationToken cancellationToken)
            {
                ApplicationUser currentUser;
                AppUser         currentAppUser, appEmployerUser;
                IdentityResult  result;
                string          password;

                currentUser = await _userManager.FindByIdAsync(_currentUserService.UserId);

                currentAppUser = await _context.User.Include(x => x.UserList).FirstOrDefaultAsync(x => x.Id == currentUser.Id);

                appEmployerUser = currentAppUser.UserList.FirstOrDefault(x => x.Id == request.Id);

                if (appEmployerUser != null)
                {
                    password = Helper.GeneratePassword(8);
                    result   = await _userManager.SetPassword(request.Id, password);

                    if (!result.Succeeded)
                    {
                        throw new ApplicationException(result.Errors.ToList().ToString());
                    }
                    else
                    {
                        _email.SendEmail(appEmployerUser.Email, "Password has been reset", "Your password has been reset by " + currentAppUser.FirstName + currentAppUser.LastName + ".<br>" +
                                         "For connecting again to My-Ticket, please use this one instead : " + password + "<br>" +
                                         "Kinds regards. <br>My-Ticket team.");
                        return(1);
                    }
                }

                return(0);
            }
Exemplo n.º 10
0
        public void Upgrade()
        {
            List <string> msg = new List <string>();

            email = EmailFactory.EmailFact("emailType");
            Console.WriteLine(email.SendEmail());
            Console.WriteLine("membership updated");
        }
Exemplo n.º 11
0
 public Employee(int empId, string empName, string gender, int age, IEmail mailobj)
 {
     this.empId   = empId;
     this.empName = empName;
     this.gender  = gender;
     this.age     = age;
     mailobj.SendEmail(empName);
 }
Exemplo n.º 12
0
        public void Active()
        {
            List <string> msg = new List <string>();

            email = EmailFactory.EmailFact("emailType");
            Console.WriteLine(email.SendEmail());
            Console.WriteLine("Activating user");
        }
Exemplo n.º 13
0
 public void Submit(string emailAddress)
 {
     try
     {
         email.SendEmail(emailAddress, "Business Object Email", "Demo");
     }
     catch (Exception ex)
     {
         logger.Log(ex);
     }
 }
 public void Submit()
 {
     try
     {
         email.SendEmail("*****@*****.**", "Business Object Email", "Demo");
         logger.Log("Email sent to [email protected]");
     }
     catch (Exception ex)
     {
         logger.Log(ex);
     }
 }
Exemplo n.º 15
0
        public async Task <IActionResult> Contact(string email, string subject, string message)
        {
            if (email != null && subject != null && message != null)
            {
                await _emailService.SendEmail(email, subject, message);

                TempData["Message"] = "Sent, we will get back to you ASAP";

                return(View());
            }

            return(View());
        }
        public void SendBlindSpotMail(EmailRequest emailRequest)
        {
            EmailTemplate mailtemplete = _mailTemplateAdapter.GetEmailTemplates(emailRequest.type);

            foreach (var coworker in emailRequest.coworkers)
            {
                try
                {
                    var mailBody = CreatMailBody(coworker, mailtemplete);
                    emailRequest.subject   = _subject;
                    emailRequest.emailbody = mailBody;
                    _email.SendEmail(coworker, mailBody, _subject);
                    emailRequest.status = "Success";
                    _mailTemplateAdapter.InsertEmailRequest(emailRequest);
                }
                catch (Exception)
                {
                    emailRequest.status = "Failed";
                    emailRequest.mailto = coworker;
                    _mailTemplateAdapter.InsertEmailRequest(emailRequest);
                }
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> Create([Bind(Include = "TeacherId,TeacherName,Address")] Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                db.Teachers.Add(teacher);
                await db.SaveChangesAsync();

                bool sendSuccessfull = await emailObj.SendEmail(teacher.TeacherName);

                return(RedirectToAction("Index"));
            }

            return(View(teacher));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> Contact(string email, string subject, string message)
        {
            if (email != null && subject != null && message != null)
            {
                await _emailService.SendEmail(email, subject, message);

                TempData["Message"] = "Sent, we will get back to you ASAP";

                return(View());
            }

            ModelState.AddModelError("email", "All Fields Must Be Completed");

            return(View());
        }
Exemplo n.º 19
0
            public async Task <int> Handle(CloseTicketsCommand request, CancellationToken cancellationToken)
            {
                TicketHeader ticket          = null;
                AppUser      user            = null;
                bool         isMemberOrAdmin = false;
                string       userEmail;
                string       messageMail = "Your ticket is now closed.<br>You can reply to this ticket to reopen it.";

                user = await _context.User.FirstOrDefaultAsync(x => x.Id == _currentUserService.UserId);

                if (await _userManager.IsInRoleAsync(user.Id, "Admin") || await _userManager.IsInRoleAsync(user.Id, "Member"))
                {
                    isMemberOrAdmin = true;
                }

                foreach (var model in request.TicketList)
                {
                    ticket = await _context.TickerHeader.Include(x => x.Status).FirstOrDefaultAsync(x => x.Id == model.Id);

                    if (ticket != null)
                    {
                        if (isMemberOrAdmin || (ticket.Requester != null && ticket.Requester.Id == _currentUserService.UserId))
                        {
                            ticket.ClosedDate = DateTime.Now;
                            ticket.Status     = await _context.Status.FirstOrDefaultAsync(x => x.Name == "Closed");
                        }

                        //Send mail to announce the ticket is closed
                        if (isMemberOrAdmin)
                        {
                            if (ticket.Requester != null)
                            {
                                userEmail = ticket.Requester?.Email;
                            }
                            else
                            {
                                userEmail = ticket.Email;
                            }
                            _email.SendEmail(userEmail, ticket.InternTitle, messageMail);
                        }
                    }
                    ticket    = null;
                    userEmail = "";
                }
                return(await _context.SaveChangesAsync(cancellationToken));
            }
        public override async Task <ExtPostContainer <string> > SaveInput(NotificationEventInput input)
        {
            await Validate(input);

            var id          = !string.IsNullOrWhiteSpace(input.Id) ? input.Id : Guid.NewGuid().ToString("N");
            var picturePath = await uploadImage.UploadImageBase64(input.Base64);


            NotificationEvent notification = new NotificationEvent {
                Id                  = id,
                Created             = DateTime.Now,
                IdBarrack           = input.IdBarrack,
                IdPhenologicalEvent = input.IdPhenologicalEvent,
                NotificationType    = input.NotificationType,
                PicturePath         = picturePath,
                Description         = input.Description,
            };

            //TODO: Cambiar tipo de dato a GeoSpacial
            #if !CONNECT
            if (input.Location != null)
            {
                notification.Location = new Point(input.Location.Lng, input.Location.Lat);
                notification.Weather  = await weather.GetWeather((float)input.Location.Lat, (float)input.Location.Lng);
            }
            #endif

            await SaveDb(notification);

            var usersEmails = await commonQueries.GetUsersMailsFromRoles(new List <string> {
                "24beac75d4bb4f8d8fae8373426af780"
            });

            email.SendEmail(usersEmails, "Notificacion",
                            $@"<html>
                    <body>
                        <p> Estimado(a), </p>
                        <p> Llego una notificacion </p>
                        <img src='{picturePath}' style='width:50%;height:auto;'>
                        <p> Atentamente,<br> -Aresa </br></p>
                    </body>
                </html>");

            return(await SaveSearch(notification));
        }
Exemplo n.º 21
0
        public async Task BuildRegistrationEmail(string emailAddress, string name)
        {
            string templateId = "d-d26e9bcbfef6438ab53fd65fca39da27";

            List <EmailItem> featuredFlums = new List <EmailItem>();
            List <int>       usedNums      = new List <int>();
            Random           rand          = new Random();

            for (int i = 0; i < 2; i++)
            {
                int temp = rand.Next(1, 10);
                while (usedNums.Contains(temp))
                {
                    temp = rand.Next(1, 10);
                }
                usedNums.Add(temp);
                Flummery flum = await _flummery.GetFlummeryBy(temp);

                featuredFlums.Add(new EmailItem {
                    Id        = flum.Id,
                    ImgSrc    = flum.ImageUrl,
                    ItemName  = flum.Name,
                    ItemPrice = flum.Price
                });
            }

            List <Personalization> personalizations = new List <Personalization>();

            personalizations.Add(new Personalization()
            {
                Tos = new List <EmailAddress>
                {
                    new EmailAddress(emailAddress)
                },
                Subject      = "Thanks for your purchase!",
                TemplateData = new RegistrationTemplateData()
                {
                    FullName     = name,
                    Date         = DateTime.Now.ToString(),
                    DisplayItems = featuredFlums
                }
            });
            await _email.SendEmail(templateId, personalizations);
        }
Exemplo n.º 22
0
            public async Task <int> Handle(CreateStaffTicketCommand request, CancellationToken cancellationToken)
            {
                AppUser      user   = null;
                TicketHeader ticket = null;
                int          result = 0;

                ticket = new TicketHeader
                {
                    Title       = request.Title,
                    Description = request.Description,
                    Priority    = await _context.Priority.FirstOrDefaultAsync(x => x.Id == request.Priority),
                    Project     = await _context.Project.FirstOrDefaultAsync(x => x.Id == request.Project),
                    Type        = await _context.Type.FirstOrDefaultAsync(x => x.Id == request.Type),
                    Group       = await _context.Group.FirstOrDefaultAsync(x => x.Id == request.Group),
                    AssignTO    = await _context.User.FirstOrDefaultAsync(x => x.Id == request.AssignTo),
                    Requester   = await _context.User.FirstOrDefaultAsync(x => x.Id == request.Requester),
                    ClosedDate  = null,
                };
                if (request.CloseImmediatly == true)
                {
                    ticket.Status = await _context.Status.FirstOrDefaultAsync(x => x.Name == "Closed");
                }
                else
                {
                    ticket.Status = await _context.Status.FirstOrDefaultAsync(x => x.Name == "Open");
                }

                _context.TickerHeader.Add(ticket);

                result = await _context.SaveChangesAsync(cancellationToken);

                ticket.InternTitle = ticket.Title + " - #" + ticket.Id;

                result = await _context.SaveChangesAsync(cancellationToken);

                if (result > 0 && ticket.Requester != null)
                {
                    _email.SendEmail(ticket.Requester.Email, ticket.InternTitle, "Your ticket is successfully created. <br>" +
                                     "We will reply soon as possible.<br>" +
                                     "<hr>Ticket content :<br>" + ticket.Description);
                }

                return(ticket.Id);
            }
Exemplo n.º 23
0
            public async Task <object> Handle(GenerateRandomCodeCommand request, CancellationToken cancellationToken)
            {
                Random random = new Random();
                int    length = 5;
                string chars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                string code;

                code = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());

                try
                {
                    _email.SendEmail(request.Email, "Account confirmation", "<h1>Your code : " + code + "</h1>");
                }
                catch (Exception e)
                {
                    throw e;
                }
                return(await Task.FromResult(new { codeConfirmation = code }));
            }
Exemplo n.º 24
0
            public async Task <int> Handle(CreateCustomerTicketCommand request, CancellationToken cancellationToken)
            {
                TicketHeader ticket = null;
                int          result = 0;


                ticket = new TicketHeader
                {
                    Title       = request.Title,
                    Description = request.Description,
                    Priority    = await _context.Priority.FirstOrDefaultAsync(x => x.Name == "Unknow"),
                    Project     = await _context.Project.FirstOrDefaultAsync(x => x.Name == "Unknow"),
                    Type        = await _context.Type.FirstOrDefaultAsync(x => x.Name == "Unknow"),
                    Status      = await _context.Status.FirstOrDefaultAsync(x => x.Name == "Open"),
                    Requester   = await _context.User.FirstOrDefaultAsync(x => x.Id == _currentUserService.UserId),
                    AssignTO    = null,
                    ClosedDate  = null,
                };



                _context.TickerHeader.Add(ticket);

                await _context.SaveChangesAsync(cancellationToken);

                ticket.InternTitle = ticket.Title + " - #" + ticket.Id;

                result = await _context.SaveChangesAsync(cancellationToken);

                if (result > 0)
                {
                    _email.SendEmail(ticket.Requester.Email, ticket.InternTitle, "Your ticket is successfully created. <br>" +
                                     "We will reply soon as possible.<br>" +
                                     "<hr>Ticket content :<br>" + ticket.Description);
                }

                return(ticket.Id);
            }
        public void ProcessSuccessResult(string zdj_src, string hrefLink, IEnumerable <HtmlNode> nazwa, string rozmiar, decimal amount)
        {
            Console.WriteLine($"[{DateTime.Now}]  udalo sie!!!!");
            LimangoProduct processingProduct = new LimangoProduct()
            {
                Name = nazwa.First().InnerText, Cost = amount, Size = rozmiar
            };

            Console.WriteLine(processingProduct.ToString());

            string htmlBody = @"<!DOCTYPE html>
                                <html>
                                <body>
                                <h1>" + processingProduct.Name + @"</h1>
                                <p>" + rozmiar + "   za: " + processingProduct.Cost + " zł" + @"</p>
                                <img src=" + zdj_src + @"><br>
                                <a href=""" + hrefLink + @"""> Link do strony </a>
                                </ body >
                                </ html > ";

            logger.LogInformation("Sending email \n" + processingProduct.ToString());
            email.SendEmail(processingProduct.Name, htmlBody);
        }
Exemplo n.º 26
0
        public async Task BuildCheckoutEmail(string emailAddress, string name, List <CartItem> items, string address, decimal total)
        {
            List <EmailItem> newItems   = new List <EmailItem>();
            string           templateId = "d-baa668b986ef47f79ef56df8a2674db8";

            foreach (var item in items)
            {
                newItems.Add(new EmailItem
                {
                    ImgSrc    = item.Product.ImageUrl,
                    Qty       = item.Qty,
                    ItemName  = item.Product.Name,
                    ItemTotal = item.Qty * item.Product.Price
                });
            }

            List <Personalization> personalizations = new List <Personalization>();

            personalizations.Add(new Personalization()
            {
                Tos = new List <EmailAddress>
                {
                    new EmailAddress(emailAddress)
                },
                Subject      = "Thanks for your purchase!",
                TemplateData = new ReceiptTemplateData()
                {
                    FullName  = name,
                    Date      = DateTime.Now.ToString(),
                    Address   = address,
                    Total     = total,
                    CartItems = newItems
                }
            });
            await _email.SendEmail(templateId, personalizations);
        }
Exemplo n.º 27
0
 public void NotifyStaff()
 {
     email.SendEmail();
 }
Exemplo n.º 28
0
        private void sendButtonClicked(object sender, EventArgs ea)
        {
            RunOnUiThread(() => {
                Toast.MakeText(this, "Sending Mail...", ToastLength.Short).Show();
            });

            TextView fromAddrView = FindViewById <TextView>(Resource.Id.editTextFromAddress);
            TextView fromNameView = FindViewById <TextView>(Resource.Id.editTextFromName);
            TextView toAddrView   = FindViewById <TextView>(Resource.Id.editTextToAddress);

            String        fromAddress = fromAddrView.Text;
            String        fromName    = fromNameView.Text;
            List <String> toAddresses = new List <string>();

            toAddresses.Add(toAddrView.Text);

            RadioGroup radios = FindViewById <RadioGroup>(Resource.Id.radioGroup1);

            switch (radios.CheckedRadioButtonId)
            {
            case Resource.Id.radioButtonGmail:
                service = new GMail(
                    this,
                    "[Gmail Client ID]",
                    "",
                    "com.cloudrail.UnifiedEmail:/oauth2redirect",
                    "someState"
                    );
                ((GMail)service).UseAdvancedAuthentication();
                break;

            case Resource.Id.radioButtonMailjet:
                service = new MailJet(
                    this,
                    "[MailJet Client ID]",
                    "[MailJet Client Secret]"
                    );
                break;

            case Resource.Id.radioButtonSendgrid:
                service = new SendGrid(
                    this,
                    "[SendGrid App Key]"
                    );
                break;
            }


            new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                // run in background
                service.SendEmail(
                    fromAddress,
                    fromName,
                    toAddresses,
                    "CloudRail is awesome!",
                    "Go ahead and try it for yourself!",
                    null,
                    null,
                    null,
                    null
                    );
                RunOnUiThread(() => {
                    Toast.MakeText(this, "Mail was send", ToastLength.Short).Show();
                });
            })).Start();
        }
Exemplo n.º 29
0
        public async Task <bool> ReceivedBuyer(ReceivedBuyerDTO receivedBuyerDTO)
        {
            try
            {
                using (var db = new SocialNetworkDeveloperContext())
                {
                    using (var transaction = db.Database.BeginTransaction())
                    {
                        try
                        {
                            var buyOrder = await db.OrdenesCompras.FirstOrDefaultAsync(x => x.IdOrdenCompra == receivedBuyerDTO.IdBuyOrder);

                            if (buyOrder == null)
                            {
                                return(false);
                            }

                            var buyer = await _userServices.GetUserByID((int)buyOrder.IdUsuario);

                            buyOrder.EstadoOrdenCompra = 4; //recibido
                            db.Update(buyOrder).State  = EntityState.Modified;
                            await db.SaveChangesAsync();

                            //actualizacion orden de compra
                            var saleOrder = await db.OrdenesVentas.FirstOrDefaultAsync(x => x.IdOrdenVenta == receivedBuyerDTO.IdSaleOrder);

                            if (saleOrder != null)
                            {
                                saleOrder.EstadoOrdenVenta = 4; //entregado
                                db.Update(saleOrder).State = EntityState.Modified;
                                await db.SaveChangesAsync();
                            }

                            //inserto raiting de publicacion
                            Rating rating = new Rating()
                            {
                                Rating1           = receivedBuyerDTO.Raiting,
                                FechaHoraCreacion = DateTime.Now,
                                IdPublicacion     = buyOrder.IdPublicacion,
                                IdUsuario         = buyOrder.IdUsuario
                            };
                            db.Ratings.Add(rating);
                            await db.SaveChangesAsync();

                            //actualizar publicación
                            //var publication = await _publicationServices.GetPublicationById((int)buyOrder.IdPublicacion);
                            var publication = await db.Publicaciones.FirstOrDefaultAsync(x => x.IdPublicacion == buyOrder.IdPublicacion);

                            //if (publication != null)
                            //{
                            //    publication.Raiting = receivedBuyerDTO.Raiting;

                            //    db.Update(publication).State = EntityState.Modified;
                            //    await _context.SaveChangesAsync();
                            //}


                            var seller = await _userServices.GetUserByID((int)publication.IdUsuario);


                            EmailDTO emailDTO = new EmailDTO()
                            {
                                EmailBuyer     = buyer.CorreoElectronico,
                                EmailSeller    = seller.CorreoElectronico,
                                Title          = string.Format("Su compra/venta de la Publicacion {0} fue Entregada", publication.Titulo),
                                MessagesSeller = string.Format(@"Estimado/a <b>{0}</b> el comprador acaba de confirmar de recibido la mercaderia, gracias por utilizar SNB&S, 
                                                    <br/> 
                                                    Detalle de la Venta 
                                                    <br/>
                                                    Publicación: <b>{1}</b>
                                                    <br/>
                                                    Cantidad: <b>{2}</b>
                                                     <br/>
                                                    Cliente: <b>{3}</b>
                                                    <br/> 
                                                    Telefono: <b>{4}</b>
                                                    <br/>
                                                    Total: <b>{5}</b>"
                                                               , seller.NombreCompleto, publication.Titulo, saleOrder.Cantidad, buyer.NombreCompleto, buyer.TelefonoContacto, saleOrder.TotalVenta),

                                MessagesBuyer = string.Format(@"Estimado/a <b>{0}</b> acaba de confirmar de recibido la mercaderia de su compra, gracias por utilizar SNB&S, 
                                                    <br/> 
                                                    Detalle De la Compra 
                                                    <br/>
                                                    Publicación: <b>{1}</b>
                                                    <br/>
                                                    Cantidad: <b>{2}</b>
                                                    <br/>
                                                    Total: <b>{3}</b>
                                                    <br/>
                                                    Vendedor: <b>{4}</b>
                                                    <br/>
                                                    Telefono: <b>{5}</b>"

                                                              , buyer.NombreCompleto, publication.Titulo, saleOrder.Cantidad, Math.Round((decimal)saleOrder.TotalVenta, 2), seller.NombreCompleto, seller.TelefonoContacto),
                            };
                            //si falla envio correo no registrar la aprobacion
                            var email = await _emailServices.SendEmail(emailDTO);

                            if (!email)
                            {
                                throw new Exception();
                            }

                            //envio sms twilio
                            var smsSeller = await _twilioServices.SendSMS(seller.TelefonoContacto, "Una Venta fue Entregada con Exito en SNB&S");

                            if (!smsSeller)
                            {
                                throw new Exception();
                            }

                            var smsBuyer = await _twilioServices.SendSMS(buyer.TelefonoContacto, "Acabas de Confirmar de Recibido tu Compra en SNB&S");

                            if (!smsBuyer)
                            {
                                throw new Exception();
                            }


                            await transaction.CommitAsync();

                            return(true);
                        }
                        catch (Exception e)
                        {
                            transaction.Rollback();
                            log.ErrorFormat("Error al ejecutar transaccion para confirmar de recibido la mercaderia ReceivedBuyer() {0} : {1} ", e.Source, e.Message);

                            return(false);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("Error al actualizar orden de compra a recibido ReceivedBuyer()  {0} : {1} ", e.Source, e.Message);
                return(false);

                throw;
            }
        }
Exemplo n.º 30
0
        public async Task <bool> AddSale(SaleOrderDTO saleOrderDTO)
        {
            using (var db = new SocialNetworkDeveloperContext())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        var seller = await _userServices.GetUserByID((int)saleOrderDTO.IdUsuario);

                        var buyer = await _userServices.GetUserByID((int)saleOrderDTO.IdComprador);

                        var publication = await _publicationServices.GetPublicationById((int)saleOrderDTO.IdPublicacion);

                        var saleOrder = _mapper.Map <OrdenesVenta>(saleOrderDTO);
                        saleOrder.FechaHoraOrdenVenta = DateTime.Now;
                        //saleOrder.TotalVentaConIva = saleOrderDTO.Cantidad * (publication.Precio + (publication.Precio * 0.13m));
                        saleOrder.TotalVenta       = saleOrderDTO.Cantidad * publication.Precio;
                        saleOrder.EstadoOrdenVenta = 1; //pendiente
                        db.OrdenesVentas.Add(saleOrder);
                        await db.SaveChangesAsync();

                        //Creacion de orden de compra
                        OrdenesCompra objCompra = new OrdenesCompra()
                        {
                            IdOrdenVenta         = saleOrder.IdOrdenVenta,
                            IdPublicacion        = publication.IdPublicacion,
                            IdUsuario            = buyer.IdUsuario,
                            FechaHoraOrdenCompra = DateTime.Now,
                            //TotalCompraConIva = saleOrderDTO.Cantidad * (publication.Precio + (publication.Precio * 0.13m)),
                            TotalCompra       = saleOrderDTO.Cantidad * publication.Precio,
                            EstadoOrdenCompra = 1, //pendiente
                            Cantidad          = saleOrderDTO.Cantidad
                        };
                        db.OrdenesCompras.Add(objCompra);
                        await db.SaveChangesAsync();

                        EmailDTO emailDTO = new EmailDTO()
                        {
                            EmailBuyer     = buyer.CorreoElectronico,
                            EmailSeller    = seller.CorreoElectronico,
                            Title          = string.Format("Se Realizo una solicitud de compra/venta de la Publicaicon {0}", publication.Titulo),
                            MessagesSeller = string.Format(@"Estimado/a <b>{0}</b> se ha realizado una solicitud de venta a travez de nuestra aplicación, 
                                                    <br/> 
                                                    Detalle De la Venta 
                                                    <br/>
                                                    Publicación: <b>{1}</b>
                                                    <br/>
                                                    Cantidad: <b>{2}</b>
                                                     <br/>
                                                    Cliente: <b>{3}</b>
                                                    <br/> 
                                                    Telefono: <b>{4}</b>
                                                    <br/> 
                                                    Dirección Entrega: <b>{5}</b>
                                                    <br/> 
                                                    Comentario: <b>{6}</b>"
                                                           , seller.NombreCompleto, publication.Titulo, saleOrderDTO.Cantidad, buyer.NombreCompleto, buyer.TelefonoContacto, saleOrderDTO.DireccionEntrega, saleOrderDTO.Comentario),

                            MessagesBuyer = string.Format(@"Estimado/a <b>{0}</b> se ha realizado una solicitud de compra a travez de nuestra aplicación, 
                                                    <br/> 
                                                    Detalle De la Compra 
                                                    <br/>
                                                    Publicación: <b>{1}</b>
                                                    <br/>
                                                    Cantidad: <b>{2}</b>"

                                                          , buyer.NombreCompleto, publication.Titulo, saleOrderDTO.Cantidad),
                        };
                        //si falla envio correo no registrar la venta
                        var email = await _emailServices.SendEmail(emailDTO);

                        if (!email)
                        {
                            throw new Exception();
                        }

                        //envio sms twilio
                        var smsSeller = await _twilioServices.SendSMS(seller.TelefonoContacto, "Se Realizo una solicitud de compra/venta en SNB&S");

                        if (!smsSeller)
                        {
                            throw new Exception();
                        }

                        var smsBuyer = await _twilioServices.SendSMS(buyer.TelefonoContacto, "Acabas de realizar una solicitud de compra en SNB&S");

                        if (!smsBuyer)
                        {
                            throw new Exception();
                        }

                        await transaction.CommitAsync();

                        return(true);
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        return(false);
                    }
                }
            }
        }
Exemplo n.º 31
0
 public void NotifyEmployee()
 {
     email.SendEmail();
 }