private void CreateAndSendEmailMessageFromTemplate(WebHookEvent evt)
        {
            var metadata = ParseMetadataFromMandrill(evt);
            var message  = new Mandrill.EmailMessage();

            message.to = new List <Mandrill.EmailAddress>()
            {
                new EmailAddress {
                    email = "*****@*****.**"
                },
                new EmailAddress {
                    email = "*****@*****.**"
                }
            };

            message.subject    = String.Format("Bounced email notification", evt.Event);
            message.from_email = "*****@*****.**";


            if (metadata.ContainsKey("CustID"))
            {
                message.AddGlobalVariable("customerID", metadata["CustID"].ToUpper());
            }
            else
            {
                message.AddGlobalVariable("customerID", "Unknown");
            }
            message.AddGlobalVariable("bouncedEmailAddress", evt.Msg.Email);
            message.AddGlobalVariable("application", GetSendingApplicationName(evt));
            message.AddGlobalVariable("timesent", TimeZoneInfo.ConvertTimeFromUtc(evt.Msg.TimeStamp, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")).ToString());

            _mandrillApi.SendMessage(message, "mandrill-email-bounce", null);
        }
Exemple #2
0
        public EventContextTests()
        {
            _httpContext  = Substitute.For <HttpContext>();
            _webHookEvent = new WebHookEventFaker().Generate();
            var gitHubClientFake = Substitute.For <GitHubClient>(new ProductHeaderValue("test"));

            _gitHubClients = Substitute.For <GitHubClients>(gitHubClientFake, gitHubClientFake);

            _sut = new EventContext(_httpContext, _webHookEvent, _gitHubClients);
        }
        private static Dictionary <string, string> ParseMetadataFromMandrill(WebHookEvent evt)
        {
            var metadata = new Dictionary <string, string>();

            if (evt.Msg.Metadata != null)
            {
                metadata = evt.Msg.Metadata.ToDictionary(m => m.Key, m => m.Value);
            }
            return(metadata);
        }
        public void Event_Serialize()
        {
            var webhook =
                new WebHookEvent
            {
                Event     = WebHookEventType.Click,
                IP        = "127.0.0.1",
                TS        = 1355340679,
                Url       = "http://clicked.me",
                UserAgent = "outlook",
                Msg       = new WebHookMessage
                {
                    TS      = 1355340679,
                    Subject = "Important Stuff",
                    Email   = "*****@*****.**",
                    Tags    = new List <string> {
                        "tag1", "tag2", "tag3"
                    },
                    Metadata = new List <WebHookMetadata>
                    {
                        new WebHookMetadata {
                            Key = "key1", Value = "val1"
                        },
                        new WebHookMetadata {
                            Key = "key2", Value = "val2"
                        }
                    },
                    Opens = new List <WebHookOpen>
                    {
                        new WebHookOpen {
                            TS = 1355340679
                        },
                        new WebHookOpen {
                            TS = 1355340679
                        }
                    },
                    State  = WebHookMessageState.Sent,
                    Clicks = new List <WebHookClick>
                    {
                        new WebHookClick {
                            TS = 1355773922, Url = @"http:\\www.GitHub.com"
                        }
                    },
                    Id         = "fc8071b3575e44228d5dd7059349ba10",
                    Sender     = "*****@*****.**",
                    Template   = "ValidTemplate",
                    SubAccount = "validSubAccount"
                }
            };

            var output = JSON.Serialize(webhook);
            var clone  = JSON.Parse <WebHookEvent>(output);

            Assert.That(webhook.Msg.Metadata.Count == clone.Msg.Metadata.Count);
        }
Exemple #5
0
        public static void EventHandler(string script)
        {
            var e = new WebHookEvent(script);

            switch (script)
            {
            case SUCCESS:       OnWebHookSuccess(e); break;

            case FAILURE:       OnWebHookFailure(e); break;
            }
        }
        private string GetSendingApplicationName(WebHookEvent evt)
        {
            if (evt.Msg.Tags.Contains("SecureFTP"))
            {
                return("Secure FTP Site");
            }
            if (evt.Msg.Subject.Contains("FAST"))
            {
                return("JobTracker - FAST System");
            }

            return(string.Format("Unknown Application. Subject line was: {0}", evt.Msg.Subject));
        }
Exemple #7
0
        /// <summary>
        /// Sends the hooks for the specified hook event, of the specified schema
        /// </summary>
        /// <param name="id">Id of job to send hooks for</param>
        /// <param name="hookEvent">The hook event to send for</param>
        /// <param name="doForSchema">The hook schame to send for</param>
        public void SendJobHooks(int id, WebHookEvent hookEvent, string doForSchema)
        {
            var action = new Data.Action
            {
                Name         = "sendhook",
                AssociatedId = hookEvent.ToString()
            };

            var resource   = string.Format("Jobs/{0}/Action", id);
            var callParams = string.Format("sendhook_schema={0}", doForSchema);

            CallWithRetry(resource, "POST", false, action, callParams);
        }
        // POST /api/sign
        public async Task <HttpResponseMessage> Post([FromBody] WebHookEvent payload)
        {
            if (payload.Payload.PackageIdentifier.EndsWith(ConfigurationManager.AppSettings["Signature:PackageIdSuffix"]))
            {
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    ReasonPhrase = "Package is already signed. "
                });
            }

            string tempPath = Path.GetTempFileName();

            try
            {
                // Download the package
                var httpClient    = new HttpClient();
                var packageStream = await httpClient.GetStreamAsync(payload.Payload.PackageDownloadUrl);

                using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    packageStream.CopyTo(stream);
                }

                // Sign the package
                PackageSigner signer = new PackageSigner();
                if (signer.SignPackage(tempPath, tempPath,
                                       System.Web.Hosting.HostingEnvironment.MapPath("~/" + ConfigurationManager.AppSettings["Signature:KeyFile"]),
                                       ConfigurationManager.AppSettings["Signature:KeyFilePassword"],
                                       payload.Payload.PackageIdentifier + ConfigurationManager.AppSettings["Signature:PackageIdSuffix"]))
                {
                    var server = new PackageServer(ConfigurationManager.AppSettings["Signature:NuGetFeedUrl"], "Signature/1.0");
                    server.PushPackage(ConfigurationManager.AppSettings["Signature:NuGetFeedApiKey"], new OptimizedZipPackage(tempPath), new FileInfo(tempPath).Length, 60 * 1000, true);
                    OptimizedZipPackage.PurgeCache();

                    return(new HttpResponseMessage(HttpStatusCode.Created)
                    {
                        ReasonPhrase = "Package has been signed."
                    });
                }
            }
            finally
            {
                File.Delete(tempPath);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                ReasonPhrase = "Package is already signed."
            });
        }
        private void UnsubscribeEmailfromMailChimpList(WebHookEvent evt)
        {
            var metadata = ParseMetadataFromMandrill(evt);

            try
            {
                var result = _mailChimpApi.Unsubscribe(metadata["MCList"], new EmailParameter()
                {
                    Email = evt.Msg.Email
                }, false, false, false);
            }
            catch (Exception)
            {
            }
        }
Exemple #10
0
 public static Task Run(this IWebHookHandler webHookHandler, WebHookEvent webHookEvent)
 {
     if (webHookEvent is DeliveredEvent)
     {
         return(webHookHandler.OnDelivieredAsync((DeliveredEvent)webHookEvent));
     }
     if (webHookEvent is ProcessedEvent)
     {
         return(webHookHandler.OnProcessedAsync((ProcessedEvent)webHookEvent));
     }
     if (webHookEvent is OpenEvent)
     {
         return(webHookHandler.OnOpenAsync((OpenEvent)webHookEvent));
     }
     if (webHookEvent is ClickEvent)
     {
         return(webHookHandler.OnClickAsync((ClickEvent)webHookEvent));
     }
     if (webHookEvent is SpamEvent)
     {
         return(webHookHandler.OnSpamReportAsync((SpamEvent)webHookEvent));
     }
     if (webHookEvent is DeferredEvent)
     {
         return(webHookHandler.OnDeferredAsync((DeferredEvent)webHookEvent));
     }
     if (webHookEvent is DroppedEvent)
     {
         return(webHookHandler.OnDroppedAsync((DroppedEvent)webHookEvent));
     }
     if (webHookEvent is BounceEvent)
     {
         return(webHookHandler.OnBouncedAsync((BounceEvent)webHookEvent));
     }
     if (webHookEvent is UnsubscribeEvent)
     {
         return(webHookHandler.OnUnsubscribeAsync((UnsubscribeEvent)webHookEvent));
     }
     if (webHookEvent is GroupUnsubscribeEvent)
     {
         return(webHookHandler.OnGroupUnsubscribeAsync((GroupUnsubscribeEvent)webHookEvent));
     }
     if (webHookEvent is GroupResubscribeEvent)
     {
         return(webHookHandler.OnGroupResubscribeAsync((GroupResubscribeEvent)webHookEvent));
     }
     throw new ArgumentOutOfRangeException(nameof(webHookEvent));
 }
        public async Task Handle(WebHookEvent webHookEvent)
        {
            var clients = await _gitHubClientFactory.Create();

            var handlers = _webHookHandlerResolver.Resolve(webHookEvent.EventName,
                                                           webHookEvent.GenericPayload.Action, webHookEvent.IsBot);

            if (!handlers.Any())
            {
                return;
            }

            var context = new EventContext(_httpContextAccessor.HttpContext, webHookEvent, clients);

            handlers.ForEach(h => h.Handle(context));
        }
        public WorkItemEventContext CreateContextFromEvent(WebHookEvent eventData)
        {
            var collectionUrl = eventData.ResourceContainers.GetValueOrDefault("collection")?.BaseUrl ?? MagicConstants.MissingUrl;
            var teamProjectId = eventData.ResourceContainers.GetValueOrDefault("project")?.Id ?? Guid.Empty;

            if (eventData.Resource is Newtonsoft.Json.Linq.JObject)
            {
                // Azure Function uses Newtonsoft.Json
                return(Newtonsoft_CreateContextFromEvent(eventData, collectionUrl, teamProjectId));
            }
            else
            {
                // ASP.Net uses System.Text.Json
                return(SystemTextJson_CreateContextFromEvent(eventData, collectionUrl, teamProjectId));
            }
        }
Exemple #13
0
        public async Task <WebHookEvent> Create(HttpContext context)
        {
            string payload;

            using (var sr = new StreamReader(context.Request.Body))
            {
                payload = await sr.ReadToEndAsync();
            }

            var webHookEvent = new WebHookEvent(context.Request.Headers[WebHookConstants.EventHeader],
                                                context.Request.Headers[WebHookConstants.DeliveryHeader],
                                                context.Request.Headers[WebHookConstants.HubSignatureHeader],
                                                payload,
                                                _serializer);

            return(webHookEvent);
        }
Exemple #14
0
        public async Task Demultiplex(WebHookEvent webHookEvent)
        {
            switch (webHookEvent.PayloadType)
            {
            case "PackageAddedWebHookEventPayloadV1":
                await _addPackageAgent.AddPackage(new Uri(webHookEvent.Payload.PackageDownloadUrl));

                break;

            default:
                throw new HttpResponseException(new HttpResponseMessage
                {
                    StatusCode   = HttpStatusCode.BadRequest,
                    ReasonPhrase = "Unknown PayloadType",
                });
            }
        }
        private static void CreateAndSendEmailMessage(WebHookEvent evt)
        {
            var metadata = ParseMetadataFromMandrill(evt);
            var message  = new Mandrill.EmailMessage();

            message.to = new List <Mandrill.EmailAddress>()
            {
                new EmailAddress {
                    email = "*****@*****.**"
                }
            };

            message.subject    = String.Format("TEST Bounced email notification", evt.Event);
            message.from_email = "*****@*****.**";

            StringBuilder body = new StringBuilder();

            body.AppendFormat("An email being sent to {0} has bounced.", evt.Msg.Email).AppendLine();
            body.AppendFormat("Email sent from address: {0}", evt.Msg.Sender).AppendLine();
            body.AppendFormat("Email subject line: {0}", evt.Msg.Subject).AppendLine();
            body.AppendLine();
            body.AppendLine("Please contact the customer and get an updated email address, or remove this email address from all systems.");
            body.AppendLine("This includes: Goldmine, JobTracker & SecureFTP");
            body.AppendFormat("Message sent at: {0}", TimeZoneInfo.ConvertTimeFromUtc(evt.Msg.TimeStamp, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))).AppendLine();
            body.AppendLine("----");

            if (metadata.ContainsKey("CustID"))
            {
                body.AppendFormat("Customer ID: {0}", metadata["CustID"]);
                body.AppendLine();
            }

            if (evt.Msg.Tags != null)
            {
                body.Append("System Tags:");
                foreach (string tag in evt.Msg.Tags)
                {
                    body.Append(" " + tag);
                }
            }

            message.text = body.ToString();

            _api.SendMessage(message);
        }
        private WorkItemEventContext Newtonsoft_CreateContextFromEvent(WebHookEvent eventData, string collectionUrl, Guid teamProjectId)
        {
            var resourceObject = eventData.Resource as Newtonsoft.Json.Linq.JObject;

            if (ServiceHooksEventTypeConstants.WorkItemUpdated == eventData.EventType)
            {
                var workItem = resourceObject.GetValue("revision").ToObject <WorkItem>();
                MigrateIdentityInformation(eventData.ResourceVersion, workItem);
                var workItemUpdate = resourceObject.ToObject <WorkItemUpdate>();
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem, eventData.EventType, workItemUpdate));
            }
            else
            {
                var workItem = resourceObject.ToObject <WorkItem>();
                MigrateIdentityInformation(eventData.ResourceVersion, workItem);
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem, eventData.EventType));
            }
        }
        public WorkItemEventContext SystemTextJson_CreateContextFromEvent(WebHookEvent eventData, string collectionUrl, Guid teamProjectId)
        {
            var resourceObject = (JsonElement)eventData.Resource;

            if (ServiceHooksEventTypeConstants.WorkItemUpdated == eventData.EventType)
            {
                var workItem = resourceObject.GetProperty("revision").ToObject <WorkItem>();
                MigrateIdentityInformation(eventData.ResourceVersion, workItem);
                var workItemUpdate = resourceObject.ToObject <WorkItemUpdate>();
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem, eventData.EventType, workItemUpdate));
            }
            else
            {
                var workItem = resourceObject.ToObject <WorkItem>();
                MigrateIdentityInformation(eventData.ResourceVersion, workItem);
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem, eventData.EventType));
            }
        }
        public async Task <OkResult> Webhook([FromBody] WebHookEvent jsonData)
        {
            this.botService.Restore();
            var appCredentials = new MicrosoftAppCredentials(configuration);

            MicrosoftAppCredentials.TrustServiceUrl(this.botService.serviceUrl);
            var connector = new ConnectorClient(new Uri(this.botService.serviceUrl), appCredentials);

            IMessageActivity newActivity = Activity.CreateMessageActivity();

            newActivity.From         = this.botService.account;
            newActivity.ChannelId    = "emulator";
            newActivity.Conversation = new ConversationAccount(id: this.botService.conversationId);
            newActivity.Text         = jsonData.eventType;

            await connector.Conversations.SendToConversationAsync(this.botService.conversationId, (Activity)newActivity);

            return(Ok());
        }
        private static WorkItemEventContext CreateContextFromEvent(WebHookEvent eventData)
        {
            var collectionUrl = eventData.ResourceContainers.GetValueOrDefault("collection")?.BaseUrl ?? "https://example.com";
            var teamProjectId = eventData.ResourceContainers.GetValueOrDefault("project")?.Id ?? Guid.Empty;

            var resourceObject = eventData.Resource as JObject;

            if (ServiceHooksEventTypeConstants.WorkItemUpdated == eventData.EventType)
            {
                var workItem       = resourceObject.GetValue("revision").ToObject <WorkItem>();
                var workItemUpdate = resourceObject.ToObject <WorkItemUpdate>();
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem, workItemUpdate));
            }
            else
            {
                var workItem = resourceObject.ToObject <WorkItem>();
                return(new WorkItemEventContext(teamProjectId, new Uri(collectionUrl), workItem));
            }
        }
Exemple #20
0
        /// <summary>
        /// Returns a serial representation of the job in the specified format and schema.
        /// </summary>
        /// <param name="format">Format to serialize to.</param>
        /// <param name="schema">Schema to serialize to.</param>
        /// <param name="forEvent">The WebHookEvent that this message represents.</param>
        /// <param name="timeStamp">Time in UTC that this message was created</param>
        /// <param name="hookId">The id of the hook this that will send this data</param>
        /// <param name="deviceTime">Time in UTC that the associated message was created on the device</param>
        /// <returns>The serialized object.</returns>
        public string ToString(
            MessageFormat format,
            WebHookSchema schema,
            WebHookEvent forEvent,
            DateTime timeStamp,
            int hookId,
            DateTime?deviceTime = null)
        {
            switch (schema)
            {
            case WebHookSchema.Cdn:
                return(Serialization.Serialize(this, format));

            case WebHookSchema.Fenkell02:
                return(new Delivery(this, true).ToString());

            case WebHookSchema.Fenkell05:
                return(new Delivery(this, false).ToString());

            case WebHookSchema.TmwV1:
                return(new Stop(this).ToString(forEvent, timeStamp, hookId.ToString(), deviceTime));

            case WebHookSchema.PodUrl:
            {
                switch (forEvent)
                {
                case WebHookEvent.PickupStop:
                    return(this.Pickup.ProofDocUrl + "&m=download");

                case WebHookEvent.DropoffStop:
                    return(this.Dropoff.ProofDocUrl + "&m=download");

                default:
                    return(null);
                }
            }

            default:
                throw new ArgumentException(string.Format("Schema {0} is not a valid WebHookSchema", schema), "schema");
            }
        }
Exemple #21
0
        public override void Process(EventContext ctx)
        {
            // if they don't have premium features, then we don't need to queue notifications
            if (!ctx.Organization.HasPremiumFeatures)
            {
                return;
            }

            _notificationQueue.EnqueueAsync(new EventNotification {
                Event        = ctx.Event,
                IsNew        = ctx.IsNew,
                IsCritical   = ctx.Event.IsCritical,
                IsRegression = ctx.IsRegression,
                //TotalOccurrences = ctx.Stack.TotalOccurrences,
                ProjectName = ctx.Project.Name
            }).Wait();

            // TODO: Get by organization id or project id.
            foreach (WebHook hook in _webHookRepository.GetByProjectId(ctx.Event.ProjectId))
            {
                bool shouldCall = hook.EventTypes.Contains(WebHookRepository.EventTypes.NewError) && ctx.IsNew ||
                                  hook.EventTypes.Contains(WebHookRepository.EventTypes.ErrorRegression) && ctx.IsRegression ||
                                  hook.EventTypes.Contains(WebHookRepository.EventTypes.CriticalError) && ctx.Event.Tags != null && ctx.Event.Tags.Contains("Critical");

                if (!shouldCall)
                {
                    continue;
                }

                Log.Trace().Project(ctx.Event.ProjectId).Message("Web hook queued: project={0} url={1}", ctx.Event.ProjectId, hook.Url).Write();

                _webHookNotificationQueue.EnqueueAsync(new WebHookNotification {
                    ProjectId = ctx.Event.ProjectId,
                    Url       = hook.Url,
                    Data      = WebHookEvent.FromEvent(ctx, _projectRepository, _stackRepository, _organizationRepository)
                }).Wait();
            }
        }
Exemple #22
0
        /// <summary>
        /// Returns a serial representation of the object.
        /// </summary>
        /// <param name="forEvent">The event for which to serialise this job</param>
        /// <param name="timeStamp">Time in UTC that this message was created</param>
        /// <param name="messageGuid">A unique identifier for this message</param>
        /// <returns>The serialized object.</returns>
        public string ToString(WebHookEvent forEvent, DateTime timeStamp, string messageGuid)
        {
            const string lineEndChar = "\r\n";

            var message = new StringBuilder();

            message.AppendFormat("ID=SN:{0}{1}", messageGuid, lineEndChar);
            message.AppendFormat("Subject=*Login Info*{0}", lineEndChar);
            message.AppendFormat("Preview=*Login Info*{0}", lineEndChar);
            message.AppendFormat("FormID=2-R{0}", lineEndChar);
            message.AppendFormat("DataType=Form{0}", lineEndChar);
            message.AppendFormat("FromName={0}{1}", _device.Name, lineEndChar);
            message.AppendFormat("CreateTime={0:yyyy-MM-dd HH:mm:ss}{1}", timeStamp, lineEndChar);
            message.AppendFormat("CreateTimeTZ=0{0}", lineEndChar);
            message.AppendFormat("ReplyMsgID=SN:0{0}", lineEndChar);
            message.AppendFormat("Priority=0{0}", lineEndChar);
            message.AppendFormat("MessageData:{0}", lineEndChar);

            message.AppendFormat("{0}{1}", _driver.RemoteId, lineEndChar);
            message.AppendFormat("{0}{1}", "Login", lineEndChar);
            message.AppendFormat("{0:yyyy-MM-dd HH:mm:ss}{1}", timeStamp, lineEndChar);

            return(message.ToString());
        }
        /// <summary>
        /// Returns a serial representation of the object.
        /// </summary>
        /// <param name="forEvent">The event for which to serialise this job</param>
        /// <param name="timeStamp">Time in UTC that this message was created</param>
        /// <param name="messageGuid">A unique identifier for this message</param>
        /// <returns>The serialized object.</returns>
        public string ToString(WebHookEvent forEvent, DateTime timeStamp, string messageGuid)
        {
            const string lineEndChar = "\r\n";

            var message = new StringBuilder();

            message.AppendFormat("ID=SN:{0}{1}", messageGuid, lineEndChar);
            message.AppendFormat("Subject=*Login Info*{0}", lineEndChar);
            message.AppendFormat("Preview=*Login Info*{0}", lineEndChar);
            message.AppendFormat("FormID=2-R{0}", lineEndChar);
            message.AppendFormat("DataType=Form{0}", lineEndChar);
            message.AppendFormat("FromName={0}{1}", _device.Name, lineEndChar);
            message.AppendFormat("CreateTime={0:yyyy-MM-dd HH:mm:ss}{1}", timeStamp, lineEndChar);
            message.AppendFormat("CreateTimeTZ=0{0}", lineEndChar);
            message.AppendFormat("ReplyMsgID=SN:0{0}", lineEndChar);
            message.AppendFormat("Priority=0{0}", lineEndChar);
            message.AppendFormat("MessageData:{0}", lineEndChar);

            message.AppendFormat("{0}{1}", _driver.RemoteId, lineEndChar);
            message.AppendFormat("{0}{1}", "Login", lineEndChar);
            message.AppendFormat("{0:yyyy-MM-dd HH:mm:ss}{1}", timeStamp, lineEndChar);

            return message.ToString();
        }
Exemple #24
0
 public EventContext(HttpContext httpContext, WebHookEvent webHookEvent, GitHubClients clients)
 {
     HttpContext  = httpContext;
     WebHookEvent = webHookEvent;
     Clients      = clients;
 }
Exemple #25
0
        public async Task <IActionResult> Post(WebHookEvent request)
        {
            await _lineService.RunAsync(request.Events);

            return(Ok());
        }
        /// <summary>
        /// Returns a serial representation of the object.
        /// </summary>
        /// <param name="forEvent">The event for which to serialise this job</param>
        /// <param name="timeStamp">Time in UTC that this message was created</param>
        /// <param name="messageGuid">A unique identifier for this message</param>
        /// <param name="deviceTime">Time in UTC that the associaed message was created on the device</param>
        /// <returns>The serialized object.</returns>
        public string ToString(WebHookEvent forEvent, DateTime timeStamp, string messageGuid, DateTime? deviceTime = null)
        {
            const string lineEndChar = "\r\n";
            
            var message = new StringBuilder();

            message.AppendFormat("ID=SN:{0}{1}", messageGuid, lineEndChar);
            message.AppendFormat("Subject=*Stop Info*{0}", lineEndChar);
            message.AppendFormat("Preview=*Stop Info*{0}", lineEndChar);
            message.AppendFormat("FormID=1-R{0}", lineEndChar);
            message.AppendFormat("DataType=Form{0}", lineEndChar);
            message.AppendFormat("FromName={0}{1}", _job.AssignedAppId, lineEndChar);
            message.AppendFormat("CreateTime={0:yyyy-MM-dd HH:mm:ss}{1}", timeStamp, lineEndChar);
            message.AppendFormat("CreateTimeTZ=0{0}", lineEndChar);
            message.AppendFormat("ReplyMsgID=SN:0{0}", lineEndChar);
            message.AppendFormat("Priority=0{0}", lineEndChar);
            message.AppendFormat("MessageData:{0}", lineEndChar);

            message.AppendFormat("{0}{1}", _job.AllocatedCarrierScac, lineEndChar);
            message.AppendFormat("{0}{1}", _job.AssignedDriverRemoteId, lineEndChar);
            message.AppendFormat("{0}{1}", _job.AssignedTruckRemoteId, lineEndChar);
            message.AppendFormat("{0}{1}", _job.ContractedCarrierScac, lineEndChar);
            message.AppendFormat("{0}{1}", _job.LoadId, lineEndChar);
            message.AppendFormat("{0}{1}", _job.ShipperScac, lineEndChar);
            message.AppendFormat("{0}{1}", _job.TripId, lineEndChar);

            var endPoint = forEvent == WebHookEvent.OnWayPickup || forEvent == WebHookEvent.AtPickup || forEvent == WebHookEvent.PickupStop
                ? _job.Pickup
                : _job.Dropoff;

            message.AppendFormat("{0}{1}", endPoint.Destination.QuickCode, lineEndChar);
            message.AppendFormat("{0}{1}", _job.Id, lineEndChar);
            message.AppendFormat("{0}{1}", _job.JobNumber, lineEndChar);
            message.AppendFormat("{0}{1}", endPoint.ProofDocUrl, lineEndChar);
            message.AppendFormat("{0:yyyy-MM-dd HH:mm:ss}{1}", deviceTime, lineEndChar);

            var status = "Unknown";
            switch (forEvent)
            {
                case WebHookEvent.PickupStop:
                    status = "PickedUp";
                    break;
                case WebHookEvent.DropoffStop:
                    status = "Complete";
                    break;
                case WebHookEvent.OnWayPickup:
                    status = "OnWayToPickup";
                    break;
                case WebHookEvent.OnWayDeliver:
                    status = "OnWayToDelivery";
                    break;
                case WebHookEvent.AtPickup:
                    status = "AtPickup";
                    break;
                case WebHookEvent.AtDelivery:
                    status = "AtDelivery";
                    break;
            }

            message.AppendFormat("{0}{1}", status, lineEndChar);
            message.AppendFormat("{0:yyyy-MM-dd HH:mm:ss}{1}", endPoint.Eta, lineEndChar);

            // Only do signoff and vehicle deets on collection/delivery
            if (forEvent == WebHookEvent.PickupStop || forEvent == WebHookEvent.DropoffStop)
            {
                message.AppendFormat("{0}{1}", endPoint.Destination.Email, lineEndChar);
                message.AppendFormat("{0}{1}", ListToString(endPoint.Signoff.NotSignedReasons), lineEndChar);
                message.AppendFormat("{0}{1}", endPoint.Signoff.SignedBy, lineEndChar);

                foreach (var v in _job.Vehicles)
                {
                    message.AppendFormat("{0}{1}", v.Vin, lineEndChar);
                    message.AppendFormat("{0}{1}", v.MovementNumber, lineEndChar);
                    message.AppendFormat("{0}{1}", v.Status, lineEndChar);
                    message.AppendFormat("{0}{1}", v.NonCompletionReason, lineEndChar);

                    var damage = forEvent == WebHookEvent.PickupStop ? v.DamageAtPickup : v.DamageAtDropoff;

                    message.AppendFormat("{0}{1}", DamageToString(damage), lineEndChar);
                }
            }

            return message.ToString();
        }
 public async Task Handle(WebHookEvent webhookEvent)
 {
     await _registry.Handle(webhookEvent);
 }
 internal WorkItemEventContext InvokeCreateContextFromEvent(WebHookEvent eventData)
 {
     return(helper.CreateContextFromEvent(eventData));
 }
        public void Event_DeSerialize()
        {
            string events_json = @"
[{
""event"":""send"",
""ts"":1355340679,
""url"": ""http://clicked.me"",
""ip"": ""127.0.0.1"",
""user_agent"": ""outlook"",
""msg"":{
 ""ts"":1355340679,
 ""subject"":""Important Stuff"",
 ""email"":""*****@*****.**"",
 ""tags"":[""tag1"",""tag2"",""tag3""],
 ""metadata"":{ ""key1"":""val1"", ""key2"":""val2"" },
 ""opens"":[{""ts"":1355340679},{""ts"":1355412679}],
 ""state"":""sent"",
 ""clicks"":[{""ts"":1355773922,""url"":""http:\/\/www.GitHub.com""}],
 ""_id"":""fc8071b3575e44228d5dd7059349ba10"",
 ""sender"":""*****@*****.**"",
 ""template"":""validTemplate"",
 ""subaccount"":""validSubAccount""}
},{
""event"":""send"",
""ts"":1355340679,
""msg"":{
 ""ts"":1355340679,
 ""subject"":""Important Stuff"",
 ""email"":""*****@*****.**"",
 ""tags"":[],
 ""metadata"":{ },
 ""opens"":[],
 ""clicks"":[],
 ""state"":""sent"",
 ""_id"":""7572c81599d945cfb8dae3a8527f8232"",
 ""sender"":""*****@*****.**"",
 ""template"":""validTemplate"",
 ""subaccount"":""validSubAccount""}
}]";

            var eventTimeDate  = new DateTime(2012, 12, 12, 19, 31, 19);
            int numberOfEvents = 2;

            // Be sure we have two JSON object
            var zot = JSON.Parse <List <object> >(events_json);

            Assert.AreEqual(numberOfEvents, zot.Count);

            // Try parsing out WebHook events
            var events = JSON.Parse <List <WebHookEvent> >(events_json);

            Assert.AreEqual(numberOfEvents, events.Count);
            WebHookEvent e = events[0];

            Assert.AreEqual("http://clicked.me", e.Url);
            Assert.AreEqual("127.0.0.1", e.IP);
            Assert.AreEqual("outlook", e.UserAgent);

            Assert.AreEqual(WebHookEventType.Send, e.Event);
            Assert.AreEqual(eventTimeDate, e.TimeStamp);

            WebHookMessage message = e.Msg;


            Assert.AreEqual("validSubAccount", message.SubAccount);
            Assert.AreEqual("validTemplate", message.Template);
            Assert.AreEqual(WebHookMessageState.Sent, message.State);
            Assert.AreEqual(eventTimeDate, message.TimeStamp);
            Assert.AreEqual("Important Stuff", message.Subject);
            Assert.AreEqual("*****@*****.**", message.Sender);
            Assert.AreEqual("*****@*****.**", message.Email);
            Assert.AreEqual("fc8071b3575e44228d5dd7059349ba10", message.Id);

            Assert.AreEqual(3, message.Tags.Count);
            Assert.AreEqual("tag1", message.Tags[0]);
            Assert.AreEqual("tag2", message.Tags[1]);
            Assert.AreEqual("tag3", message.Tags[2]);

            Assert.AreEqual(2, message.Metadata.Count);
            Assert.AreEqual("key1", message.Metadata[0].Key);
            Assert.AreEqual("val1", message.Metadata[0].Value);
            Assert.AreEqual("key2", message.Metadata[1].Key);
            Assert.AreEqual("val2", message.Metadata[1].Value);

            Assert.AreEqual(2, message.Opens.Count);
            Assert.AreEqual(eventTimeDate, message.Opens[0].TimeStamp);
            Assert.AreEqual(1, message.Clicks.Count);
            Assert.AreEqual("http://www.GitHub.com", message.Clicks[0].Url);
        }
        public async Task <ActionResult> HandleGitHubHooks(WebHookEvent webhookEvent)
        {
            await _registry.Handle(webhookEvent);

            return(Ok());
        }
        public void HandleEventsWithDifferentResourceVersion_CheckIdentityConversion_Succeeds(WebHookEvent eventData)
        {
            var eventContext = azureFunctionHandler.InvokeCreateContextFromEvent(eventData);

            var workItem = eventContext.WorkItemPayload.WorkItem;

            Assert.IsType <IdentityRef>(workItem.Fields[CoreFieldRefNames.AssignedTo]);
            Assert.IsType <IdentityRef>(workItem.Fields[CoreFieldRefNames.ChangedBy]);
            Assert.IsType <IdentityRef>(workItem.Fields[CoreFieldRefNames.CreatedBy]);
        }
Exemple #32
0
        public async Task <IActionResult> GenerateJWTToken(WebHookEvent webHookEvent)
        {
            await _gitHubWebHookHandler.Handle(webHookEvent);

            return(Ok());
        }
        /// <summary>
        /// Sends the hooks for the specified hook event, of the specified schema
        /// </summary>
        /// <param name="id">Id of job to send hooks for</param>
        /// <param name="hookEvent">The hook event to send for</param>
        /// <param name="doForSchema">The hook schame to send for</param>
        public void SendJobHooks(int id, WebHookEvent hookEvent, string doForSchema)
        {
            var action = new Data.Action
            {
                Name = "sendhook",
                AssociatedId = hookEvent.ToString()
            };

            var resource = string.Format("Jobs/{0}/Action", id);
            var callParams = string.Format("sendhook_schema={0}", doForSchema);
            CallWithRetry(resource, "POST", false, action, callParams);
        }