Пример #1
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap        = context.JobDetail.JobDataMap;
            int        expirationDays = dataMap.GetInt("ExpirationPeriod");
            int        delayMinutes   = dataMap.GetInt("DelayPeriod");

            var rockContext = new RockContext();
            var qry         = new CommunicationService(rockContext)
                              .GetQueued(expirationDays, delayMinutes, false, false)
                              .OrderBy(c => c.Id);

            var exceptionMsgs      = new List <string>();
            int communicationsSent = 0;

            foreach (var comm in qry.AsNoTracking().ToList())
            {
                try
                {
                    Rock.Model.Communication.Send(comm);
                    communicationsSent++;
                }

                catch (Exception ex)
                {
                    exceptionMsgs.Add(string.Format("Exception occurred sending communication ID:{0}:{1}    {2}", comm.Id, Environment.NewLine, ex.Messages().AsDelimited(Environment.NewLine + "   ")));
                    ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                }
            }

            if (communicationsSent > 0)
            {
                context.Result = string.Format("Sent {0} {1}", communicationsSent, "communication".PluralizeIf(communicationsSent > 1));
            }
            else
            {
                context.Result = "No communications to send";
            }

            if (exceptionMsgs.Any())
            {
                throw new Exception("One or more exceptions occurred sending communications..." + Environment.NewLine + exceptionMsgs.AsDelimited(Environment.NewLine));
            }

            // check for communications that have not been sent but are past the expire date. Mark them as failed and set a warning.
            var beginWindow          = RockDateTime.Now.AddDays(0 - expirationDays);
            var qryExpiredRecipients = new CommunicationRecipientService(rockContext).Queryable()
                                       .Where(cr =>
                                              cr.Communication.Status == CommunicationStatus.Approved &&
                                              cr.Status == CommunicationRecipientStatus.Pending &&
                                              (
                                                  (!cr.Communication.FutureSendDateTime.HasValue && cr.Communication.CreatedDateTime.HasValue && cr.Communication.CreatedDateTime < beginWindow) ||
                                                  (cr.Communication.FutureSendDateTime.HasValue && cr.Communication.FutureSendDateTime < beginWindow)
                                              ));

            var count = qryExpiredRecipients.Count();

            rockContext.BulkUpdate(qryExpiredRecipients, c => new CommunicationRecipient {
                Status = CommunicationRecipientStatus.Failed, StatusNote = "Communication was not sent before the expire window (possibly due to delayed approval)."
            });
        }
Пример #2
0
        private void ChangeCollection()
        {
            this.Clear();
            var collection = GameState.Collections[GameState.CurrentCollectionIndex];

            collectionText.GetComponent <Text>().text = collection;

            GameState.CurrentCollectionLevels = LevelFileLoader.GetLevels(collection).ToArray();

            var index = 0;

            foreach (var level in GameState.CurrentCollectionLevels)
            {
                var buttonGameObject = (GameObject)Instantiate(levelButtonPrefab);
                buttonGameObject.transform.SetParent(layoutContent.transform, false);
                buttonGameObject.transform.GetChild(0).GetComponent <Text>().text = level.Item1;
                instances.Add(buttonGameObject);
                var button = buttonGameObject.GetComponent <UnityEngine.UI.Button>();

                // add lsitener
                button.onClick.AddListener(() =>
                {
                    GameState.CurrentLevelIndex = index;
                    CommunicationService.ChangeLevel(level);
                });
            }

            // switch buttons
            previousButton.SetActive(GameState.CurrentCollectionIndex > 0);
            nextButton.SetActive(GameState.CurrentCollectionIndex < collection.Length - 1);
            index++;
        }
Пример #3
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap    dataMap         = context.JobDetail.JobDataMap;
            int           alertPeriod     = dataMap.GetInt("AlertPeriod");
            Guid?         systemEmailGuid = dataMap.GetString("AlertEmail").AsGuidOrNull();
            List <string> recipientEmails = dataMap.GetString("AlertRecipients").SplitDelimitedValues().ToList();

            if (systemEmailGuid.HasValue && recipientEmails.Any())
            {
                var rockContext = new RockContext();

                int expirationDays = GetJobAttributeValue("ExpirationPeriod", 3, rockContext);
                var cutoffTime     = RockDateTime.Now.AddMinutes(0 - alertPeriod);

                var communications = new CommunicationService(rockContext)
                                     .GetQueued(expirationDays, alertPeriod, false, false)
                                     .Where(c => !c.ReviewedDateTime.HasValue || c.ReviewedDateTime.Value.CompareTo(cutoffTime) < 0) // Make sure communication wasn't just recently approved
                                     .OrderBy(c => c.Id)
                                     .ToList();

                if (communications.Any())
                {
                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Communications", communications);

                    var emailMessage = new RockEmailMessage(systemEmailGuid.Value);
                    foreach (var email in recipientEmails)
                    {
                        emailMessage.AddRecipient(new RecipientData(email, mergeFields));
                    }
                    emailMessage.Send();
                }
            }
        }
        private Dictionary <string, string> CreateCommunication(List <PersonAlias> personAliases, RockContext rockContext = null)
        {
            if (rockContext == null)
            {
                rockContext = new RockContext();
            }
            var service       = new CommunicationService(rockContext);
            var communication = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Transient;

            communication.SenderPersonAliasId = CurrentPersonAliasId;

            service.Add(communication);


            // Get the primary aliases
            foreach (var personAlias in personAliases)
            {
                var recipient = new CommunicationRecipient();
                recipient.PersonAliasId = personAlias.Id;
                communication.Recipients.Add(recipient);
            }

            rockContext.SaveChanges();

            var queryParameters = new Dictionary <string, string>();

            queryParameters.Add("CommunicationId", communication.Id.ToString());

            return(queryParameters);
        }
Пример #5
0
        public void GetTemplate()
        {
            var template = CommunicationService.GetTemplate(1459, _token);

            Assert.IsNotNull(template);
            Assert.AreEqual("Event Reminder", template.Subject);
        }
Пример #6
0
        /// <summary>
        /// Handles the Delete event of the gCommunication control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gCommunication_Delete(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            // First remove it from Subsplash
            gCommunication_Remove(sender, e);

            var rockContext          = new RockContext();
            var communicationService = new CommunicationService(rockContext);
            var communication        = communicationService.Get(e.RowKeyId);

            if (communication != null)
            {
                string errorMessage;
                if (!communicationService.CanDelete(communication, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                communicationService.Delete(communication);

                rockContext.SaveChanges();
            }

            BindGrid();
        }
Пример #7
0
        public void CommunicationDateKeyJoinsCorrectly()
        {
            var expectedRecordCount = 15;
            var year = 2015;

            using (var rockContext = new RockContext())
            {
                var communicationService = new CommunicationService(rockContext);

                var minDateValue = TestDataHelper.GetAnalyticsSourceMinDateForYear(rockContext, year);
                var maxDateValue = TestDataHelper.GetAnalyticsSourceMaxDateForYear(rockContext, year);

                for (var i = 0; i < 15; i++)
                {
                    var communication = BuildCommunication(rockContext,
                                                           TestDataHelper.GetRandomDateInRange(minDateValue, maxDateValue));

                    communicationService.Add(communication);
                }

                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var communicationService = new CommunicationService(rockContext);
                var communications       = communicationService.
                                           Queryable().
                                           Where(i => i.ForeignKey == communicationForeignKey).
                                           Where(i => i.SendSourceDate.CalendarYear == year);

                Assert.AreEqual(expectedRecordCount, communications.Count());
                Assert.IsNotNull(communications.First().SendSourceDate);
            }
        }
Пример #8
0
 public PeerSyncHandler(BlockService blockService, PeerService peerService,
                        CommunicationService communicationService)
 {
     _blockService         = blockService;
     _peerService          = peerService;
     _communicationService = communicationService;
 }
        private void ShouldAddCommunicationWithSpecifiedDBStatusCode(DBStatusCode dBStatusCode, Common.Constants.ResultType expectedResultType)
        {
            // Sample communication to test
            Communication comm = new Communication()
            {
                Text              = "Test communication",
                Subject           = "Testing communication",
                EffectiveDateTime = new DateTime(2020, 04, 04),
                ExpiryDateTime    = new DateTime(2020, 05, 13)
            };

            // Set up delegate
            DBResult <Communication> insertResult = new DBResult <Communication>
            {
                Payload = comm,
                Status  = dBStatusCode
            };

            Mock <ICommunicationDelegate> communicationDelegateMock = new Mock <ICommunicationDelegate>();

            communicationDelegateMock.Setup(s => s.Add(It.Is <Communication>(x => x.Text == comm.Text), true)).Returns(insertResult);

            // Set up service
            ICommunicationService service = new CommunicationService(
                new Mock <ILogger <CommunicationService> >().Object,
                communicationDelegateMock.Object
                );

            RequestResult <Communication> actualResult = service.Add(comm);

            // Check result
            Assert.Equal(expectedResultType, actualResult.ResultStatus);
            Assert.True(actualResult.ResourcePayload.IsDeepEqual(comm));
        }
Пример #10
0
        public MainViewModel()
        {
            _serializationService = new CobsSerializationService();
            _serializationService.RegisterType <MessageHandShakeRequest>(0);
            _serializationService.RegisterType <MessageHandShakeResponse>(1);
            _serializationService.RegisterType <MessageAddSession>(2);
            _serializationService.RegisterType <MessageRemoveSession>(3);
            _serializationService.RegisterType <MessageUpdateVolumeSession>(4);
            _serializationService.RegisterType <MessageSettings>(5);

            _settingsViewModel = new SettingsViewModel();
            _settingsViewModel.PropertyChanged += OnSettingsChanged;

            // TODO: pass in SystemSounds
            _audioSessionService = new AudioSessionService(_settingsViewModel.SystemSounds);
            _audioSessionService.SessionCreated       += OnAudioSessionCreated;
            _audioSessionService.SessionRemoved       += OnAudioSessionRemoved;
            _audioSessionService.SessionVolumeChanged += OnAudioSessionVolumeChanged;

            _discoveryService = new DiscoveryService(_serializationService);
            _discoveryService.DeviceDiscovered += OnDeviceDiscovered;

            _communicationService = new CommunicationService(_serializationService);
            _communicationService.MessageReceived += OnMessageReceived;
            _communicationService.Error           += OnCommunicationError;
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            StorageManager manager = new StorageManager();

            try
            {
                Publication pub = manager.getEntityByID <Publication>(Int32.Parse(Request["PubId"]));
                if (pub == null)
                {
                    Response.StatusCode = 400;
                    Response.Write("HTTP 400 Bad Request");
                }
                else
                {
                    Uri    uri   = new Uri(pub.URIUpload);
                    string token = uri.Query.Substring(7);
                    if (Request["token"] != null && token.Equals(Request["token"]))
                    {
                        CommunicationService service = CommunicationService.Instance;
                        Response.ContentType = "text/xml";
                        service.GenerateFeed(pub, Response.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                if (Response.StatusCode != 400)
                {
                    Response.StatusCode = 400;
                    Response.Write("HTTP 400 Bad Request");
                }
            }
            Response.End();
        }
Пример #12
0
        protected void gCommunication_Copy(object sender, RowEventArgs e)
        {
            int?newCommunicationId = null;

            using (var rockContext = new RockContext())
            {
                var communicationService = new CommunicationService(rockContext);

                var newCommunication = communicationService.Copy(e.RowKeyId, CurrentPersonAliasId);
                if (newCommunication != null)
                {
                    communicationService.Add(newCommunication);
                    rockContext.SaveChanges();

                    newCommunicationId = newCommunication.Id;
                }
            }

            if (newCommunicationId != null)
            {
                var pageParams = new Dictionary <string, string>
                {
                    { PageParameterKey.CommunicationId, newCommunicationId.ToString() }
                };
                NavigateToLinkedPage(AttributeKey.DetailPage, pageParams);
            }
        }
Пример #13
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>
        /// <param name="communication">The communication.</param>
        public override void Send(Model.Communication communication)
        {
            var rockContext          = new RockContext();
            var communicationService = new CommunicationService(rockContext);

            communication = communicationService.Get(communication.Id);

            if (communication != null &&
                communication.Status == Model.CommunicationStatus.Approved &&
                communication.Recipients.Where(r => r.Status == Model.CommunicationRecipientStatus.Pending).Any() &&
                (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
            {
                // Update any recipients that should not get sent the communication
                var recipientService = new CommunicationRecipientService(rockContext);
                foreach (var recipient in recipientService.Queryable("PersonAlias.Person")
                         .Where(r =>
                                r.CommunicationId == communication.Id &&
                                r.Status == CommunicationRecipientStatus.Pending)
                         .ToList())
                {
                    var person = recipient.PersonAlias.Person;
                    if (person.IsDeceased ?? false)
                    {
                        recipient.Status     = CommunicationRecipientStatus.Failed;
                        recipient.StatusNote = "Person is deceased!";
                    }
                }

                rockContext.SaveChanges();
            }

            base.Send(communication);
        }
Пример #14
0
        public void Execute(IServiceProvider serviceProvider)
        {
            var traceService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            traceService.Trace("Получили ITracingService");

            var pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var target        = (Entity)pluginContext.InputParameters["Target"];

            var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service        = serviceFactory.CreateOrganizationService(Guid.Empty);// null

            try
            {
                Entity postImage = null;
                if (pluginContext.PreEntityImages.Contains("nav_precommunicationupdateimage") && pluginContext.PreEntityImages["nav_precommunicationupdateimage"] is Entity)
                {
                    traceService.Trace("Получили PreEntityImages");
                    postImage = (Entity)pluginContext.PreEntityImages["nav_precommunicationupdateimage"];
                }
                CommunicationService commService = new CommunicationService(service, traceService);
                commService.CheckUniqMainTypeContact(target, postImage);
            }
            catch (Exception exc)
            {
                traceService.Trace("Ошибка " + exc.ToString());

                throw new InvalidPluginExecutionException(exc.Message);
            }
        }
Пример #15
0
        private Tuple <RequestResult <Communication>, Communication> ExecuteGetActiveCommunication(Database.Constants.DBStatusCode dbResultStatus = Database.Constants.DBStatusCode.Read)
        {
            Communication communication = new Communication
            {
                Id = Guid.NewGuid(),
                EffectiveDateTime = DateTime.UtcNow.AddDays(-1),
                ExpiryDateTime    = DateTime.UtcNow.AddDays(2)
            };

            DBResult <Communication> dbResult = new DBResult <Communication>
            {
                Payload = communication,
                Status  = dbResultStatus
            };

            ServiceCollection services = new ServiceCollection();

            services.AddMemoryCache();
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            IMemoryCache memoryCache = serviceProvider.GetService <IMemoryCache>();

            Mock <ICommunicationDelegate> communicationDelegateMock = new Mock <ICommunicationDelegate>();

            communicationDelegateMock.Setup(s => s.GetActiveBanner()).Returns(dbResult);

            ICommunicationService service = new CommunicationService(
                new Mock <ILogger <CommunicationService> >().Object,
                communicationDelegateMock.Object,
                memoryCache
                );
            RequestResult <Communication> actualResult = service.GetActiveBanner();

            return(new Tuple <RequestResult <Communication>, Communication>(actualResult, communication));
        }
Пример #16
0
 public void RaiseCallbackEvent(string eventArgument)
 {
     try
     {
         result = "";
         if (eventArgument != null && eventArgument != "")
         {
             CommunicationService        cs  = CommunicationService.Instance;
             Dictionary <string, string> dic = new Dictionary <string, string>();
             string[] service = eventArgument.Split('$');
             string[] temp    = service[1].Split('&');
             foreach (string couple in temp)
             {
                 if (couple != "")
                 {
                     dic.Add(couple.Split('|')[0], couple.Split('|')[1]);
                 }
             }
             string uri = cs.BuildUri(service[0], dic);
             Page.Session["uriFromComm"] = uri;
         }
         result = "ok";
     }
     catch (Exception e)
     {
         result = "Error on uri creation, contact an admin";
     }
 }
Пример #17
0
        /// <summary>
        /// Handles the Click event of the btnCopy control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnCopy_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CommunicationId.HasValue)
            {
                var rockContext   = new RockContext();
                var service       = new CommunicationService(rockContext);
                var communication = service.Get(CommunicationId.Value);
                if (communication != null)
                {
                    var newCommunication = communication.Clone(false);
                    newCommunication.CreatedByPersonAlias    = null;
                    newCommunication.CreatedByPersonAliasId  = null;
                    newCommunication.CreatedDateTime         = RockDateTime.Now;
                    newCommunication.ModifiedByPersonAlias   = null;
                    newCommunication.ModifiedByPersonAliasId = null;
                    newCommunication.ModifiedDateTime        = RockDateTime.Now;
                    newCommunication.Id   = 0;
                    newCommunication.Guid = Guid.Empty;
                    newCommunication.SenderPersonAliasId = CurrentPersonAliasId;
                    newCommunication.Status = CommunicationStatus.Draft;
                    newCommunication.ReviewerPersonAliasId = null;
                    newCommunication.ReviewedDateTime      = null;
                    newCommunication.ReviewerNote          = string.Empty;

                    communication.Recipients.ToList().ForEach(r =>
                                                              newCommunication.Recipients.Add(new CommunicationRecipient()
                    {
                        PersonAliasId             = r.PersonAliasId,
                        Status                    = CommunicationRecipientStatus.Pending,
                        StatusNote                = string.Empty,
                        AdditionalMergeValuesJson = r.AdditionalMergeValuesJson
                    }));


                    foreach (var attachment in communication.Attachments.ToList())
                    {
                        var newAttachment = new CommunicationAttachment();
                        newAttachment.BinaryFileId      = attachment.BinaryFileId;
                        newAttachment.CommunicationType = attachment.CommunicationType;
                        newCommunication.Attachments.Add(newAttachment);
                    }

                    service.Add(newCommunication);
                    rockContext.SaveChanges();

                    // Redirect to new communication
                    if (CurrentPageReference.Parameters.ContainsKey("CommunicationId"))
                    {
                        CurrentPageReference.Parameters["CommunicationId"] = newCommunication.Id.ToString();
                    }
                    else
                    {
                        CurrentPageReference.Parameters.Add("CommunicationId", newCommunication.Id.ToString());
                    }

                    Response.Redirect(CurrentPageReference.BuildUrl());
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                int?senderPersonAliasId = null;
                if (FromAddress.IsNotNullOrWhiteSpace())
                {
                    var sender = new PersonService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(p => p.Email == FromAddress)
                                 .FirstOrDefault();
                    senderPersonAliasId = sender != null ? sender.PrimaryAliasId : (int?)null;
                }

                var communication = new CommunicationService(rockContext).CreateEmailCommunication(
                    RecipientEmails, FromName, FromAddress, ReplyTo, Subject, HtmlMessage, BulkCommunication, SendDateTime,
                    RecipientStatus, senderPersonAliasId);

                if (communication != null && communication.Recipients.Count() == 1 && RecipientGuid.HasValue)
                {
                    communication.Recipients.First().Guid = RecipientGuid.Value;
                }

                rockContext.SaveChanges();
            }
        }
Пример #19
0
        public MainViewModel()
        {
            _serializationService = new CobsSerializationService();
            _serializationService.RegisterType <MessageHandShakeRequest>(0);
            _serializationService.RegisterType <MessageAcknowledgment>(1);
            _serializationService.RegisterType <MessageAddSession>(2);
            _serializationService.RegisterType <MessageRemoveSession>(3);
            _serializationService.RegisterType <MessageUpdateVolumeSession>(4);
            _serializationService.RegisterType <MessageSetDefaultEndpoint>(5);
            _serializationService.RegisterType <MessageSettings>(6);

            _settingsViewModel = new SettingsViewModel();
            _settingsViewModel.PropertyChanged += OnSettingsChanged;

            _audioSessionService = new AudioSessionService();
            _audioSessionService.DefaultDeviceChanged += OnDefaultDeviceChanged;
            _audioSessionService.DeviceCreated        += OnDeviceCreated;
            _audioSessionService.DeviceRemoved        += OnDeviceRemoved;
            _audioSessionService.DeviceVolumeChanged  += OnDeviceVolumeChanged;
            _audioSessionService.SessionCreated       += OnAudioSessionCreated;
            _audioSessionService.SessionRemoved       += OnAudioSessionRemoved;
            _audioSessionService.SessionVolumeChanged += OnAudioSessionVolumeChanged;

            _communicationService = new CommunicationService(_serializationService);
            _communicationService.MessageReceived  += OnMessageReceived;
            _communicationService.Error            += OnCommunicationError;
            _communicationService.DeviceDiscovered += OnDeviceDiscovered;
        }
Пример #20
0
        public void Arrange()
        {
            _notificationsApi = new Mock <INotificationsApi>();
            _logger           = new Mock <ILogger>();

            _communicationService = new CommunicationService(_notificationsApi.Object, _logger.Object);
        }
Пример #21
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        private void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("CommunicationId"))
            {
                return;
            }

            Rock.Model.Communication communication = null;

            if (!itemKeyValue.Equals(0))
            {
                communication              = new CommunicationService().Get(itemKeyValue);
                RockPage.PageTitle         = string.Format("Communication #{0}", communication.Id);
                this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList();

                lTitle.Text = ("Subject: " + communication.Subject).FormatAsHtmlTitle();
            }
            else
            {
                communication = new Rock.Model.Communication()
                {
                    Status = CommunicationStatus.Transient
                };
                RockPage.PageTitle = "New Communication";
                lTitle.Text        = "New Communication".FormatAsHtmlTitle();
            }

            if (communication == null)
            {
                return;
            }

            ShowDetail(communication);
        }
Пример #22
0
        /// <summary>
        /// Handles the Click event of the btnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                using (new UnitOfWorkScope())
                {
                    var service       = new CommunicationService();
                    var communication = UpdateCommunication(service);

                    if (communication != null)
                    {
                        string message = string.Empty;

                        var prevStatus = communication.Status;
                        if (CheckApprovalRequired(communication.Recipients.Count) && !IsUserAuthorized("Approve"))
                        {
                            communication.Status = CommunicationStatus.Submitted;
                            message = "Communication has been submitted for approval.";
                        }
                        else
                        {
                            communication.Status           = CommunicationStatus.Approved;
                            communication.ReviewedDateTime = DateTime.Now;
                            communication.ReviewerPersonId = CurrentPersonId;
                            message = "Communication has been queued for sending.";

                            // TODO: Send notice to sender that communication was approved
                        }

                        communication.Recipients
                        .Where(r =>
                               r.Status == CommunicationRecipientStatus.Cancelled ||
                               r.Status == CommunicationRecipientStatus.Failed)
                        .ToList()
                        .ForEach(r =>
                        {
                            r.Status     = CommunicationRecipientStatus.Pending;
                            r.StatusNote = string.Empty;
                        }
                                 );

                        service.Save(communication, CurrentPersonId);

                        if (communication.Status == CommunicationStatus.Approved)
                        {
                            bool sendNow = false;
                            if (bool.TryParse(GetAttributeValue("SendWhenApproved"), out sendNow) && sendNow)
                            {
                                var transaction = new Rock.Transactions.SendCommunicationTransaction();
                                transaction.CommunicationId = communication.Id;
                                transaction.PersonId        = CurrentPersonId;
                                Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
                            }
                        }

                        ShowResult(message, communication);
                    }
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Handles the Click event of the btnDeny control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnDeny_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                using (new UnitOfWorkScope())
                {
                    var service       = new CommunicationService();
                    var communication = UpdateCommunication(service);

                    if (communication != null)
                    {
                        var prevStatus = communication.Status;
                        if (IsUserAuthorized("Approve"))
                        {
                            communication.Status           = CommunicationStatus.Denied;
                            communication.ReviewedDateTime = DateTime.Now;
                            communication.ReviewerPersonId = CurrentPersonId;
                        }

                        service.Save(communication, CurrentPersonId);

                        // TODO: Send notice to sneder that communication was denied

                        ShowResult("The communicaiton has been denied", communication);
                    }
                }
            }
        }
        private static void CreateCommunicationsTestData(int expirationDays, int delayMinutes)
        {
            var beginWindow     = RockDateTime.Now.AddDays(0 - expirationDays).AddDays(0 - 2);
            var endWindow       = RockDateTime.Now.AddMinutes(0 - delayMinutes).AddDays(2);
            var currentDateTime = beginWindow;
            var sender          = GetNewPersonAlias();

            var communications = new List <Rock.Model.Communication>();

            communications.AddRange(CreateCommunication(sender, null, null));

            while (beginWindow < endWindow)
            {
                communications.AddRange(CreateCommunication(sender, beginWindow, null));
                communications.AddRange(CreateCommunication(sender, beginWindow, beginWindow.AddDays(2)));
                communications.AddRange(CreateCommunication(sender, null, beginWindow));

                beginWindow = beginWindow.AddDays(1);
            }

            using (var rockContext = new RockContext())
            {
                var communicationService = new CommunicationService(rockContext);
                communicationService.AddRange(communications);
                rockContext.SaveChanges();
            }
        }
Пример #25
0
        /// <summary>
        /// Gets the HTML preview.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public override string GetHtmlPreview(Model.Communication communication, Person person)
        {
            var rockContext = new RockContext();

            // Requery the Communication object
            communication = new CommunicationService(rockContext).Get(communication.Id);

            var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
            var mergeValues      = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(null);

            if (person != null)
            {
                mergeValues.Add("Person", person);

                var recipient = communication.Recipients.Where(r => r.PersonAlias != null && r.PersonAlias.PersonId == person.Id).FirstOrDefault();
                if (recipient != null)
                {
                    // Add any additional merge fields created through a report
                    foreach (var mergeField in recipient.AdditionalMergeValues)
                    {
                        if (!mergeValues.ContainsKey(mergeField.Key))
                        {
                            mergeValues.Add(mergeField.Key, mergeField.Value);
                        }
                    }
                }
            }

            string message = communication.GetMediumDataValue("Message");

            return(message.ResolveMergeFields(mergeValues));
        }
Пример #26
0
        /// <summary>
        /// Handles the Click event of the btnTest control and sends a test communication to the
        /// current person if they have an email address on their record.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnTest_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CurrentPerson != null)
            {
                SetActionButtons(resetToSend: true);

                if (string.IsNullOrWhiteSpace(CurrentPerson.Email))
                {
                    nbError.Text    = "A test email cannot be sent because you do not have an email address.";
                    nbError.Visible = true;
                    return;
                }

                // Get existing or new communication record
                var communication = GetCommunication(new RockContext(), null);

                if (communication != null && CurrentPersonAliasId.HasValue)
                {
                    // Using a new context (so that changes in the UpdateCommunication() are not persisted )
                    var testCommunication = new Rock.Model.Communication();
                    testCommunication.SenderPersonAliasId       = communication.SenderPersonAliasId;
                    testCommunication.Subject                   = communication.Subject;
                    testCommunication.IsBulkCommunication       = communication.IsBulkCommunication;
                    testCommunication.MediumEntityTypeId        = communication.MediumEntityTypeId;
                    testCommunication.MediumDataJson            = communication.MediumDataJson;
                    testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson;

                    testCommunication.FutureSendDateTime    = null;
                    testCommunication.Status                = CommunicationStatus.Approved;
                    testCommunication.ReviewedDateTime      = RockDateTime.Now;
                    testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId.Value;

                    var testRecipient = new CommunicationRecipient();
                    if (communication.Recipients.Any())
                    {
                        var recipient = communication.Recipients.FirstOrDefault();
                        testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson;
                    }
                    testRecipient.Status        = CommunicationRecipientStatus.Pending;
                    testRecipient.PersonAliasId = CurrentPersonAliasId.Value;
                    testCommunication.Recipients.Add(testRecipient);

                    var rockContext          = new RockContext();
                    var communicationService = new CommunicationService(rockContext);
                    communicationService.Add(testCommunication);
                    rockContext.SaveChanges();

                    var medium = testCommunication.Medium;
                    if (medium != null)
                    {
                        medium.Send(testCommunication);
                    }

                    communicationService.Delete(testCommunication);
                    rockContext.SaveChanges();

                    nbTestResult.Visible = true;
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Delete a Person record, and all dependent records.
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="personId"></param>
        /// <returns></returns>
        private bool DeletePerson(RockContext dataContext, int personId)
        {
            var personService = new PersonService(dataContext);

            var person = personService.Get(personId);

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

            // Delete Person Views
            var personViewedService = new PersonViewedService(dataContext);

            var personViewedQuery = personViewedService.Queryable()
                                    .Where(x => x.TargetPersonAlias.PersonId == person.Id || x.ViewerPersonAlias.PersonId == person.Id);

            personViewedService.DeleteRange(personViewedQuery);

            // Delete Communications
            var communicationService = new CommunicationService(dataContext);

            var communicationQuery = communicationService.Queryable()
                                     .Where(x => x.SenderPersonAlias.PersonId == person.Id);

            communicationService.DeleteRange(communicationQuery);

            // Delete Communication Recipients
            var recipientsService = new CommunicationRecipientService(dataContext);

            var recipientsQuery = recipientsService.Queryable()
                                  .Where(x => x.PersonAlias.PersonId == person.Id);

            recipientsService.DeleteRange(recipientsQuery);

            // Delete Interactions
            var interactionService = new InteractionService(dataContext);

            var interactionQuery = interactionService.Queryable()
                                   .Where(x => x.PersonAlias.PersonId == person.Id);

            interactionService.DeleteRange(interactionQuery);

            // Delete Person Aliases
            var personAliasService = new PersonAliasService(dataContext);

            personAliasService.DeleteRange(person.Aliases);

            // Delete Person Search Keys
            var personSearchKeyService = new PersonSearchKeyService(dataContext);

            var searchKeys = person.GetPersonSearchKeys(dataContext);

            personSearchKeyService.DeleteRange(searchKeys);

            // Delete Person
            personService.Delete(person);

            return(true);
        }
Пример #28
0
        public async void Get_retruns_Success_location_second(int input)
        {
            LiveLocationMessage zone = new LiveLocationMessage()
            {
                UserID   = null,
                Location = "{\"type\":\"Point\",\"coordinates\":[100.0,0.0]}"
            };

            var query = JsonConvert.SerializeObject(zone);

            LiveLocationMessage liveMessage = new LiveLocationMessage()
            {
                UserID   = Guid.NewGuid(),
                Location = "{\"type\":\"Point\",\"coordinates\":[100.0,0.0]}"
            };
            var res = new List <LiveLocationMessage>();

            res.Add(liveMessage);
            // Arrange
            var mockZoneService = new Mock <ICommunicationService>();
            // mockZoneService.Setup(service =>
            //     service.interpretInput(It.IsAny<string>())
            //     ).ReturnsAsync(res);

            // Act
            var result = await CommunicationService.interpretInput(query);

            var query2  = JsonConvert.SerializeObject(result);
            var result2 = await CommunicationService.interpretInput(query);

            // Assert
            var okObjectResult = Assert.IsType <ReturnMessage>(result);
        }
Пример #29
0
        /// <summary>
        /// Gets the latest communication ID for the SMSFromDefinedValueId to the recipient within daysPastToSearch to present
        /// </summary>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="fromPersonAliasId">From person alias identifier.</param>
        /// <param name="daysPastToSearch">The days past to search.</param>
        /// <returns></returns>
        private int?GetCommunicationId(DefinedValueCache fromPhone, int fromPersonAliasId, int daysPastToSearch)
        {
            // This is the last communication
            using (var rockContext = new RockContext())
            {
                var recipientService             = new CommunicationRecipientService(rockContext);
                var latestRecipientCommunication = recipientService
                                                   .Queryable()
                                                   .AsNoTracking()
                                                   .Where(r => r.PersonAliasId == fromPersonAliasId)
                                                   .Where(r => r.CreatedDateTime >= DbFunctions.AddDays(RockDateTime.Now, -daysPastToSearch))
                                                   .OrderByDescending(c => c.CreatedDateTime)
                                                   .FirstOrDefault();

                if (latestRecipientCommunication == null)
                {
                    return(null);
                }

                var communicationService = new CommunicationService(rockContext);
                var communication        = communicationService
                                           .Queryable()
                                           .AsNoTracking()
                                           .Where(c => c.SMSFromDefinedValueId == fromPhone.Id)
                                           .Where(c => c.Id == latestRecipientCommunication.Id)
                                           .FirstOrDefault();

                if (communication != null)
                {
                    return(communication.Id);
                }

                return(null);
            }
        }
Пример #30
0
        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (CommunicationId.HasValue)
                {
                    var service       = new CommunicationService();
                    var communication = service.Get(CommunicationId.Value);
                    if (communication != null)
                    {
                        var prevStatus = communication.Status;

                        communication.Recipients
                        .Where(r => r.Status == CommunicationRecipientStatus.Pending)
                        .ToList()
                        .ForEach(r => r.Status = CommunicationRecipientStatus.Cancelled);

                        // Save and re-read communication to reload recipient statuses
                        service.Save(communication, CurrentPersonId);
                        communication = service.Get(communication.Id);

                        if (!communication.Recipients
                            .Where(r => r.Status == CommunicationRecipientStatus.Success)
                            .Any())
                        {
                            communication.Status = CommunicationStatus.Draft;
                        }

                        ShowResult("The communication has been cancelled", communication);
                    }
                }
            }
        }
Пример #31
0
        //private volatile bool m_workingCameraListReceiver = false;
        public MainForm()
        {
            m_service = new CommunicationService();

            InitializeComponent();

            FormClosed += MainForm_FormClosed;
        }
        /// <summary>
        /// Handles Client event of 'Start Server' button.
        /// </summary>
        /// <param name="sender">Source of event</param>
        /// <param name="e">Event arguments</param>
        private void btnStartServer_Click(object sender, RoutedEventArgs e)
        {
            //Get TCP port number from textbox
            int port;
            try
            {
                port = Convert.ToInt32(txtPort.Text);
                if (port <= 0 || port > 65536)
                {
                    throw new Exception(port + " is not a valid TCP port number.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("TCP port must be a positive number. Exception detail: " + ex.Message);
                return;
            }

            try
            {
                _serviceApplication = ScsServiceBuilder.CreateService(new ScsTcpEndPoint(port));
                _communicationService = new CommunicationService();
                _serviceApplication.AddService<ICommunicationService, CommunicationService>(_communicationService);
                _communicationService.ModuleListChanged += chatService_UserListChanged;
                _serviceApplication.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Service can not be started. Exception detail: " + ex.Message);
                return;
            }

            btnStartServer.IsEnabled = false;
            btnStopServer.IsEnabled = true;
            txtPort.IsEnabled = false;
        }