예제 #1
0
        public HttpResponseMessage Get()
        {
            XDocument msgToSend = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF8""?>
                                     <SMARTPLUG id=""edimax"">
	                                    <CMD id=""get"">
		                                   <Device.System.Power.State/>
	                                    </CMD>
                                     </SMARTPLUG>");

            XDocument msgReceived;

            try
            {
                msgReceived = cm.SendMessage(msgToSend, Config.IPadress, Config.Username, Config.Password);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.GatewayTimeout, ex));
            }

            var value = (string)msgReceived.Root.Value;
            List <Models.State> list = new List <Models.State>();

            list.Add(new Models.State()
            {
                IsOn = (value == "ON")
            });

            var json     = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.None);
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(response);
        }
예제 #2
0
        public HttpResponseMessage Get()
        {
            XDocument msgToSend = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF8""?>
                                                   <SMARTPLUG id=""edimax"">
                                                      <CMD id=""get"">
                                                         <SCHEDULE/>
                                                      </CMD>
                                                   </SMARTPLUG>");
            XDocument msgReceived;

            try
            {
                msgReceived = cm.SendMessage(msgToSend, Config.IPadress, Config.Username, Config.Password);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.GatewayTimeout, ex));
            }

            List <string> decodedSchedule = new List <string>();

            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.0.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.1.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.2.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.3.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.4.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.5.List").First());
            decodedSchedule.Add((string)msgReceived.Descendants("Device.System.Power.Schedule.6.List").First());

            List <Schedule> scheduleList = new List <Schedule>();

            for (int i = 0; i < decodedSchedule.Count; i++)
            {
                string[] entries = decodedSchedule[i].Split('-');
                foreach (string entry in entries)
                {
                    if (!String.IsNullOrEmpty(entry))
                    {
                        scheduleList.Add(DecodeHelper.DecodeString(i, entry));
                    }
                }
            }

            var json     = JsonConvert.SerializeObject(scheduleList, Newtonsoft.Json.Formatting.None);
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(response);
        }
예제 #3
0
        public HttpResponseMessage Get()
        {
            XDocument msgToSend = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF8""?>
                                     <SMARTPLUG id=""edimax"">
                                        <CMD id=""get"">
                                           <SYSTEM_INFO/>
                                        </CMD>
                                     </SMARTPLUG>");

            XDocument msgReceived;

            try
            {
                msgReceived = cm.SendMessage(msgToSend, Config.IPadress, Config.Username, Config.Password);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.GatewayTimeout, ex));
            }

            List <Models.DeviceConfig> list = new List <Models.DeviceConfig>();

            list.Add(new Models.DeviceConfig()
            {
                Name         = (string)msgReceived.Descendants("Device.System.Name").First(),
                Model        = (string)msgReceived.Descendants("Run.Model").First(),
                MAC          = (string)msgReceived.Descendants("Run.LAN.Client.MAC.Address").First(),
                IsMailingOn  = ((string)msgReceived.Descendants("Device.System.Power.Schedule.Support").First() == "1"),
                IsScheduleOn = ((string)msgReceived.Descendants("Device.System.SMTP.Support").First() == "1")
            });

            var json     = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.None);
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(response);
        }
예제 #4
0
        public HttpResponseMessage Get()
        {
            XDocument msgToSend = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF8""?>
                                     <SMARTPLUG id = ""edimax"">
                                        <CMD id = ""get"">
                                           <NOW_POWER/>
                                        </CMD>
                                     </SMARTPLUG>");

            XDocument msgReceived;

            try
            {
                msgReceived = cm.SendMessage(msgToSend, Config.IPadress, Config.Username, Config.Password);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.GatewayTimeout, ex));
            }

            List <Models.CurrentRun> list = new List <Models.CurrentRun>();

            list.Add(new Models.CurrentRun()
            {
                LastToogleTime = DateTime.ParseExact((string)msgReceived.Descendants("Device.System.Power.LastToggleTime").First(),
                                                     "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture),
                CurrentValue = Double.Parse((string)msgReceived.Descendants("Device.System.Power.NowCurrent").First(), CultureInfo.InvariantCulture),
                PowerValue   = Double.Parse((string)msgReceived.Descendants("Device.System.Power.NowPower").First(), CultureInfo.InvariantCulture),
                EnergyValue  = new Models.Energy()
                {
                    Day   = Double.Parse((string)msgReceived.Descendants("Device.System.Power.NowEnergy.Day").First(), CultureInfo.InvariantCulture),
                    Week  = Double.Parse((string)msgReceived.Descendants("Device.System.Power.NowEnergy.Week").First(), CultureInfo.InvariantCulture),
                    Month = Double.Parse((string)msgReceived.Descendants("Device.System.Power.NowEnergy.Month").First(), CultureInfo.InvariantCulture)
                }
            });

            var json     = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.None);
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(response);
        }
예제 #5
0
        /// <summary>
        /// Sends the attendance reminders.
        /// </summary>
        /// <param name="leaders">The leaders.</param>
        /// <param name="occurrences">The occurrences.</param>
        /// <param name="systemCommunication">The system communication.</param>
        /// <param name="jobPreferredCommunicationType">Type of the job preferred communication.</param>
        /// <param name="isSmsEnabled">if set to <c>true</c> [is SMS enabled].</param>
        /// <returns></returns>
        private SendMessageResult SendAttendanceReminders(List <GroupMember> leaders,
                                                          Dictionary <int, List <DateTime> > occurrences,
                                                          SystemCommunication systemCommunication,
                                                          CommunicationType jobPreferredCommunicationType,
                                                          bool isSmsEnabled)
        {
            var result = new SendMessageResult();

            // Loop through the leaders
            foreach (var leader in leaders)
            {
                var mediumType = Rock.Model.Communication.DetermineMediumEntityTypeId(
                    ( int )CommunicationType.Email,
                    ( int )CommunicationType.SMS,
                    ( int )CommunicationType.PushNotification,
                    jobPreferredCommunicationType,
                    leader.CommunicationPreference,
                    leader.Person.CommunicationPreference);

                var leaderOccurrences = occurrences.Where(o => o.Key == leader.GroupId);
                foreach (var leaderOccurrence in leaderOccurrences)
                {
                    var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null, leader.Person);
                    mergeObjects.Add("Person", leader.Person);
                    mergeObjects.Add("Group", leader.Group);
                    mergeObjects.Add("Occurrence", leaderOccurrence.Value.Max());

                    var sendResult = CommunicationHelper.SendMessage(leader.Person, mediumType, systemCommunication, mergeObjects);

                    result.MessagesSent += sendResult.MessagesSent;
                    result.Errors.AddRange(sendResult.Errors);
                    result.Warnings.AddRange(sendResult.Warnings);
                }
            }
            return(result);
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        /// <param name="message"></param>
        public override void Execute(Message message)
        {
            using (var rockContext = new RockContext())
            {
                // Load the alert and alert type
                var financialTransactionAlertService = new FinancialTransactionAlertService(rockContext);
                var alert = financialTransactionAlertService.Queryable()
                            .AsNoTracking()
                            .Include(a => a.FinancialTransactionAlertType)
                            .FirstOrDefault(a => a.Id == message.FinancialTransactionAlertId);

                var alertType = alert?.FinancialTransactionAlertType;

                // If the alert or alert type are no longer in the database, then there is nothing that can be done
                if (alertType == null)
                {
                    return;
                }

                // Get the person that this alert was generated for. Several of the items below use this
                var personAliasService = new PersonAliasService(rockContext);
                var person             = personAliasService.Queryable()
                                         .AsNoTracking()
                                         .Where(pa => pa.Id == alert.PersonAliasId)
                                         .Select(pa => pa.Person)
                                         .FirstOrDefault();

                // Generate the merge objects for the lava templates used in the items below
                var isoDate           = alert.AlertDateTime.ToISO8601DateString();
                var alertsPageId      = PageCache.Get(SystemGuid.Page.GIVING_ALERTS).Id;
                var relativeAlertLink = $"page/{alertsPageId}?StartDate={isoDate}&EndDate={isoDate}&AlertTypeId={alertType.Id}";

                var mergeObjects = new Dictionary <string, object> {
                    { nameof(FinancialTransactionAlert), alert },
                    { nameof(FinancialTransactionAlertType), alertType },
                    { nameof(Person), person },
                    { "RelativeAlertLink", relativeAlertLink }
                };

                // Launch workflow if configured
                if (alertType.WorkflowTypeId.HasValue)
                {
                    var workflowAttributeValues = new Dictionary <string, string>();
                    workflowAttributeValues.Add(nameof(FinancialTransactionAlert), alert.Guid.ToString());
                    workflowAttributeValues.Add(nameof(FinancialTransactionAlertType), alertType.Guid.ToString());
                    workflowAttributeValues.Add(nameof(Person), person.Guid.ToString());
                    alert.LaunchWorkflow(alertType.WorkflowTypeId, string.Empty, workflowAttributeValues, null);
                }

                // Add the person to a connection opportunity if configured
                if (alertType.ConnectionOpportunityId.HasValue)
                {
                    var connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    var statuses = connectionOpportunityService.Queryable()
                                   .AsNoTracking()
                                   .Where(co =>
                                          co.Id == alertType.ConnectionOpportunityId)
                                   .SelectMany(co => co.ConnectionType.ConnectionStatuses)
                                   .Where(cs => cs.IsActive)
                                   .ToList()
                                   .OrderBy(cs => cs.Order);

                    var status = statuses.FirstOrDefault(cs => cs.IsDefault) ?? statuses.FirstOrDefault();

                    if (status != null)
                    {
                        var connectionRequestService = new ConnectionRequestService(rockContext);
                        var request = new ConnectionRequest
                        {
                            ConnectionOpportunityId = alertType.ConnectionOpportunityId.Value,
                            PersonAliasId           = alert.PersonAliasId,
                            ConnectionStatusId      = status.Id
                        };

                        if (alert.TransactionId.HasValue)
                        {
                            request.LoadAttributes();
                            request.SetAttributeValue("FinancialTransactionId", alert.TransactionId.Value.ToString());
                        }

                        connectionRequestService.Add(request);
                    }
                }

                // Send a bus event if configured
                if (alertType.SendBusEvent)
                {
                    new TransactionWasAlertedMessage
                    {
                        FinancialTransactionAlertId = alert.Id
                    }.Publish();
                }

                // Send a communication if configured
                if (alertType.SystemCommunicationId.HasValue)
                {
                    var systemCommunicationService = new SystemCommunicationService(rockContext);
                    var systemCommunication        = systemCommunicationService.Get(alertType.SystemCommunicationId.Value);

                    if (person != null && systemCommunication != null)
                    {
                        CommunicationHelper.SendMessage(person, ( int )person.CommunicationPreference, systemCommunication, mergeObjects);
                    }
                }

                // Send a communication to account followers if an Account Participant System Communication and Account is specified
                // for this alert type
                if (alertType.AccountParticipantSystemCommunicationId.HasValue && alertType.FinancialAccountId.HasValue)
                {
                    var systemCommunicationService            = new SystemCommunicationService(rockContext);
                    var financialAccountService               = new FinancialAccountService(rockContext);
                    var accountParticipantSystemCommunication = systemCommunicationService.Get(alertType.AccountParticipantSystemCommunicationId.Value);
                    if (accountParticipantSystemCommunication != null)
                    {
                        var accountFollowers = financialAccountService
                                               .GetAccountParticipants(alertType.FinancialAccountId.Value, RelatedEntityPurposeKey.FinancialAccountGivingAlert)
                                               .Select(a => a.Person);

                        foreach (var accountFollower in accountFollowers)
                        {
                            CommunicationHelper.SendMessage(accountFollower, ( int )accountFollower.CommunicationPreference, accountParticipantSystemCommunication, mergeObjects);
                        }
                    }
                }

                // Send a notification to a group if configured
                if (alertType.AlertSummaryNotificationGroupId.HasValue)
                {
                    var systemEmailGuid            = SystemGuid.SystemCommunication.FINANCIAL_TRANSACTION_ALERT_NOTIFICATION_SUMMARY.AsGuid();
                    var systemCommunicationService = new SystemCommunicationService(rockContext);
                    var systemCommunication        = systemCommunicationService.Get(systemEmailGuid);

                    CommunicationHelper.SendMessage(alertType.AlertSummaryNotificationGroupId.Value, systemCommunication, mergeObjects);
                }

                rockContext.SaveChanges();
            }
        }
예제 #7
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.Get(AttributeKey.SystemCommunication).ToString().AsGuid();
            var        groupGuid         = dataMap.Get(AttributeKey.Group).ToString().AsGuid();
            var        sendToDescendants = dataMap.Get(AttributeKey.SendToDescendantGroups).ToString().AsBoolean();

            var rockContext         = new RockContext();
            var systemCommunication = new SystemCommunicationService(rockContext).Get(emailTemplateGuid);

            var group = new GroupService(rockContext).Get(groupGuid);

            if (group != null)
            {
                var groupIds = new List <int>();
                GetGroupIds(groupIds, sendToDescendants, group);

                var recipients = new List <RockEmailMessageRecipient>();

                var groupMemberList = new GroupMemberService(rockContext)
                                      .Queryable()
                                      .Where(gm => groupIds.Contains(gm.GroupId))
                                      .Where(gm => gm.GroupMemberStatus == GroupMemberStatus.Active)
                                      .ToList();

                var errors       = new List <string>();
                var warnings     = new List <string>();
                var messagesSent = 0;

                foreach (GroupMember groupMember in groupMemberList)
                {
                    var person = groupMember.Person;

                    var mediumType = Rock.Model.Communication.DetermineMediumEntityTypeId(
                        ( int )CommunicationType.Email,
                        ( int )CommunicationType.SMS,
                        ( int )CommunicationType.PushNotification,
                        groupMember.CommunicationPreference,
                        person.CommunicationPreference);

                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", person);
                    mergeFields.Add("GroupMember", groupMember);
                    mergeFields.Add("Group", groupMember.Group);

                    var sendMessageResults = CommunicationHelper.SendMessage(person, mediumType, systemCommunication, mergeFields);
                    errors.AddRange(sendMessageResults.Errors);
                    warnings.AddRange(sendMessageResults.Warnings);
                    messagesSent += sendMessageResults.MessagesSent;
                }

                var jobResults = new StringBuilder($"{messagesSent} messages were sent.");
                if (warnings.Any())
                {
                    jobResults.AppendLine();
                    jobResults.AppendLine($"{warnings.Count} warnings:");
                    warnings.ForEach(w => { jobResults.AppendLine(w); });
                }

                context.Result = jobResults.ToString();
                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errors.Count()));
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    context.Result += errorMessage;
                    var         exception = new Exception(errorMessage);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
        }