Ejemplo n.º 1
1
        public async Task CreateNewMeeting()
        {
            try
            {
                Microsoft.Graph.Event evt = new Microsoft.Graph.Event();

                Location location = new Location();
                location.DisplayName = tbLocation.Text;

                ItemBody body = new ItemBody();
                body.Content = tbBody.Text;
                body.ContentType = BodyType.Html;

                List<Attendee> attendees = new List<Attendee>();
                Attendee attendee = new Attendee();
                EmailAddress email = new EmailAddress();
                email.Address = tbToRecipients.Text;
                attendee.EmailAddress = email;
                attendee.Type = AttendeeType.Required;
                attendees.Add(attendee);

                evt.Subject = tbSubject.Text;
                evt.Body = body;
                evt.Location = location;
                evt.Attendees = attendees;

                DateTimeTimeZone dtStart = new DateTimeTimeZone();
                dtStart.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dts = dtpStartDate.Value.Date + dtpStartTime.Value.TimeOfDay;
                dtStart.DateTime = dts.ToString();
                
                DateTimeTimeZone dtEnd = new DateTimeTimeZone();
                dtEnd.TimeZone = TimeZoneInfo.Local.Id;
                DateTime dte = dtpEndDate.Value.Date + dtpEndTime.Value.TimeOfDay;
                dtEnd.DateTime = dte.ToString();

                evt.Start = dtStart;
                evt.End = dtEnd;
                
                // log the request info
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().Headers.ToString());
                sdklogger.Log(graphClient.Me.Events.Request().GetHttpRequestMessage().RequestUri.ToString());

                // send the new message
                var createdEvent = await graphClient.Me.Events.Request().AddAsync(evt);

                // log the send and associated id
                sdklogger.Log("Meeting Sent : Id = " + createdEvent.Id);
            }
            catch (Exception ex)
            {
                sdklogger.Log("NewMeetingSend Failed: " + ex.Message);
                sdklogger.Log(ex.Message);
            }
            finally
            {
                // close the form
                Close();
            }
        }
Ejemplo n.º 2
0
        public void Equals_DifferentAddressesAndNullTypes_AreNotEqual()
        {
            var emailAddress1 = new EmailAddress("*****@*****.**", null);
            var emailAddress2 = new EmailAddress("*****@*****.**", null);

            Assert.NotEqual(emailAddress1, emailAddress2);
        }
        /// <summary>
        /// Checks the access an account has with an organization..
        /// </summary>
        /// <param name="name">The organization name.</param>
        /// <param name="accountId">The account identifier.</param>
        /// <param name="allowAdmin">if set to <c>true</c> allow admin.</param>
        /// <param name="allowWrite">if set to <c>true</c> allow write.</param>
        /// <param name="allowRead">if set to <c>true</c> allow read.</param>
        public void CheckAccess(
            DomainLabel name,
            EmailAddress accountId,
            out bool allowAdmin,
            out bool allowWrite,
            out bool allowRead)
        {
            allowAdmin = false;
            allowWrite = false;
            allowRead = false;

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (accountId == null)
            {
                throw new ArgumentNullException("accountId");
            }

            CloudTable orgMemberTable = this.GetOrganizationMembershipTable();
            TableOperation getOrgMember = TableOperation.Retrieve<OrganizationMembershipEntity>(
                name.ToString(),
                accountId.ToString());
            TableResult result = orgMemberTable.Execute(getOrgMember);
            OrganizationMembershipEntity entity = result.Result as OrganizationMembershipEntity;
            if (entity != null)
            {
                allowRead = true;
                allowWrite = entity.AllowWrite;
                allowAdmin = entity.AllowAdmin;
            }
        }
Ejemplo n.º 4
0
        public void Equals_SameAddressAndNullTypes_AreEqual()
        {
            var emailAddress1 = new EmailAddress("*****@*****.**", null);
            var emailAddress2 = new EmailAddress("*****@*****.**", null);

            Assert.Equal(emailAddress1, emailAddress2);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Activates the given account if it is not already activated.
        /// </summary>
        /// <param name="accountId">the account to activate.</param>
        public void ActivateAccount(
            EmailAddress accountId)
        {
            CloudTable loginTable = this.GetLoginTable();
            CloudTable accountTable = this.GetAccountTable();

            LoginEntity existingEntity = FindExistingLogin(loginTable, accountId);
            AccountEntity existingAccount = FindExistingAccount(accountTable, accountId);
            if (existingEntity == null || existingAccount == null)
            {
                throw new InvalidOperationException("Account does not exist.");
            }

            if (existingEntity.Activated)
            {
                return;
            }

            existingAccount.ActivatedTime = DateTime.UtcNow;
            existingEntity.Activated = true;
            TableOperation updateAccountOperation = TableOperation.Replace(existingAccount);
            accountTable.Execute(updateAccountOperation);
            TableOperation updateLoginOperation = TableOperation.Replace(existingEntity);
            loginTable.Execute(updateLoginOperation);
        }
Ejemplo n.º 6
0
 public ActionResult Create(EmailAddress Model)
 {
     return Dispatcher.Create(
         DataModel: Model,
         SuccessResult: m => ModalRedirectToLocal(Url.Action("Index", "Settings", new { Area = "Account" }, null)),
         InvalidResult: m => PartialView(m));
 }
Ejemplo n.º 7
0
        public void EmailAddress_TwoAddressesDifferentValue_AreNotEqual()
        {
            var address = new EmailAddress("*****@*****.**", "test");
            var address2 = new EmailAddress("*****@*****.**", "test");

            Assert.IsTrue(address != address2);
        }
Ejemplo n.º 8
0
        public void Equals_SameAddressAndDifferentTypes_AreNotEqual()
        {
            var emailAddress1 = new EmailAddress("*****@*****.**", EmailAddressType.Personal);
            var emailAddress2 = new EmailAddress("*****@*****.**", EmailAddressType.Work);

            Assert.NotEqual(emailAddress1, emailAddress2);
        }
Ejemplo n.º 9
0
 public AccountRegistration(Username username, Password password, FullName fullName, EmailAddress email)
 {
     Email = email;
     Username = username;
     Password = password;
     FullName = fullName;
 }
Ejemplo n.º 10
0
        public void Equals_SameAddressAndSameTypes_AreEqual()
        {
            var emailAddress1 = new EmailAddress("*****@*****.**", EmailAddressType.Personal);
            var emailAddress2 = new EmailAddress("*****@*****.**", EmailAddressType.Personal);

            Assert.Equal(emailAddress1, emailAddress2);
        }
        public void Handler_ReturnsNullUser_WhenFound_ByUnverifiedEmail()
        {
            var nameOrEmail = FakeData.Email();
            var query = new UserByNameOrVerifiedEmail(nameOrEmail);
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            Expression<Func<UserBy, bool>> expectedUserQuery =
                x => x.Name == nameOrEmail;
            queries.Setup(x => x.Execute(It.Is(expectedUserQuery)))
                .Returns(Task.FromResult(null as User));
            var user = new User { Name = FakeData.String(), };
            var emailAddress = new EmailAddress
            {
                Value = nameOrEmail,
                UserId = user.Id,
                User = user,
                IsVerified = false,
            };
            Expression<Func<EmailAddressBy, bool>> expectedEmailQuery =
                x => x.Value == nameOrEmail && x.IsVerified == true;
            queries.Setup(x => x.Execute(It.Is(expectedEmailQuery)))
                .Returns(Task.FromResult(emailAddress));
            var handler = new HandleUserByNameOrVerifiedEmailQuery(queries.Object);

            User result = handler.Handle(query).Result;

            result.ShouldBeNull();
            queries.Verify(x => x.Execute(It.Is(expectedUserQuery)), Times.Once);
            queries.Verify(x => x.Execute(It.Is(expectedEmailQuery)), Times.Once);
        }
Ejemplo n.º 12
0
        public void EmailAddress_TwoAddressesSameValue_AreEqual()
        {
            var address = new EmailAddress("*****@*****.**", "test");
            var address2 = new EmailAddress("*****@*****.**", "test");

            Assert.IsTrue(address == address2);
        }
Ejemplo n.º 13
0
        public void EqualsMethod()
        {
            var email1 = new EmailAddress("*****@*****.**");
            var email2 = new EmailAddress("*****@*****.**");

            Assert.True(email1.Equals(email2));
        }
        public async Task<Message> ComposeRepairCompletedEmailMessage(int incidentId)
        {
            var incident = await GetIncident(incidentId);
            var attachments = await GetInspectionOrRepairPhotosAsAttachments("Room Inspection Photos", incident.sl_inspectionID.Id, incident.sl_roomID.Id);

            var property = incident.sl_propertyID;

            var propertyOwnerRecipientEmail = new EmailAddress { Address = property.sl_emailaddress, Name = property.sl_owner };
            var dispacherRecipientEmail = new EmailAddress { Address = DispatcherEmail, Name = DispatcherName };

            var bodyTemplate = System.IO.File.ReadAllText(bodyTemplateFile);
            var viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("InspectionPhotosAttachments", attachments);
            var body = RazorEngine.Razor.Parse(bodyTemplate, incident, viewBag, "EmailBody");

            var message = new Message
            {
                Subject = string.Format("Repair Report - {0} - {1:MM/dd/yyyy}", property.Title, DateTime.UtcNow),
                Importance = Importance.Normal,
                Body = new ItemBody
                {
                    ContentType = BodyType.HTML,
                    Content = body
                },
            };
            message.ToRecipients.Add(new Recipient { EmailAddress = propertyOwnerRecipientEmail });
            message.CcRecipients.Add(new Recipient { EmailAddress = dispacherRecipientEmail });
            foreach (var attachment in attachments)
                message.Attachments.Add(attachment);

            return message;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates the system account.
        /// </summary>
        /// <param name="identifier">The identifier.</param>
        /// <param name="displayName">The display name.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <param name="identityProviderName">Name of the identity provider.</param>
        /// <param name="identityProviderUri">The identity provider URI.</param>
        /// <returns>
        /// A SystemAccount.
        /// </returns>
        public SystemAccount CreateSystemAccount(string identifier, string displayName, EmailAddress emailAddress, string identityProviderName, string identityProviderUri   )
        {
            var account = new SystemAccount ( identifier, displayName, emailAddress, identityProviderName, identityProviderUri );
            _repository.MakePersistent ( account );

            return account;
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Code"/> class.
 /// </summary>
 /// <param name="accountId">The account identifier.</param>
 /// <param name="applicationName">Name of the application.</param>
 /// <param name="expires">The expires.</param>
 /// <param name="hash">The hash.</param>
 private OAuth2Code(EmailAddress accountId, DomainLabel applicationName, DateTime expires, byte[] hash)
     : base(hash)
 {
     this.accountId = accountId;
     this.applicationName = applicationName;
     this.expires = expires;
 }
Ejemplo n.º 17
0
        public void Equals_SameAddressAndOneNullType_AreNotEqual()
        {
            var emailAddress1 = new EmailAddress("*****@*****.**", null);
            var emailAddress2 = new EmailAddress("*****@*****.**", EmailAddressType.Work);

            Assert.NotEqual(emailAddress1, emailAddress2);
        }
Ejemplo n.º 18
0
        public void EqualsOperator()
        {
            var email1 = new EmailAddress("*****@*****.**");
            var email2 = new EmailAddress("*****@*****.**");

            Assert.True(email1 == email2);
        }
 public ContactInformation(EmailAddress emailAddress, PostalAddress postalAddress, Telephone primaryTelephone,
     Telephone secondaryTelephone)
 {
     this.EmailAddress = emailAddress;
     this.PostalAddress = postalAddress;
     this.PrimaryTelephone = primaryTelephone;
     this.SecondaryTelephone = secondaryTelephone;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocationEmailAddress"/> class.
        /// </summary>
        /// <param name="emailAddress">
        /// The email address.
        /// </param>
        /// <param name="emailAddressType">
        /// The email address type.
        /// </param>
        public LocationEmailAddress(EmailAddress emailAddress, LocationEmailAddressType emailAddressType)
        {
            Check.IsNotNull(emailAddress, () => EmailAddress);
            Check.IsNotNull(emailAddressType, () => LocationEmailAddressType);

            _emailAddress = emailAddress;
            _locationEmailAddressType = emailAddressType;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AgencyEmailAddress"/> class.
        /// </summary>
        /// <param name="emailAddress">
        /// The email address.
        /// </param>
        /// <param name="emailAddressType">
        /// The email address type.
        /// </param>
        public AgencyEmailAddress(EmailAddress emailAddress, AgencyEmailAddressType emailAddressType)
        {
            Check.IsNotNull(emailAddress, () => EmailAddress);
            Check.IsNotNull(emailAddressType, () => AgencyEmailAddressType);

            _emailAddress = emailAddress;
            _agencyEmailAddressType = emailAddressType;
        }
Ejemplo n.º 22
0
        public bool AcceptRecipient(SMTPContext context, EmailAddress recipient)
        {
            bool match = recipient.Username.ToLower() == "text";

            ServiceLocator.Current.Log.WarningIf(!match, "Received mail not to [email protected]. Instead, " + recipient.ToString());

            return match;
        }
Ejemplo n.º 23
0
 public SpeakerDocument(Id id, Version version, SpeakerBio bio, PhoneNumber phoneNumber, EmailAddress emailAddress, SpeakerName name)
 {
     Bio = bio;
     Email = emailAddress;
     Id = id;
     PhoneNumber = phoneNumber;
     Name = name;
     Version = version;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Sends activation email.
 /// </summary>
 /// <param name="accountId">the account to activate.</param>
 /// <param name="activationUrl">the activation url.</param>
 public void SendActivationEmail(EmailAddress accountId, Uri activationUrl)
 {
     using (MailMessage message = new MailMessage(this.info.From, accountId.ToString()))
     {
         message.Subject = "Account Activation Notification";
         message.Body = activationUrl.ToString();
         this.SendMailMessage(message);
     }
 }
Ejemplo n.º 25
0
        private void SetUserEmailIfNeeded(UserId userId, EmailAddress email)
        {
            UserDetails userDetails = _readModel.GetUserDetails(userId);

            if (String.IsNullOrWhiteSpace(userDetails.Email))
            {
                _bus.Send(new SetUserEmail(userId, email));
            }
        }
 public static void OnEmailAddressChanged(EmailAddress oldAddress, EmailAddress newAddress)
 {
     var handler = EmailAddressChanged;
     if (handler != null)
     {
         var args = new EmailAddressChangedEventArgs { OldAddress = oldAddress, NewAddress = newAddress };
         handler(null, args);
     }
 }
Ejemplo n.º 27
0
 public SpeakerDocument(Id id, Version version, SpeakerBio bio, PhoneNumber phoneNumber, EmailAddress emailAddress, Name name)
 {
     Bio = (string) bio;
     Email = (string) emailAddress;
     Id = (Guid) id;
     PhoneNumber = (string) phoneNumber;
     Name = (string) name;
     Version = (int)version;
 }
Ejemplo n.º 28
0
		public Microsoft.Communications.Contacts.Contact GetCanonicalContact(Microsoft.LiveFX.Client.Contact c)
		{
			Microsoft.Communications.Contacts.Contact contact = new Microsoft.Communications.Contacts.Contact();
			//LiveItemCollection<Profile, ProfileResource> profiles = c.Profiles;

			contact.Names.Add(new Name(c.Resource.GivenName, c.Resource.MiddleName, c.Resource.FamilyName, NameCatenationOrder.FamilyGivenMiddle));

			foreach (ContactPhone cp in c.Resource.PhoneNumbers)
			{
				PhoneNumber pn = new PhoneNumber(cp.Value);
				if (cp.Type == ContactPhone.ContactPhoneType.Business ||
					cp.Type == ContactPhone.ContactPhoneType.Business2)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Voice, PropertyLabels.Business);
				else if (cp.Type == ContactPhone.ContactPhoneType.BusinessMobile)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Cellular, PropertyLabels.Business);
				else if (cp.Type == ContactPhone.ContactPhoneType.Mobile)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Cellular);
				else if (cp.Type == ContactPhone.ContactPhoneType.Personal)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Voice, PropertyLabels.Personal);
				else if (cp.Type == ContactPhone.ContactPhoneType.Personal2)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Voice, PropertyLabels.Personal);
				else if (cp.Type == ContactPhone.ContactPhoneType.Other)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Voice);
				else if (cp.Type == ContactPhone.ContactPhoneType.OtherFax)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Fax);
				else if (cp.Type == ContactPhone.ContactPhoneType.Fax)
					contact.PhoneNumbers.Add(pn, PhoneLabels.Fax);
				else 
					contact.PhoneNumbers.Add(pn);
			}

			if (c.Resource.WindowsLiveId != null && c.Resource.WindowsLiveId.Trim() != null)
				contact.EmailAddresses.Add(new EmailAddress(c.Resource.WindowsLiveId, "Windows Live ID"), PropertyLabels.Preferred);

			foreach (ContactEmail ce in c.Resource.Emails)
			{
				EmailAddress ea = new EmailAddress(ce.Value);
				if (ce.Type == ContactEmail.ContactEmailType.Personal)
					contact.EmailAddresses.Add(ea, PropertyLabels.Personal);
				else if (ce.Type == ContactEmail.ContactEmailType.Business)
					contact.EmailAddresses.Add(ea, PropertyLabels.Business);
				else if (ce.Type == ContactEmail.ContactEmailType.Other)
					contact.EmailAddresses.Add(ea);
				else
					contact.EmailAddresses.Add(ea);
			}

			DateTime lastChanged = c.Resource.LastUpdatedTime.DateTime.ToUniversalTime();
			contact.Dates.Add(lastChanged, "LastModificationTime");

			string absoluteUri = c.Resource.Id;
			Guid guid = new Guid(absoluteUri.PadLeft(32, '0'));
			contact.ContactIds.Add(guid, "Live");

			return contact;
		}
Ejemplo n.º 29
0
        /// <summary>
        /// Creates an account with given id and password.
        /// </summary>
        /// <param name="accountId">The account id.</param>
        /// <param name="password">The account password.</param>
        public void CreateAccount(
            EmailAddress accountId,
            SecureString password)
        {
            PasswordHash passwordHash = PasswordHash.Create(password);

            CloudTable loginTable = this.GetLoginTable();
            CloudTable accountTable = this.GetAccountTable();

            LoginEntity existingEntity = FindExistingLogin(loginTable, accountId);
            if (existingEntity != null)
            {
                if (existingEntity.Activated)
                {
                    throw new InvalidOperationException("account already activated.");
                }

                AccountEntity existingAccount = FindExistingAccount(accountTable, accountId);
                if (existingAccount == null)
                {
                    existingAccount = new AccountEntity();
                    existingAccount.PartitionKey = accountId.Domain;
                    existingAccount.RowKey = accountId.LocalPart;
                }
                else if (existingAccount.CreatedTime + ActivationTimeout > DateTime.UtcNow)
                {
                    throw new InvalidOperationException("Account creation cannot be retried yet.");
                }

                existingEntity.Salt = passwordHash.Salt;
                existingEntity.SaltedHash = passwordHash.Hash;
                TableOperation replaceOperation = TableOperation.InsertOrReplace(existingEntity);
                loginTable.Execute(replaceOperation);

                existingAccount.CreatedTime = DateTime.UtcNow;
                TableOperation insertAccountOperation = TableOperation.InsertOrReplace(existingAccount);
                accountTable.Execute(insertAccountOperation);
            }
            else
            {
                LoginEntity newEntity = new LoginEntity();
                newEntity.PartitionKey = accountId.Domain;
                newEntity.RowKey = accountId.LocalPart;
                newEntity.Salt = passwordHash.Salt;
                newEntity.SaltedHash = passwordHash.Hash;
                TableOperation insertOperation = TableOperation.Insert(newEntity);
                loginTable.Execute(insertOperation);

                AccountEntity newAccount = new AccountEntity();
                newAccount.PartitionKey = accountId.Domain;
                newAccount.RowKey = accountId.LocalPart;
                newAccount.CreatedTime = DateTime.UtcNow;
                TableOperation insertAccountOperation = TableOperation.InsertOrReplace(newAccount);
                accountTable.Execute(insertAccountOperation);
            }
        }
        public UserRegistered(TenantId tenantId, string userName, FullName name, EmailAddress emailAddress)
        {
            this.TenantId = tenantId.Id;
            this.UserName = userName;
            this.Name = name;
            this.EmailAddress = emailAddress;

            this.EventVersion = 1;
            this.OccurredOn = DateTime.Now;
        }
Ejemplo n.º 31
0
 public void Can_parse_standard_address()
 {
     EmailAddress.Parse("*****@*****.**").ToString().ShouldBe("*****@*****.**");
 }
Ejemplo n.º 32
0
     : super()
 {
     _emailAddress = new EmailAddress();
 }
Ejemplo n.º 33
0
 public override string ToString()
 {
     return(CustomerNumber + ", " + FirstName + ", " + LastName + ", " + EmailAddress.Print() + ", " + CustAdresse.ToString() + ", " + LastAccess.ToShortDateString() + ", " + AccountBalance);
 }
Ejemplo n.º 34
0
 public string PrintCustomerCrypt()
 {
     return(Crypto.EncodeLine(new string[] { CustomerNumber.ToString(), FirstName, LastName, EmailAddress.Print(), CustAdresse.ToCSVString(), LastAccess.ToShortDateString(), AccountBalance.ToString() }));
 }
Ejemplo n.º 35
0
 public HomeController()
 {
     _emailAddress     = ObjectFactory.GetInstance <EmailAddress>();
     _email            = ObjectFactory.GetInstance <Email>();
     _configRepository = ObjectFactory.GetInstance <IConfigRepository>();
 }
Ejemplo n.º 36
0
        public async Task <DialogTurnResult> AfterConfirmRecipient(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await _emailStateAccessor.GetAsync(sc.Context);

                // result is null when just update the recipient name. show recipients page should be reset.
                if (sc.Result == null)
                {
                    state.ShowRecipientIndex = 0;
                    return(await sc.BeginDialogAsync(Action.ConfirmRecipient));
                }

                var choiceResult = (sc.Result as FoundChoice)?.Value.Trim('*');
                if (choiceResult != null)
                {
                    if (choiceResult == General.Intent.Next.ToString())
                    {
                        state.ShowRecipientIndex++;
                        return(await sc.BeginDialogAsync(Action.ConfirmRecipient));
                    }

                    if (choiceResult == UpdateUserDialogOptions.UpdateReason.TooMany.ToString())
                    {
                        state.ShowRecipientIndex++;
                        return(await sc.BeginDialogAsync(Action.ConfirmRecipient, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.TooMany)));
                    }

                    if (choiceResult == General.Intent.Previous.ToString())
                    {
                        if (state.ShowRecipientIndex > 0)
                        {
                            state.ShowRecipientIndex--;
                        }

                        return(await sc.BeginDialogAsync(Action.ConfirmRecipient));
                    }

                    var recipient    = new Recipient();
                    var emailAddress = new EmailAddress
                    {
                        Name    = choiceResult.Split(": ")[0],
                        Address = choiceResult.Split(": ")[1],
                    };
                    recipient.EmailAddress = emailAddress;
                    if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                    {
                        state.Recipients.Add(recipient);
                    }

                    state.ConfirmRecipientIndex++;
                }

                if (state.ConfirmRecipientIndex < state.NameList.Count)
                {
                    return(await sc.BeginDialogAsync(Action.ConfirmRecipient));
                }

                return(await sc.EndDialogAsync(true));
            }
            catch (Exception ex)
            {
                throw await HandleDialogExceptions(sc, ex);
            }
        }
 public Contact(EmailAddress emailAddress) : base(emailAddress)
 {
 }
        public async Task <Response> ExecuteCorreoSolicitudAprobada(string correo, Entity entity)
        {
            var solicitud = (SolicitudHotel)entity;
            //correo = "*****@*****.**";
            var cedulaJ = solicitud.CedulaJuridica;
            var link    = "";
            var datos   = "";
            var usuario = new Usuario
            {
                Identificacion = solicitud.IdUsuario,
                Correo         = correo
            };
            UsuarioManager mngU = new UsuarioManager();
            var            c    = mngU.Validar(usuario);

            if (c != null)
            {
                datos = "" + solicitud.CodigoSolicitud;
                link  = "https://adtripapp.azurewebsites.net/Home/vLogin/";
            }
            else
            {
                datos = "" + solicitud.CodigoSolicitud;
                link  = "https://adtripapp.azurewebsites.net/Home/vRegistroUsuarios/";
            }
            var membresia = solicitud.Membrecia;

            var client = new SendGridClient("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");

            var from             = new EmailAddress("*****@*****.**", "Adtrip");              //destinatario
            var subject          = "Solicitud aprobada";                                              //asunto del correo
            var to               = new EmailAddress(correo, "Usuario");
            var plainTextContent = "Solicitud de hotel aprobada, por favor continue con el registro"; // texto plano
            var htmlContent      = @"<head>
            <link href=""https://fonts.googleapis.com/css?family=Montserrat"" rel=""stylesheet"">
        </head>
        <div style=""font-family: 'Montserrat', sans-serif; background-image: url('https://res.cloudinary.com/datatek/image/upload/v1563745950/correo_datatek_qpeykq.jpg'); 
        background-size: cover; "">
            <div style=""background:  rgba(0, 0, 0, 0.8); width:100%; height: 100%;"">
                <table style=""max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;"">
                    <tr>
                        <td>
                            <div style=""color: #fff; margin: 4% 10% 2%; font-family: sans-serif; text-shadow: 2px 2px 4px #000000"">
                                <div style=""width: 100%;margin:20px 0; display: inline-block;text-align: center"">
                                    <img style=""padding: 0; width: 150px; margin: 5px"" src=""https://res.cloudinary.com/datatek/image/upload/v1563746114/ADTRIP_LOGO_sfprzx.png"">
                                </div>
                                <h2 style=""color: #fff; margin: 0 0 7px; font-size: 34px; margin: 0 auto; text-align: center; padding-bottom: 40px"">Solicitud de hotel aprobada</h2>
                                <p style=""margin: 2px; font-size: 22px; padding-left: 20px; color: #fff;"">
                                    Por favor acepte la membresía en el registro:</p>
                                <ul style=""font-size: 18px; color: #fff; margin: 10px 0; padding-left: 50px;"">
                                    <li style=""padding: 10px;"">Membresía: $" + membresia + @"</li>
                                    <li style=""padding: 10px;"">Cédula jurídica del hotel: " + cedulaJ + @"</li>
                                </ul>
                                <div style=""width: 100%; text-align: center; padding-top: 20px; padding-bottom: 42px"">
                                    <a style=""text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #00cccc""
                                        href=""" + link + datos + @""">Ir a registro</a>                               
                                </div>
                                <p style=""color: #fff; font-size: 14px; text-align: center; margin: 30px 0 0; padding-bottom: 30px;"">Ir al registro para continuar</p>
                                </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>";
            //se crea el correo
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            Console.WriteLine(msg);
            var response = await client.SendEmailAsync(msg);

            Console.WriteLine(response);

            return(response);
        }
Ejemplo n.º 39
0
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            // Get the SendGrid key
            var apiKey = Configuration["SendGridKey"];

            // Create a new SendGrid client
            var client = new SendGridClient(apiKey);

            // From
            var from = new EmailAddress(details.FromEmail, details.FromName);

            // To
            var to = new EmailAddress(details.ToEmail, details.ToName);

            // Subject
            var subject = details.Subject;

            // Content
            var content = details.Content;

            // Create Email class ready to send
            var msg = MailHelper.CreateSingleEmail(
                from,
                to,
                subject,
                // Plain content
                details.IsHTML ? null : details.Content,
                // HTML content
                details.IsHTML ? details.Content : null);

            // Finally, send the email...
            var response = await client.SendEmailAsync(msg);

            // If we succeeded...
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                // Return successful response
                return(new SendEmailResponse());
            }

            // Otherwise, it failed...

            try
            {
                // Get the result in the body
                var bodyResult = await response.Body.ReadAsStringAsync();

                // Deserialize the response
                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                // Add any errors to the response
                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
                };

                // Make sure we have at least one error
                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    // Add an unknown error
                    // TODO: Localization
                    errorResponse.Errors = new List <string>(new[] { "Unknown error from email sending service. Please contact Fasetto support." });
                }

                // Return the response
                return(errorResponse);
            }
            catch (Exception ex)
            {
                // TODO: Localization

                // Break if we are debugging
                if (Debugger.IsAttached)
                {
                    var error = ex;
                    Debugger.Break();
                }

                // If something unexpected happened, return message
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Unknown error occurred" })
                });
            }
        }
Ejemplo n.º 40
0
 public void Login(string email, string password)
 {
     EmailAddress.SendKeys(email);
     Password.SendKeys(password);
     LoginBtn.Click();
 }
Ejemplo n.º 41
0
 public void Can_clean_gmail_address_missing_domain_suffix()
 {
     EmailAddress.Parse("adrian@gmail").ToString().ShouldBe("*****@*****.**");
 }
        private void RegisterAdministratorFor(
            Tenant tenant,
            FullName administorName,
            EmailAddress emailAddress,
            PostalAddress postalAddress,
            Telephone primaryTelephone,
            Telephone secondaryTelephone)
        {
            RegistrationInvitation invitation = tenant.OfferRegistrationInvitation("init").OpenEnded();
            string strongPassword             = new PasswordService().GenerateStrongPassword();

            // Publishes domain event UserRegistered.
            User admin = tenant.RegisterUser(
                invitation.InvitationId,
                "admin",
                strongPassword,
                Enablement.IndefiniteEnablement(),
                new Person(
                    tenant.TenantId,
                    administorName,
                    new ContactInformation(
                        emailAddress,
                        postalAddress,
                        primaryTelephone,
                        secondaryTelephone)));

            tenant.WithdrawInvitation(invitation.InvitationId);

            // Since this is a new entity, add it to
            // the collection-oriented repository.
            // Subsequent changes to the entity
            // are implicitly persisted.
            this.userRepository.Add(admin);

            // Publishes domain event RoleProvisioned.
            Role adminRole = tenant.ProvisionRole(
                "Administrator",
                string.Format("Default {0} administrator.", tenant.Name));

            // Publishes domain event UserAssignedToRole,
            // but not GroupUserAdded because the group
            // reference held by the role is an "internal" group.
            adminRole.AssignUser(admin);

            //if (adminRole.)

            // Since this is a new entity, add it to
            // the collection-oriented repository.
            // Subsequent changes to the entity
            // are implicitly persisted.
            this.roleRepository.Add(adminRole);

            DomainEventPublisher
            .Instance
            .Publish(new TenantAdministratorRegistered(
                         tenant.TenantId,
                         admin.Username,
                         administorName,
                         emailAddress,
                         admin.Username,
                         strongPassword));
        }
 private void __and_EmailAddressWasChanged()
 {
     eventStream.Add(CustomerEmailAddressChanged.Build(customerID, changedEmailAddress, changedConfirmationHash));
     emailAddress     = changedEmailAddress;
     confirmationHash = changedConfirmationHash;
 }
Ejemplo n.º 44
0
        public async Task <IHttpActionResult> NewProductFileFeedback(NewFeedbackDTO newFeedbackDTO)
        {
            string userName = User.Identity.Name;
            User   user     = db.Users.Where(_user => _user.UserName == userName).SingleOrDefault();

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ProductFile productFile = db.ProductFiles.Where(_productFile => _productFile.ID == newFeedbackDTO.ProductFileID)
                                      .Include(_productFile => _productFile.GroupsVisibleTo)
                                      .Include(_productFile => _productFile.Product.GroupsVisibleTo)
                                      .Include(_productFile => _productFile.Product.TeamMembers
                                               .Select(_teamMember => _teamMember.User))
                                      .Include(_productFile => _productFile.Product.Company)
                                      .Include(_productFile => _productFile.Product.Company.Owner)
                                      .SingleOrDefault();

            if (productFile == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if ((productFile.Product.CompanyID != user.Company.ID) &&
                (productFile.Product.TeamMembers.Any(teamMember => teamMember.UserID == user.Id && teamMember.CanEditTheProduct == true)) &&
                ((productFile.Product.Privacy == ProductPrivacy.Private) ||
                 (productFile.Product.Privacy == ProductPrivacy.VisibleToSelectedGroups &&
                  productFile.Product.GroupsVisibleTo.Any(followerGroup => followerGroup.Followers.Any(follower => follower.UserID == user.Id)) == false)) &&
                ((productFile.Privacy == ProductFilePrivacy.Private) ||
                 (productFile.Privacy == ProductFilePrivacy.VisibleToSelectedGroups &&
                  productFile.GroupsVisibleTo.Any(followerGroup => followerGroup.Followers.Any(follower => follower.UserID == user.Id)) == false)))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            ProductFileFeedback replyTo = null;

            if (newFeedbackDTO.ReplyToID != null)
            {
                replyTo = db.Feedback.Where(_feedback => _feedback.ID == newFeedbackDTO.ReplyToID).SingleOrDefault();

                if (replyTo == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
            }

            ProductFileFeedback feedback = Mapper.Map <NewFeedbackDTO, ProductFileFeedback>(newFeedbackDTO);

            if (replyTo != null)
            {
                feedback.ReplyToID      = replyTo.ID;
                feedback.ReplyTo        = replyTo;
                replyTo.UpdatedAt       = DateTime.Now;
                db.Entry(replyTo).State = EntityState.Modified;
            }

            feedback.UserID        = user.Id;
            feedback.User          = user;
            feedback.ProductFileID = productFile.ID;
            feedback.ProductFile   = productFile;
            feedback.PostedAt      = DateTime.Now;
            feedback.UpdatedAt     = DateTime.Now;
            feedback = db.Feedback.Add(feedback);
            await db.SaveChangesAsync();

            string feedbackAuthorUserName = user.UserName;

            if (user.FirstName != null || user.LastName != null)
            {
                feedbackAuthorUserName = (user.FirstName == null ? "" : user.FirstName) + " " + (user.LastName == null ? "" : user.LastName);
            }

            string          feedbackAuthorCompanyName = user.Company == null ? "" : user.Company.DisplayName;
            string          apiKey         = SENDGRID_API_KEY;
            SendGridClient  sendGridClient = new SendGridClient(apiKey, "https://api.sendgrid.com");
            EmailAddress    emailSender    = new EmailAddress("*****@*****.**", "Cervitt");
            String          subject        = "Feedback notification";
            EmailAddress    emailRecipient = new EmailAddress(productFile.Product.Company.Owner.Email);
            Content         content        = new Content("text/html", "Hello world!");
            SendGridMessage mail           = MailHelper.CreateSingleEmail(emailSender, emailRecipient, subject, "", "");

            mail.TemplateId = "976c0e75-4105-4f08-b924-aefb27bf44e8";
            mail.AddSubstitution("<%companyName%>", productFile.Product.Company.DisplayName);
            mail.AddSubstitution("<%productName%>", productFile.Product.Name);
            mail.AddSubstitution("<%feedbackAuthorUserId%>", user.Id.ToString());
            mail.AddSubstitution("<%feedbackAuthorUserName%>", feedbackAuthorUserName);
            mail.AddSubstitution("<%feedbackAuthorUserTitle%>", user.JobTitle);
            mail.AddSubstitution("<%feedbackAuthorCompanyName%>", feedbackAuthorCompanyName);
            mail.AddSubstitution("<%feedbackTitle%>", feedback.Title);
            mail.AddSubstitution("<%feedbackBody%>", feedback.Body);

            dynamic response = sendGridClient.SendEmailAsync(mail);

            return(Ok(Mapper.Map <ProductFileFeedback, FeedbackDTO>(feedback)));
        }
        public String GetRecipientEmail(Recipient recipient)
        {
            String  retEmail       = "";
            Boolean builtFakeEmail = false;

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry     = null;
            String       addressEntryType = "";

            try {
                try {
                    addressEntry = recipient.AddressEntry;
                } catch {
                    log.Warn("Can't resolve this recipient!");
                    addressEntry = null;
                }
                if (addressEntry == null)
                {
                    log.Warn("No AddressEntry exists!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }
                else
                {
                    try {
                        addressEntryType = addressEntry.Type;
                    } catch {
                        log.Warn("Cannot access addressEntry.Type!");
                    }
                    log.Fine("AddressEntry Type: " + addressEntryType);
                    if (addressEntryType == "EX")   //Exchange
                    {
                        log.Fine("Address is from Exchange");
                        retEmail = ADX_GetSMTPAddress(addressEntry.Address);
                    }
                    else if (addressEntry.Type != null && addressEntry.Type.ToUpper() == "NOTES")
                    {
                        log.Fine("From Lotus Notes");
                        //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    }
                    else
                    {
                        log.Fine("Not from Exchange");
                        try {
                            if (string.IsNullOrEmpty(addressEntry.Address))
                            {
                                log.Warn("addressEntry.Address is empty.");
                                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                            }
                            else
                            {
                                retEmail = addressEntry.Address;
                            }
                        } catch (System.Exception ex) {
                            log.Error("Failed accessing addressEntry.Address");
                            log.Error(ex.Message);
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                        }
                    }
                }

                if (string.IsNullOrEmpty(retEmail) || retEmail == "Unknown")
                {
                    log.Error("Failed to get email address through Addin MAPI access!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }

                if (retEmail != null && retEmail.IndexOf("<") > 0)
                {
                    retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                    retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
                }
                log.Fine("Email address: " + retEmail, retEmail);
                if (!EmailAddress.IsValidEmail(retEmail) && !builtFakeEmail)
                {
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    if (!EmailAddress.IsValidEmail(retEmail))
                    {
                        MainForm.Instance.Logboxout("ERROR: Recipient \"" + recipient.Name + "\" with email address \"" + retEmail + "\" is invalid.", notifyBubble: true);
                        MainForm.Instance.Logboxout("This must be manually resolved in order to sync this appointment.");
                        throw new ApplicationException("Invalid recipient email for \"" + recipient.Name + "\"");
                    }
                }
                return(retEmail);
            } finally {
                addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry);
            }
        }
        /// <summary>
        /// Gets the free/busy status appointment information for User2 (as specified in ptfconfig) through testUserName's account.
        /// </summary>
        /// <param name="testUserName">The user who gets the free/busy status information.</param>
        /// <param name="password">The testUserName's password.</param>
        /// <returns>
        /// <para>"0": means "FreeBusy", which indicates brief information about the appointments on the calendar;</para>
        /// <para>"1": means "Detailed", which indicates detailed information about the appointments on the calendar;</para>
        /// <para>"2": means the appointment free/busy information can't be viewed or error occurs, which indicates the user has no permission to get information about the appointments on the calendar;</para>
        /// </returns>
        public string GetUserFreeBusyStatus(string testUserName, string password)
        {
            // Use the specified user for the web service client authentication
            string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);

            this.availability.Credentials = new NetworkCredential(testUserName, password, domain);

            GetUserAvailabilityRequestType availabilityRequest = new GetUserAvailabilityRequestType();

            SerializableTimeZone timezone = new SerializableTimeZone()
            {
                Bias         = 480,
                StandardTime = new SerializableTimeZoneTime()
                {
                    Bias = 0, Time = "02:00:00", DayOrder = 5, Month = 10, DayOfWeek = "Sunday"
                },
                DaylightTime = new SerializableTimeZoneTime()
                {
                    Bias = -60, Time = "02:00:00", DayOrder = 1, Month = 4, DayOfWeek = "Sunday"
                }
            };

            availabilityRequest.TimeZone = timezone;

            // Specifies the mailbox to query for availability information.
            string       user         = Common.GetConfigurationPropertyValue("User2Name", this.Site);
            EmailAddress emailAddress = new EmailAddress()
            {
                Address = string.IsNullOrEmpty(user) ? string.Empty : user + "@" + domain
            };

            MailboxData mailboxData = new MailboxData()
            {
                Email        = emailAddress,
                AttendeeType = MeetingAttendeeType.Organizer,
            };

            availabilityRequest.MailboxDataArray = new MailboxData[] { mailboxData };

            // Identify the time to compare free/busy information.
            FreeBusyViewOptionsType freeBusyViewOptions = new FreeBusyViewOptionsType()
            {
                TimeWindow = new Duration()
                {
                    StartTime = DateTime.Now, EndTime = DateTime.Now.AddHours(3)
                },
                RequestedView          = FreeBusyViewType.Detailed,
                RequestedViewSpecified = true
            };

            availabilityRequest.FreeBusyViewOptions = freeBusyViewOptions;

            GetUserAvailabilityResponseType availabilityInfo = null;

            try
            {
                availabilityInfo = this.availability.GetUserAvailability(availabilityRequest);
            }
            catch (SoapException exception)
            {
                Site.Assert.Fail("Error occurs when getting free/busy status: {0}", exception.Message);
            }

            string freeBusyStatus = "3";

            FreeBusyResponseType[] freeBusyArray = availabilityInfo.FreeBusyResponseArray;
            if (freeBusyArray != null)
            {
                foreach (FreeBusyResponseType freeBusy in freeBusyArray)
                {
                    ResponseClassType responseClass = freeBusy.ResponseMessage.ResponseClass;
                    if (responseClass == ResponseClassType.Success)
                    {
                        // If the response FreeBusyViewType value is FreeBusy or Detailed, the freeBusyStatus is Detailed.
                        // If all the response FreeBusyViewType values are FreeBusy, the freeBusyStatus is FreeBusy;
                        if (freeBusy.FreeBusyView.FreeBusyViewType == FreeBusyViewType.Detailed)
                        {
                            freeBusyStatus = "1";
                        }
                        else if (freeBusy.FreeBusyView.FreeBusyViewType == FreeBusyViewType.FreeBusy)
                        {
                            if (freeBusyStatus != "1")
                            {
                                freeBusyStatus = "0";
                            }
                        }
                    }
                    else if (responseClass == ResponseClassType.Error)
                    {
                        if (freeBusy.ResponseMessage.ResponseCode == ResponseCodeType.ErrorNoFreeBusyAccess)
                        {
                            return("2");
                        }
                        else
                        {
                            Site.Assert.Fail("Error occurs when getting free/busy status. ErrorCode: {0}; ErrorMessage: {1}.", freeBusy.ResponseMessage.ResponseCode, freeBusy.ResponseMessage.MessageText);
                        }
                    }
                }
            }

            return(freeBusyStatus);
        }
Ejemplo n.º 47
0
 public HomeController(EmailAddress _fromAddress, IEmailService _emailService)
 {
     FromAndToEmailAddress = _fromAddress;
     EmailService          = _emailService;
 }
Ejemplo n.º 48
0
 public async Task SignupAsync(EmailAddress email, CultureInfo culture)
 {
     await _apiClient.PostAllAccountsUserAsync(email.Address, culture).Free();
 }
Ejemplo n.º 49
0
 public string PrintCustomerForView()
 {
     return(CustomerNumber + "," + FirstName + "," + LastName + "," + EmailAddress.Print() + "," + AccountBalance + "," + LastAccess.ToShortDateString() + "," + CustAdresse.ToCSVString());
 }
Ejemplo n.º 50
0
 public async Task <UserPublicKey> OtherPublicKeyAsync(EmailAddress email)
 {
     return((await _apiClient.GetAllAccountsOtherUserPublicKeyAsync(email.Address).Free()).ToUserPublicKey());
 }
Ejemplo n.º 51
0
 public void ChangeEmail(string emailAddress)
 {
     EmailAddress.ChangeEmail(emailAddress);
 }
Ejemplo n.º 52
0
 public async Task <UserPublicKey> OtherUserInvitePublicKeyAsync(EmailAddress email, CustomMessageParameters customParameters)
 {
     return((await _apiClient.PostAllAccountsOtherUserInvitePublicKeyAsync(email.Address, customParameters).Free()).ToUserPublicKey());
 }
Ejemplo n.º 53
0
 public void SetNormalizedNames()
 {
     NormalizedUserName     = AdminUserName.ToUpperInvariant();
     NormalizedEmailAddress = EmailAddress.ToUpperInvariant();
 }
Ejemplo n.º 54
0
        public async Task <DialogTurnResult> ConfirmName(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                if (((state.NameList == null) || (state.NameList.Count == 0)) && state.EmailList.Count == 0)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }

                var unionList = new List <PersonModel>();

                if (state.FirstEnterFindContact || state.EmailList.Count > 0)
                {
                    state.FirstEnterFindContact = false;
                    if (state.NameList.Count > 1)
                    {
                        var nameString = await GetReadyToSendNameListStringAsync(sc);

                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(FindContactResponses.BeforeSendingMessage, new StringDictionary()
                        {
                            { "NameList", nameString }
                        }));
                    }
                }

                if (state.EmailList.Count > 0)
                {
                    foreach (var email in state.EmailList)
                    {
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = email,
                            Address = email,
                        };
                        recipient.EmailAddress = emailAddress;

                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }
                    }

                    state.EmailList.Clear();

                    if (state.NameList.Count > 0)
                    {
                        return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                    }
                    else
                    {
                        return(await sc.EndDialogAsync());
                    }
                }

                if (state.ConfirmRecipientIndex < state.NameList.Count)
                {
                    var currentRecipientName = state.NameList[state.ConfirmRecipientIndex];

                    var token            = state.Token;
                    var service          = ServiceManager.InitUserService(token, state.GetUserTimeZone(), state.MailSourceType);
                    var originPersonList = await service.GetPeopleAsync(currentRecipientName);

                    var originContactList = await service.GetContactsAsync(currentRecipientName);

                    originPersonList.AddRange(originContactList);

                    var originUserList = new List <PersonModel>();
                    try
                    {
                        originUserList = await service.GetUserAsync(currentRecipientName);
                    }
                    catch
                    {
                        // do nothing when get user failed. because can not use token to ensure user use a work account.
                    }

                    (var personList, var userList) = DisplayHelper.FormatRecipientList(originPersonList, originUserList);

                    // people you work with has the distinct email address has the highest priority
                    if (personList.Count == 1 && personList.First().Emails != null && personList.First().Emails?.Count() == 1 && !string.IsNullOrEmpty(personList.First().Emails.First()))
                    {
                        state.ConfirmedPerson = personList.First();
                        return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, personList.First()));
                    }

                    personList.AddRange(userList);

                    foreach (var person in personList)
                    {
                        if (unionList.Find(p => p.DisplayName == person.DisplayName) == null)
                        {
                            var personWithSameName = personList.FindAll(p => p.DisplayName == person.DisplayName);
                            if (personWithSameName.Count == 1)
                            {
                                unionList.Add(personWithSameName.FirstOrDefault());
                            }
                            else
                            {
                                var unionPerson = personWithSameName.FirstOrDefault();
                                var emailList   = new List <string>();
                                foreach (var sameNamePerson in personWithSameName)
                                {
                                    foreach (var email in sameNamePerson.Emails)
                                    {
                                        if (!string.IsNullOrEmpty(email))
                                        {
                                            emailList.Add(email);
                                        }
                                    }
                                }

                                unionPerson.Emails = emailList;
                                unionList.Add(unionPerson);
                            }
                        }
                    }
                }
                else
                {
                    return(await sc.EndDialogAsync());
                }

                unionList.RemoveAll(person => !person.Emails.Exists(email => email != null));
                unionList.RemoveAll(person => !person.Emails.Any());

                state.UnconfirmedPerson = unionList;

                if (unionList.Count == 0)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }
                else if (unionList.Count == 1)
                {
                    state.ConfirmedPerson = unionList.First();
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, unionList.First()));
                }
                else
                {
                    var nameString = string.Empty;
                    if (unionList.Count <= ConfigData.GetInstance().MaxDisplaySize)
                    {
                        return(await sc.PromptAsync(Actions.Choice, await GenerateOptionsForName(sc, unionList, sc.Context, true)));
                    }
                    else
                    {
                        return(await sc.PromptAsync(Actions.Choice, await GenerateOptionsForName(sc, unionList, sc.Context, false)));
                    }
                }
            }
            catch (SkillException skillEx)
            {
                await HandleDialogExceptions(sc, skillEx);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Ejemplo n.º 55
0
 public SendgridMail(string apiKey, EmailAddress to, EmailAddress from) : base(to, from)
 {
     ApiKey       = apiKey.Trim();
     TemplateData = new Dictionary <string, string>();
 }
Ejemplo n.º 56
0
        public async Task <DialogTurnResult> AfterConfirmEmail(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                var confirmedPerson = state.ConfirmedPerson;
                var name            = confirmedPerson.DisplayName;
                if (sc.Result is bool)
                {
                    if ((bool)sc.Result)
                    {
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = name,
                            Address = confirmedPerson.Emails.First()
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.FirstRetryInFindContact = true;
                        state.ConfirmRecipientIndex++;
                        if (state.ConfirmRecipientIndex < state.NameList.Count)
                        {
                            return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                        }
                        else
                        {
                            return(await sc.EndDialogAsync());
                        }
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.ConfirmNo)));
                    }
                }

                var luisResult       = state.LuisResult;
                var topIntent        = luisResult?.TopIntent().intent;
                var generlLuisResult = state.GeneralLuisResult;
                var generalTopIntent = generlLuisResult?.TopIntent().intent;

                if (state.NameList != null && state.NameList.Count > 0)
                {
                    if (sc.Result == null)
                    {
                        if (generalTopIntent == General.Intent.ShowNext)
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                        }
                        else if (generalTopIntent == General.Intent.ShowPrevious)
                        {
                            if (state.ShowRecipientIndex > 0)
                            {
                                state.ShowRecipientIndex--;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(FindContactResponses.AlreadyFirstPage));
                            }
                        }
                        else if (IsReadMoreIntent(generalTopIntent, sc.Context.Activity.Text))
                        {
                            if (state.RecipientChoiceList.Count <= ConfigData.GetInstance().MaxReadSize)
                            {
                                state.ShowRecipientIndex++;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                state.ReadRecipientIndex++;
                            }
                        }
                        else
                        {
                            // result is null when just update the recipient name. show recipients page should be reset.
                            state.ShowRecipientIndex = 0;
                            state.ReadRecipientIndex = 0;
                        }

                        return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, confirmedPerson));
                    }

                    var choiceResult = (sc.Result as FoundChoice)?.Value.Trim('*');
                    if (choiceResult != null)
                    {
                        // Find an recipient
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = choiceResult.Split(": ")[0],
                            Address = choiceResult.Split(": ")[1],
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.ConfirmRecipientIndex++;
                        state.FirstRetryInFindContact = true;

                        // Clean up data
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        state.ConfirmedPerson    = new PersonModel();
                        state.RecipientChoiceList.Clear();
                    }
                }

                if (state.ConfirmRecipientIndex < state.NameList.Count)
                {
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                }
                else
                {
                    return(await sc.EndDialogAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Ejemplo n.º 57
0
 public void Can_parse_dirty_address()
 {
     EmailAddress.Parse("adrian 2 @@ gmail.com,").ToString().ShouldBe("*****@*****.**");
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Creates a new instance of the <see cref="PersonaEmailAddress"/> class.
 /// </summary>
 public PersonaEmailAddress()
     : base()
 {
     _emailAddress = new EmailAddress();
 }
Ejemplo n.º 59
0
        public void Send(IEnumerable <string> to, string from, string subject, string message)
        {
            try
            {
                // //// From
                var pairFrom  = from.Split(';');
                var emailFrom = pairFrom[0];
                var nameFrom  = pairFrom[1];
                var client    = new SendGridClient(Program.sendGridKey);
                var _from     = new EmailAddress(emailFrom, nameFrom);
                // //// To
                var _to = new List <EmailAddress>();
                foreach (var pairs in to)
                {
                    var pair  = pairs.Split(';');
                    var email = pair[0];
                    var name  = pair[1];
                    _to.Add(new EmailAddress(email, name));
                }
                var plainTextContent = message;
                var htmlContent      = message;
                var msg      = MailHelper.CreateSingleEmailToMultipleRecipients(_from, _to, subject, plainTextContent, htmlContent);
                var response = client.SendEmailAsync(msg);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            // try
            // {
            //     var mailMsg = new System.Net.Mail.MailMessage();

            //     //// To
            //     foreach(var pairs in to)
            //     {
            //         var pair = pairs.Split(';');
            //         var email = pair[0];
            //         var name = pair[1];
            //         mailMsg.To.Add(new System.Net.Mail.MailAddress(email, name));
            //     }

            //     //// From
            //     var pairFrom = from.Split(';');
            //     var emailFrom = pairFrom[0];
            //     var nameFrom = pairFrom[1];
            //     mailMsg.From = new System.Net.Mail.MailAddress(emailFrom, nameFrom);

            //     mailMsg.Subject = subject;
            //     mailMsg.AlternateViews.Add(System.Net.Mail.AlternateView.CreateAlternateViewFromString(message, null, System.Net.Mime.MediaTypeNames.Text.Plain));
            //     mailMsg.AlternateViews.Add(System.Net.Mail.AlternateView.CreateAlternateViewFromString(message.Replace(System.Environment.NewLine, "<br>"), null, System.Net.Mime.MediaTypeNames.Text.Html));

            //     //// Init SmtpClient and send
            //     var smtpClient = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
            //     var credentials = new System.Net.NetworkCredential("aqi", "Capital!1234");
            //     smtpClient.Credentials = credentials;

            //     smtpClient.Send(mailMsg);
            // }
            // catch(Exception e)
            // {
            //     Console.WriteLine(e);
            // }
        }
Ejemplo n.º 60
0
        public static List <CalendarObject> GetCalendarData(DateTime lookupDate)
        {
            List <CalendarObject> calendarObjects = new List <CalendarObject>();

            //umdemo.dnsalias.com explicit credentials
            ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding();

            ICredentials creds = new NetworkCredential(user, password, "um.test.com");

            exchangeServer.Credentials = creds;
            exchangeServer.Url         = @"http://um.test.com/ews/exchange.asmx";

            GetUserAvailabilityRequestType request = new GetUserAvailabilityRequestType();

            MailboxData[] mailboxes = new MailboxData[1];
            mailboxes[0] = new MailboxData();

            // Identify the user mailbox to review their Free/Busy data
            EmailAddress emailAddress = new EmailAddress();

            emailAddress.Address = "*****@*****.**";

            emailAddress.Name = String.Empty;

            mailboxes[0].Email = emailAddress;

            request.MailboxDataArray = mailboxes;

            //Set TimeZone
            request.TimeZone                        = new SerializableTimeZone();
            request.TimeZone.Bias                   = 480;
            request.TimeZone.StandardTime           = new SerializableTimeZoneTime();
            request.TimeZone.StandardTime.Bias      = 0;
            request.TimeZone.StandardTime.DayOfWeek = DayOfWeekType.Sunday.ToString();
            request.TimeZone.StandardTime.DayOrder  = 1;
            request.TimeZone.StandardTime.Month     = 11;
            request.TimeZone.StandardTime.Time      = "02:00:00";
            request.TimeZone.DaylightTime           = new SerializableTimeZoneTime();
            request.TimeZone.DaylightTime.Bias      = -60;
            request.TimeZone.DaylightTime.DayOfWeek = DayOfWeekType.Sunday.ToString();
            request.TimeZone.DaylightTime.DayOrder  = 2;
            request.TimeZone.DaylightTime.Month     = 3;
            request.TimeZone.DaylightTime.Time      = "02:00:00";


            // Identify the time to compare if the user is Free/Busy
            Duration duration = new Duration();

            duration.StartTime = lookupDate;
            duration.EndTime   = lookupDate.AddDays(1);

            // Identify the options for comparing F/B
            FreeBusyViewOptionsType viewOptions = new FreeBusyViewOptionsType();

            viewOptions.TimeWindow = duration;

            viewOptions.RequestedView          = FreeBusyViewType.Detailed;
            viewOptions.RequestedViewSpecified = true;


            request.FreeBusyViewOptions = viewOptions;

            GetUserAvailabilityResponseType response = exchangeServer.GetUserAvailability(request);

            foreach (FreeBusyResponseType responseType in response.FreeBusyResponseArray)
            {
                if (responseType.FreeBusyView.CalendarEventArray.Length > 0)
                {
                    foreach (CalendarEvent calendar in responseType.FreeBusyView.CalendarEventArray)
                    {
                        CalendarObject calendarObject = new CalendarObject();

                        calendarObject.Location  = calendar.CalendarEventDetails.Location;
                        calendarObject.Subject   = calendar.CalendarEventDetails.Subject;
                        calendarObject.StartDate = calendar.StartTime;
                        calendarObject.EndDate   = calendar.EndTime;
                        calendarObject.IsMeeting = calendar.CalendarEventDetails.IsMeeting;

                        calendarObjects.Add(calendarObject);
                    }
                }
            }

            return(calendarObjects);
        }