Пример #1
0
        internal static IList <RecipientData> CreateFakeRecipientQueryResult(string address)
        {
            Microsoft.Exchange.InfoWorker.Common.Availability.EmailAddress emailAddress = new Microsoft.Exchange.InfoWorker.Common.Availability.EmailAddress(string.Empty, address);
            Dictionary <PropertyDefinition, object> propertyMap = new Dictionary <PropertyDefinition, object>
            {
                {
                    ADRecipientSchema.RecipientType,
                    RecipientType.MailContact
                },
                {
                    ADRecipientSchema.PrimarySmtpAddress,
                    new SmtpAddress(address)
                },
                {
                    ADRecipientSchema.ExternalEmailAddress,
                    new SmtpProxyAddress(address, true)
                }
            };
            RecipientData item = RecipientData.Create(emailAddress, propertyMap);

            return(new List <RecipientData>
            {
                item
            });
        }
Пример #2
0
        public override AvailabilityException CreateExceptionForUnsupportedVersion(RecipientData recipient, int serverVersion)
        {
            ProxyServerWithMinimumRequiredVersionNotFound proxyServerWithMinimumRequiredVersionNotFound = new ProxyServerWithMinimumRequiredVersionNotFound(recipient.EmailAddress, serverVersion, Globals.E15Version);

            proxyServerWithMinimumRequiredVersionNotFound.Data["ThumbnailPhotoKey"] = recipient.ThumbnailPhoto;
            return(proxyServerWithMinimumRequiredVersionNotFound);
        }
Пример #3
0
        public static string GetCustomMailTip(RecipientData recipientData, int traceId, int lcid)
        {
            MailTipsUtility.GetMailTipsTracer.TraceFunction((long)traceId, "Entering GetBestCustomMailTip");
            CultureInfo cultureInfo = null;

            try
            {
                cultureInfo = new CultureInfo(lcid);
            }
            catch (ArgumentException)
            {
                MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip - invalid culture, returning default");
                return(ADRecipient.DefaultMailTipGetter(recipientData.MailTipTranslations) as string);
            }
            object mailTipTranslations = recipientData.MailTipTranslations;

            if (mailTipTranslations == null)
            {
                return(null);
            }
            IList <string> list = (IList <string>)mailTipTranslations;

            if (list.Count == 0)
            {
                MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip - no values, returning null");
                return(null);
            }
            string result;

            if (list.Count != 1)
            {
                for (int i = 0; i < 10; i++)
                {
                    string name = cultureInfo.Name;
                    MailTipsUtility.GetMailTipsTracer.TraceDebug <string>((long)traceId, "Checking for custom MailTip for {0}", name);
                    if (MailTipsUtility.TryGetTranslation(list, name, out result))
                    {
                        MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip with match");
                        return(result);
                    }
                    if (cultureInfo == CultureInfo.InvariantCulture)
                    {
                        MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip with default");
                        return(ADRecipient.DefaultMailTipGetter(recipientData.MailTipTranslations) as string);
                    }
                    cultureInfo = cultureInfo.Parent;
                }
                return(ADRecipient.DefaultMailTipGetter(recipientData.MailTipTranslations) as string);
            }
            string text;

            if (ADRecipient.TryGetMailTipParts(list[0], out text, out result))
            {
                MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip - returning the sole value");
                return(result);
            }
            MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Exiting GetBestCustomMailTip - sole value corrupt, returning null");
            return(null);
        }
Пример #4
0
        /// <summary>
        /// Adds email addresses from another recipient list into this list.
        /// </summary>
        /// <remarks>
        /// Only new email addresses will be added. Email addresses that exists
        /// in this list already will not be affected.
        /// </remarks>
        /// <param name="sourceRecipientListId">The id of the recipient list where email addresses will be fetched from.</param>
        /// <returns>The number of email addresses imported into this list</returns>
        public int AddRecipientItemsFromRecipientList(int sourceRecipientListId)
        {
            RecipientData dataUtil = GetWorker();
            int           count    = dataUtil.RecipientItemInsertFromRecipientList(_id, sourceRecipientListId);

            ClearEmailAddressCount();
            return(count);
        }
Пример #5
0
        public override BaseQuery CreateFromGroup(RecipientData recipientData, BaseQuery[] groupMembers, bool groupCapped)
        {
            TraceWrapper.SearchLibraryTracer.TraceError(this.GetHashCode(), "Attempted to create group query in x-forest case.", new object[0]);
            TrackingError          trackingError = new TrackingError(ErrorCode.UnexpectedErrorPermanent, string.Empty, "Group autodiscover query for Cross-Forest disallowed", string.Empty);
            TrackingFatalException ex            = new TrackingFatalException(trackingError, null, false);

            DiagnosticWatson.SendWatsonWithoutCrash(ex, "CreateFromGroup", TimeSpan.FromDays(1.0));
            throw ex;
        }
Пример #6
0
 public MailTips(RecipientData recipientData) : this(recipientData.EmailAddress)
 {
     this.recipientData = recipientData;
     if (!recipientData.IsEmpty)
     {
         this.configuration = CachedOrganizationConfiguration.GetInstance(recipientData.OrganizationId, CachedOrganizationConfiguration.ConfigurationTypes.All);
         return;
     }
     this.permission = MailTipsPermission.AllAccess;
 }
Пример #7
0
        public static EmailAddresses ListAll(int recipientListId)
        {
            EmailAddresses items = new EmailAddresses();

            RecipientData dataUtil          = GetWorker();
            DataTable     emailAddressTable = dataUtil.RecipientListGetAllItems(recipientListId);

            FillFromDataTable(emailAddressTable, items);
            return(items);
        }
Пример #8
0
        /// <summary>
        /// Deletes the email address items for this recipient list
        /// </summary>
        /// <remarks>
        /// The EmailAddress property will be cleared when calling this method.
        /// </remarks>
        public void DeleteEmailAddressItems()
        {
            RecipientData dataUtil = GetWorker();

            dataUtil.RecipientListRemoveAllItems(_id);

            // Reset collection
            _emailAddresses = null;
            ClearEmailAddressCount();
        }
Пример #9
0
        /// <summary>
        /// Searches the recipientList for emailaddresses that matches
        /// a specified string. Will search all emails with a LIKE clause.
        /// </summary>
        /// <param name="recipientListId">The recipient list id.</param>
        /// <param name="searchFor">The email to search for.</param>
        /// <returns>A collection of recipient. The collection count can be 0</returns>
        public static EmailAddresses Search(int recipientListId, string searchFor)
        {
            //RecipientList items = new RecipientList();
            EmailAddresses items    = new EmailAddresses();
            RecipientData  dataUtil = GetWorker();

            DataTable recipientsTable = dataUtil.RecipientListSearch(recipientListId, searchFor);

            FillFromDataTable(recipientsTable, items);
            return(items);
        }
Пример #10
0
        private static FileHolder[] GetFiles(
            EventType type,
            RecipientData recipient,
            IReadOnlyDictionary <string, FileHolder[]> files)
        {
            if (type == EventType.ApplicationSetState && recipient.Role != RoleType.Client)
            {
                return(null);
            }

            return(files == null ? null : files[recipient.Culture]);
        }
Пример #11
0
        /// <summary>
        /// Lists all recipient lists that specified email adress belongs to
        /// </summary>
        /// <returns>A RecipientLists collection of all recipient lists</returns>
        public static RecipientLists ListAllByEmail(string email)
        {
            RecipientLists recipientLists = new RecipientLists();
            RecipientData  dataUtil       = GetWorker();
            DataTable      recipTable     = dataUtil.RecipientListGetAllByEmail(email);

            foreach (DataRow row in recipTable.Rows)
            {
                RecipientList recipientList = new RecipientList(row);
                recipientLists.Add(recipientList);
            }
            return(recipientLists);
        }
Пример #12
0
        public static EmailAddress Load(int recipientListId, string emailAddress)
        {
            RecipientData dataUtil = GetWorker();

            // Get it, making sure we pass a washed address
            DataRow emailRow = dataUtil.RecipientListGetItem(recipientListId, NewsLetterUtil.CleanEmailAddress(emailAddress));

            if (emailRow != null)
            {
                return(new EmailAddress(emailRow));
            }
            else
            {
                return(null);
            }
        }
Пример #13
0
        public static RecipientLists ListOneType(string listType)
        {
            RecipientLists recipientLists = new RecipientLists();
            RecipientData  dataUtil       = GetWorker();
            DataTable      recipTable     = dataUtil.RecipientListGetAll();

            foreach (DataRow row in recipTable.Rows)
            {
                RecipientList recipientList = new RecipientList(row);
                if (recipientList.ListType.ToString().Equals(listType))
                {
                    recipientLists.Add(recipientList);
                }
            }
            return(recipientLists);
        }
Пример #14
0
        /// <summary>
        /// Loads the specified list.
        /// </summary>
        /// <param name="recipientListId">The id of the recipient list.</param>
        /// <returns>The job if found, null if no job with the id could be found</returns>
        public static RecipientList Load(int recipientListId)
        {
            RecipientData dataUtil   = GetWorker();
            DataTable     recipTable = dataUtil.RecipientListGetById(recipientListId);

            // See if we found one
            if (recipTable.Rows.Count != 1)
            {
                return(null);
            }

            // Found one
            RecipientList recipList = new RecipientList(recipTable.Rows[0]);

            return(recipList);
        }
Пример #15
0
        public void Test_SetStateForNotClient()
        {
            const EventType eventType = EventType.ApplicationSetState;
            var             applicationDetailsData = _container.Create <ApplicationData>();
            var             eventDataForEntity     = _container.Create <EventDataForEntity>();
            var             eventData     = _container.Create <EventData>();
            var             recipientData = new RecipientData(_container.Create <string>(), _container.Create <string>(), RoleType.Broker);
            var             localization  = _container.Create <EmailTemplateLocalizationData>();
            var             templateId    = _container.Create <long>();

            // ReSharper disable ImplicitlyCapturedClosure
            _container.Serializer.Setup(x => x.Deserialize <EventDataForEntity>(eventData.Data)).Returns(eventDataForEntity);
            _container.ApplicationRepository.Setup(x => x.Get(eventDataForEntity.EntityId)).Returns(applicationDetailsData);
            _container.TemplateRepositoryHelper.Setup(x => x.GetTemplateId(eventType)).Returns(templateId);
            _container.TemplateRepositoryHelper.Setup(x => x.GetLocalization(templateId, recipientData.Culture))
            .Returns(localization);
            _container.CommonFilesFacade.Setup(x => x.GetFiles(eventType, eventDataForEntity, It.IsAny <string[]>()))
            .Returns(_container.Create <IReadOnlyDictionary <string, FileHolder[]> >());
            _container.RecipientsFacade.Setup(x => x.GetRecipients(eventType, eventDataForEntity))
            .Returns(new[] { recipientData });
            _container.TextBulder.Setup(
                x => x.GetText(localization.Subject, recipientData.Culture, eventType, applicationDetailsData, eventDataForEntity.Data))
            .Returns(localization.Subject);
            _container.TextBulder.Setup(
                x => x.GetText(localization.Body, recipientData.Culture, eventType, applicationDetailsData, eventDataForEntity.Data))
            .Returns(localization.Body);

            var messages = _builder.Get(eventType, eventData);

            messages[0].Files.Should().BeNull();
            messages[0].IsBodyHtml.ShouldBeEquivalentTo(localization.IsBodyHtml);
            messages[0].Body.ShouldBeEquivalentTo(localization.Body);
            messages[0].Subject.ShouldBeEquivalentTo(localization.Subject);
            messages[0].To[0].ShouldBeEquivalentTo(recipientData.Email);

            _container.ApplicationRepository.Verify(x => x.Get(eventDataForEntity.EntityId));
            _container.TemplateRepositoryHelper.Verify(x => x.GetLocalization(templateId, recipientData.Culture));
            _container.TemplateRepositoryHelper.Verify(x => x.GetTemplateId(eventType));
            _container.CommonFilesFacade.Verify(x => x.GetFiles(eventType, eventDataForEntity, It.IsAny <string[]>()));
            _container.RecipientsFacade.Verify(x => x.GetRecipients(eventType, eventDataForEntity));
            _container.TextBulder.Verify(
                x => x.GetText(localization.Subject, recipientData.Culture, eventType, applicationDetailsData, eventDataForEntity.Data));
            _container.TextBulder.Verify(
                x => x.GetText(localization.Body, recipientData.Culture, eventType, applicationDetailsData, eventDataForEntity.Data));
            // ReSharper restore ImplicitlyCapturedClosure
        }
Пример #16
0
        /// <summary>
        /// Removes emailaddresses from the recipient list.
        /// Validates the input email address to prevent sql statements in the input.
        /// </summary>
        /// <param name="emailAddressArray">Array of emailadrresses</param>
        /// <returns></returns>
        private int RemoveEmailAddresses(string[] emailAddressArray)
        {
            int numberOfDeletedItems = 0;

            RecipientData recipientUtil = GetWorker();

            foreach (string emailAddress in emailAddressArray)
            {
                string emailAddressCleaned = NewsLetterUtil.CleanEmailAddress(emailAddress);

                if (EmailSyntaxValidator.Validate(emailAddressCleaned))
                {
                    recipientUtil.RecipientListRemoveItem(_id, emailAddressCleaned);
                    numberOfDeletedItems++;
                }
            }
            ClearEmailAddressCount();
            return(numberOfDeletedItems);
        }
Пример #17
0
        /// <summary>
        /// Saves the job
        /// </summary>
        public virtual void Save()
        {
            // verify paramterers before sending them to the database
            if (string.IsNullOrEmpty(Name))
            {
                throw new ArgumentException("Name cannot be null or empty");
            }

            if (Name.Length > 255)
            {
                throw new ArgumentException("Name cannot be more then 255 characters");
            }

            if (string.IsNullOrEmpty(Description) == false)
            {
                if (Description.Length > 2000)
                {
                    throw new ArgumentException("Description cannot be more then 2000 characters");
                }
            }

            RecipientData dataUtil = GetWorker();

            if (Id == 0)
            {
                // New list
                // Verify that we do not have a list with same name
                RecipientList existing = Load(_name);
                if (existing != null)
                {
                    throw new ArgumentException("A recipient list with the same name already exists.");
                }

                int newId = dataUtil.RecipientListCreate(_type, _name, _description);
                _id = newId;
            }
            else
            {
                // Edit existing
                dataUtil.RecipientListEdit(_id, _type, _name, _description);
            }
        }
Пример #18
0
 public override BaseQuery CreateFromUnknown(RecipientData recipientData, LocalizedException exception)
 {
     return(GetMessageTrackingBaseQuery.CreateFromUnknown(recipientData, exception));
 }
 public override BaseQuery CreateFromIndividual(RecipientData recipientData, LocalizedException exception)
 {
     return(FindMessageTrackingBaseQuery.CreateFromIndividual(recipientData, exception));
 }
 public override BaseQuery CreateFromIndividual(RecipientData recipientData)
 {
     return(FindMessageTrackingBaseQuery.CreateFromIndividual(recipientData));
 }
Пример #21
0
        protected override byte[] ExecuteInternal()
        {
            UserPhotoApplication userPhotoApplication = new UserPhotoApplication(this.photoRequest, this.photosConfiguration, this.photoRequest.Trace, this.upstreamTracer);

            byte[] result;
            using (RequestDispatcher requestDispatcher = new RequestDispatcher(base.RequestLogger))
            {
                IList <RecipientData> list = this.LookupTargetUserInDirectory();
                if (list.Count == 0)
                {
                    this.tracer.TraceDebug((long)this.GetHashCode(), "Target user not found in directory.");
                    this.StatusCode = HttpStatusCode.NotFound;
                    this.Expires    = this.ComputeExpiresHeader(string.Empty, HttpStatusCode.NotFound);
                    result          = null;
                }
                else
                {
                    RecipientData recipientData = list[0];
                    this.tracer.TraceDebug <SmtpAddress>((long)this.GetHashCode(), "Target user found with PRIMARY SMTP address: '{0}'", recipientData.PrimarySmtpAddress);
                    if (string.IsNullOrEmpty(this.photoRequest.TargetPrimarySmtpAddress) && recipientData.PrimarySmtpAddress.IsValidAddress && recipientData.PrimarySmtpAddress != SmtpAddress.Empty)
                    {
                        this.photoRequest.TargetPrimarySmtpAddress = recipientData.PrimarySmtpAddress.ToString();
                    }
                    QueryGenerator queryGenerator = new QueryGenerator(userPhotoApplication, base.ClientContext, base.RequestLogger, requestDispatcher, this.queryPrepareDeadline, this.requestProcessingDeadline, list);
                    try
                    {
                        UserPhotoQuery userPhotoQuery = (UserPhotoQuery)queryGenerator.GetQueries()[0];
                        requestDispatcher.Execute(this.requestProcessingDeadline, base.HttpResponse);
                        this.individualMailboxesProcessed = queryGenerator.UniqueQueriesCount;
                        if (userPhotoQuery.Result == null)
                        {
                            this.tracer.TraceError <ClientContext, string>((long)this.GetHashCode(), "Query result is NULL.  Client context: {0}; target: {1}", base.ClientContext, this.photoRequest.TargetSmtpAddress);
                            result = null;
                        }
                        else
                        {
                            byte[] array = userPhotoQuery.Result.UserPhotoBytes;
                            this.ETag        = userPhotoQuery.Result.CacheId;
                            this.StatusCode  = userPhotoQuery.Result.StatusCode;
                            this.Expires     = this.ComputeExpiresHeader(userPhotoQuery.Result.Expires, userPhotoQuery.Result.StatusCode);
                            this.ContentType = userPhotoQuery.Result.ContentType;
                            if (userPhotoQuery.Result.ExceptionInfo != null)
                            {
                                this.tracer.TraceError <LocalizedException>((long)this.GetHashCode(), "Query result has an exception: {0}", userPhotoQuery.Result.ExceptionInfo);
                                base.RequestLogger.AppendToLog <string>("EXP", userPhotoQuery.Result.ExceptionInfo.ToString());
                            }
                            array = this.FallbackToThumbnailIfNecessary(userPhotoQuery);
                            userPhotoApplication.LogThreadsUsage(base.RequestLogger);
                            result = array;
                        }
                    }
                    catch (Exception arg)
                    {
                        this.tracer.TraceError <Exception>((long)this.GetHashCode(), "Exception at query dispatch: {0}", arg);
                        throw;
                    }
                    finally
                    {
                        requestDispatcher.LogStatistics(base.RequestLogger);
                    }
                }
            }
            return(result);
        }
Пример #22
0
 private MailTipsQuery(RecipientData recipientData, MailTipsQueryResult result) : base(recipientData, result)
 {
 }
Пример #23
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            // Get the From value
            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            // Get the recipients
            var    recipients = new List <RecipientData>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            recipients.Add(new RecipientData(toAttributeValue, mergeFields));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var recipient = new RecipientData(smsNumber, mergeFields);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RecipientData(smsNumber, recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            // Get the message
            string message     = GetAttributeValue(action, "Message");
            Guid?  messageGuid = message.AsGuidOrNull();

            if (messageGuid.HasValue)
            {
                var attribute = AttributeCache.Read(messageGuid.Value, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid.Value);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ||
                            attribute.FieldType.Class == "Rock.Field.Types.MemoFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            // Add the attachment (if one was specified)
            var binaryFile = new BinaryFileService(rockContext).Get(GetAttributeValue(action, "Attachment", true).AsGuid());

            // Send the message
            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.SetRecipients(recipients);
                smsMessage.FromNumber = DefinedValueCache.Read(fromId.Value);
                smsMessage.Message    = message;
                if (binaryFile != null)
                {
                    smsMessage.Attachments.Add(binaryFile);
                }

                smsMessage.Send();
            }

            return(true);
        }
Пример #24
0
 private UserPhotoQuery(RecipientData recipientData, UserPhotoQueryResult result) : base(recipientData, result)
 {
 }
Пример #25
0
 public static UserPhotoQuery CreateFromIndividual(RecipientData data, LocalizedException exception, ITracer upstreamTracer)
 {
     return(new UserPhotoQuery(data, new UserPhotoQueryResult(exception, upstreamTracer)));
 }
Пример #26
0
 public static UserPhotoQuery CreateFromIndividual(RecipientData data, ITracer upstreamTracer)
 {
     return(new UserPhotoQuery(data, null));
 }
Пример #27
0
 private GetMessageTrackingBaseQuery(RecipientData recipientData, GetMessageTrackingBaseQueryResult result) : base(recipientData, result)
 {
 }
Пример #28
0
 public static GetMessageTrackingBaseQuery CreateFromIndividual(RecipientData recipientData, LocalizedException exception)
 {
     return(new GetMessageTrackingBaseQuery(recipientData, new GetMessageTrackingBaseQueryResult(exception)));
 }
Пример #29
0
 public static GetMessageTrackingBaseQuery CreateFromIndividual(RecipientData recipientData)
 {
     return(new GetMessageTrackingBaseQuery(recipientData, null));
 }
Пример #30
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            var recipients  = new List <RecipientData>();

            string toValue = GetAttributeValue(action, "To");
            Guid   guid    = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var           personAlias = new PersonAliasService(rockContext).Get(personAliasGuid);
                                List <string> devices     = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(a => a.PersonAliasId.HasValue && a.PersonAliasId == personAlias.Id && a.NotificationsEnabled)
                                                            .Select(a => a.DeviceRegistrationId)
                                                            .ToList();

                                string deviceIds = String.Join(",", devices);

                                if (devices.Count == 0)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person does not have devices that support notifications", true);
                                }
                                else
                                {
                                    var recipient = new RecipientData(deviceIds, mergeFields);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    List <string> devices = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(p => p.PersonAliasId.HasValue && p.PersonAliasId == person.PrimaryAliasId && p.NotificationsEnabled)
                                                            .Select(p => p.DeviceRegistrationId)
                                                            .ToList();

                                    string deviceIds = String.Join(",", devices);

                                    if (deviceIds.AsBoolean())
                                    {
                                        var recipient = new RecipientData(deviceIds, mergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            string message     = GetAttributeValue(action, "Message");
            Guid   messageGuid = message.AsGuid();

            if (!messageGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(messageGuid, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            string title     = GetAttributeValue(action, "Title");
            Guid   titleGuid = title.AsGuid();

            if (!titleGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(titleGuid, rockContext);
                if (attribute != null)
                {
                    string titleAttributeValue = action.GetWorklowAttributeValue(titleGuid);
                    if (!string.IsNullOrWhiteSpace(titleAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            title = titleAttributeValue;
                        }
                    }
                }
            }

            string sound     = GetAttributeValue(action, "Sound");
            Guid   soundGuid = sound.AsGuid();

            if (!soundGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(soundGuid, rockContext);
                if (attribute != null)
                {
                    string soundAttributeValue = action.GetWorklowAttributeValue(soundGuid);
                    if (!string.IsNullOrWhiteSpace(soundAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.BooleanFieldType")
                        {
                            sound = soundAttributeValue;
                        }
                    }
                }
            }
            sound = sound.AsBoolean() ? "default" : "";

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var pushMessage = new RockPushMessage();
                pushMessage.SetRecipients(recipients);
                pushMessage.Title   = title;
                pushMessage.Message = message;
                pushMessage.Sound   = sound;
                pushMessage.Send();
            }

            return(true);
        }