예제 #1
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            var content = req.Content;

            string jsonContent = await content.ReadAsStringAsync();

            //log.Info($"Received D365 Event with payload: {jsonContent}");

            Microsoft.Xrm.Sdk.RemoteExecutionContext remoteExecutionContext = DeserializeJsonString <Microsoft.Xrm.Sdk.RemoteExecutionContext>(jsonContent);


            //read Plugin Message Name
            string messageName = remoteExecutionContext.MessageName;

            log.Info($"Message Name : {messageName}");
            //read execution depth of plugin
            Int32 depth = remoteExecutionContext.Depth;

            log.Info($"Depth : {depth}");
            //read BusinessUnitId
            Guid businessUnitid = remoteExecutionContext.BusinessUnitId;

            log.Info($"Business Unit ID  : {businessUnitid.ToString()}");
            //read Target Entity
            Microsoft.Xrm.Sdk.Entity targetEntity = (Microsoft.Xrm.Sdk.Entity)remoteExecutionContext.InputParameters["Target"];
            log.Info($"Target Entity Logical Name   : {targetEntity.LogicalName} - ID : {targetEntity.Id.ToString()}");

            //read attribute from Target Entity
            string dataPayload = targetEntity.GetAttributeValue <string>("fkh_eventdata");

            log.Info($"Data PayLoad : {dataPayload}");

            if (!string.IsNullOrEmpty(dataPayload))
            {
                log.Info($"Sending Event to EventGrid Topic...");
                callTopicAsync(log, dataPayload, targetEntity.ToEntityReference()).GetAwaiter().GetResult();
                log.Info($"Event successfully sent to EventGrid Topic...");
            }

            return(jsonContent == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + jsonContent));
        }
예제 #2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("AlertCreated Function Triggered Via Webhook.");

            // Get the remote execution context
            string jsonContext = await req.Content.ReadAsStringAsync();

            log.Info("Read context: " + jsonContext);

            jsonContext = FormatJson(jsonContext);
            log.Info("Formatted JSON Context string: " + jsonContext);

            Microsoft.Xrm.Sdk.RemoteExecutionContext context = DeserializeJsonString <Microsoft.Xrm.Sdk.RemoteExecutionContext>(jsonContext);

            //var context = await req.Content.ReadAsAsync<RemoteExecutionContext>();

            // Ensure this function was called on the create message of the scan_alert entity
            if (context.MessageName != "Create" && context.PrimaryEntityName != "scan_alert")
            {
                var err = "AlertCreated Context Execution Is Invalid";
                log.Error(err);
                return(req.CreateResponse(HttpStatusCode.BadRequest, err));
            }

            var alert = context.PostEntityImages.FirstOrDefault().Value.ToEntity <scan_alert>();

            if (alert == null)
            {
                var err = "Invalid Alert Post Entity Image";
                log.Error(err);
                return(req.CreateResponse(HttpStatusCode.BadRequest, err));
            }

            log.Info("Obtained Valid Context");
            log.Info("Processing Alert " + alert.Id.ToString());

            string orgUrl = ConfigurationManager.AppSettings["ScantegraOrgUrl"];
            Uri    orgUri = new Uri(orgUrl);

            log.Info(orgUri.ToString());
            //var proxyClient = new OrganizationWebProxyClient(orgUri, true);
            CrmServiceClient.AuthOverrideHook = new AuthHook();
            //CrmServiceClient test = new CrmServiceClient()
            CrmServiceClient crmSvc = new CrmServiceClient(orgUri, true);

            if (crmSvc.IsReady)
            {
                log.Info("Connected To Dynamics 365");
            }
            //crmSvc.OrganizationWebProxyClient.EnableProxyTypes();

            var scantegraContext = new ScantegraServiceContext(crmSvc.OrganizationWebProxyClient);


            // Pull the alert to get the full entity
            alert = scantegraContext.scan_alertSet.Where(a => a.Id == alert.Id).FirstOrDefault();


            // Pull the alert notification group from the rule
            var alertNotificationGroup = scantegraContext.scan_alertnotificationgroupSet.Where(ang => ang.Id == alert.scan_AlertNotificationGroup.Id).FirstOrDefault();

            log.Info("ANG ID " + alertNotificationGroup.Id.ToString());

            // Pull the alert notification actions from the intersection table
            var alertNotificationActionAssociations = scantegraContext.scan_alertgroupalertnotificationassociationSet.Where(a => a.scan_AlertNotificationGroup.Id == alertNotificationGroup.Id).ToList();

            // Iterate through the alert notification actions and process accordingly
            foreach (var association in alertNotificationActionAssociations)
            {
                var alertNotificationAction = scantegraContext.scan_alertnotificationactionSet.Where(aa => aa.Id == association.scan_AlertNotificationAction.Id).FirstOrDefault();
                log.Info("Processing action " + alertNotificationAction.Id.ToString());
                switch (alertNotificationAction.scan_NotificationActionType.Value)
                {
                case (int)scan_AlertNotificationActionType.PostToMicrosoftTeams:
                    var client = new TeamsClient(alertNotificationAction.scan_TeamsWebhookUrl);
                    var card   = new AlertCard()
                    {
                        Title = alert.scan_name,
                        Text  = $"{alert.FormattedValues["scan_alertseverity"]} - {alert.scan_name}"
                    };
                    client.PostMessage(card);
                    break;
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }