public static void SendAlert(JObject task, Logging logging)
        {
            TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();

            try
            {
                if ((JObject)task["Target"] != null)
                {
                    if ((JArray)task["Target"]["Alerts"] != null)
                    {
                        foreach (JObject Alert in (JArray)task["Target"]["Alerts"])
                        {
                            //Only Send out for Operator Level Alerts
                            //if (Alert["AlertCategory"].ToString() == "Task Specific Operator Alert")
                            {
                                //Get Plain Text and Email Subject from Template Files
                                System.Collections.Generic.Dictionary <string, string> Params = new System.Collections.Generic.Dictionary <string, string>();
                                Params.Add("Source.RelativePath", task["Source"]["RelativePath"].ToString());
                                Params.Add("Source.DataFileName", task["Source"]["DataFileName"].ToString());
                                Params.Add("Alert.EmailRecepientName", Alert["EmailRecepientName"].ToString());

                                string _plainTextContent = System.IO.File.ReadAllText(System.IO.Path.Combine(Shared._ApplicationBasePath, Shared._ApplicationOptions.LocalPaths.HTMLTemplateLocation, Alert["EmailTemplateFileName"].ToString() + ".txt"));
                                _plainTextContent = _plainTextContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                                string _htmlContent = System.IO.File.ReadAllText(System.IO.Path.Combine(Shared._ApplicationBasePath, Shared._ApplicationOptions.LocalPaths.HTMLTemplateLocation, Alert["EmailTemplateFileName"].ToString() + ".html"));
                                _htmlContent = _htmlContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                                var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
                                var client = new SendGridClient(apiKey);
                                var msg    = new SendGridMessage()
                                {
                                    From             = new EmailAddress(task["Target"]["SenderEmail"].ToString(), task["Target"]["SenderDescription"].ToString()),
                                    Subject          = Alert["EmailSubject"].ToString(),
                                    PlainTextContent = _plainTextContent,
                                    HtmlContent      = _htmlContent
                                };
                                msg.AddTo(new EmailAddress(Alert["EmailRecepient"].ToString(), Alert["EmailRecepientName"].ToString()));
                                var res = client.SendEmailAsync(msg).Result;
                            }
                        }
                    }

                    TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(task["TaskInstanceId"]), Guid.Parse(task["ExecutionUid"].ToString()), TaskMetaData.BaseTasks.TaskStatus.Complete, System.Guid.Empty, "");
                }
            }
            catch (Exception e)
            {
                logging.LogErrors(e);
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(task["TaskInstanceId"]), Guid.Parse(task["ExecutionUid"].ToString()), TaskMetaData.BaseTasks.TaskStatus.FailedNoRetry, System.Guid.Empty, "Failed to send email");
            }
        }
        public static JObject LogCore(HttpRequest req,
                                      Logging LogHelper)
        {
            short _FrameworkNumberOfRetries = Shared.GlobalConfigs.GetInt16Config("FrameworkNumberOfRetries");

            string  requestBody = new StreamReader(req.Body).ReadToEndAsync().Result;
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            dynamic _TaskInstanceId         = JObject.Parse(data.ToString())["TaskInstanceId"];
            dynamic _NumberOfRetries        = JObject.Parse(data.ToString())["NumberOfRetries"];
            dynamic _PostObjectExecutionUid = JObject.Parse(data.ToString())["ExecutionUid"];
            dynamic _AdfRunUid           = JObject.Parse(data.ToString())["RunId"];
            dynamic _LogTypeId           = JObject.Parse(data.ToString())["LogTypeId"]; //1 Error, 2 Warning, 3 Info, 4 Performance, 5 Debug
            dynamic _LogSource           = JObject.Parse(data.ToString())["LogSource"]; //ADF, AF
            dynamic _ActivityType        = JObject.Parse(data.ToString())["ActivityType"];
            dynamic _StartDateTimeOffSet = JObject.Parse(data.ToString())["StartDateTimeOffSet"];
            dynamic _Status  = JObject.Parse(data.ToString())["Status"]; //Started Failed Completed
            dynamic _Comment = JObject.Parse(data.ToString())["Comment"];

            _Comment = _Comment == null ? null : _Comment.ToString().Replace("'", "");
            dynamic _EndDateTimeOffSet = JObject.Parse(data.ToString())["EndDateTimeOffSet"];
            dynamic _RowsInserted      = JObject.Parse(data.ToString())["RowsInserted"];

            if (_TaskInstanceId != null)
            {
                LogHelper.DefaultActivityLogItem.TaskInstanceId = (long?)_TaskInstanceId;
            }
            if (_LogSource != null)
            {
                LogHelper.DefaultActivityLogItem.LogSource = (string)_LogSource;
            }
            if (_LogTypeId != null)
            {
                LogHelper.DefaultActivityLogItem.LogTypeId = (short?)_LogTypeId;
            }
            if (_StartDateTimeOffSet != null)
            {
                LogHelper.DefaultActivityLogItem.StartDateTimeOffset = (DateTimeOffset)_StartDateTimeOffSet;
            }
            if (_Status != null)
            {
                LogHelper.DefaultActivityLogItem.Status = (string)_Status;
            }
            if (_EndDateTimeOffSet != null)
            {
                LogHelper.DefaultActivityLogItem.EndDateTimeOffset = (DateTimeOffset)_EndDateTimeOffSet;
            }
            if (_PostObjectExecutionUid != null)
            {
                LogHelper.DefaultActivityLogItem.ExecutionUid = (Guid?)_PostObjectExecutionUid;
            }

            LogHelper.LogInformation(_Comment);

            TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();

            BaseTasks.TaskStatus TaskStatus = new BaseTasks.TaskStatus();


            if (_ActivityType == "Data-Movement-Master")
            {
                if (_Status == "Failed")
                {
                    //Todo Put Max Number of retries in DB at TaskMasterLevel -- This has now been done. Have left logic in function as stored procedure handles with all failed statuses.
                    _NumberOfRetries = (_NumberOfRetries == null) ? 0 : (int)_NumberOfRetries + 1;
                    TaskStatus       = ((_NumberOfRetries < _FrameworkNumberOfRetries) ? BaseTasks.TaskStatus.FailedRetry : BaseTasks.TaskStatus.FailedNoRetry);
                }
                else
                {
                    if (Enum.TryParse <BaseTasks.TaskStatus>(_Status.ToString(), out TaskStatus) == false)
                    {
                        string InvalidStatus = "TaskStatus Enum does not exist for: " + _Status.ToString();
                        LogHelper.LogErrors(new Exception("TaskStatus Enum does not exist for: " + _Status.ToString()));
                        _Comment   = _Comment.ToString() + "." + InvalidStatus;
                        TaskStatus = BaseTasks.TaskStatus.FailedNoRetry;
                    }
                }
                TMD.LogTaskInstanceCompletion((Int64)_TaskInstanceId, (System.Guid)_PostObjectExecutionUid, TaskStatus, (System.Guid)_AdfRunUid, (String)_Comment);
            }


            JObject Root = new JObject
            {
                ["Result"] = "Complete"
            };

            return(Root);
        }
Пример #3
0
        public static dynamic GetAzureStorageListingsCore(HttpRequest req, Logging logging)
        {
            string  requestBody     = new System.IO.StreamReader(req.Body).ReadToEndAsync().Result;
            dynamic taskInformation = JsonConvert.DeserializeObject(requestBody);
            string  _TaskInstanceId = taskInformation["TaskInstanceId"].ToString();
            string  _ExecutionUid   = taskInformation["ExecutionUid"].ToString();

            try
            {
                string _storageAccountName = taskInformation["Source"]["StorageAccountName"];
                //The name is actually the base url so we need to parse it to get the name only
                _storageAccountName = _storageAccountName.Split('.')[0].Replace("https://", "");
                string _storageAccountToken = taskInformation["Source"]["StorageAccountToken"];
                Int64  _SourceSystemId      = taskInformation["Source"]["SystemId"];

                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                using SqlConnection _con = TMD.GetSqlConnection();

                var res = _con.QueryWithRetry(string.Format("Select Max(PartitionKey) MaxPartitionKey from AzureStorageListing where SystemId = {0}", _SourceSystemId.ToString()));

                string MaxPartitionKey = DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd hh:mm");

                foreach (var r in res)
                {
                    if (r.MaxPartitionKey != null)
                    {
                        MaxPartitionKey = DateTime.Parse(r.MaxPartitionKey).AddMinutes(-1).ToString("yyyy-MM-dd hh:mm");
                    }
                }

                using (HttpClient SourceClient = new HttpClient())
                {
                    //Now use the SAS URI to connect rather than the MSI / Service Principal as AD Based Auth not yet avail for tables
                    var _storageCredentials  = new StorageCredentials(_storageAccountToken);
                    var SourceStorageAccount = new CloudStorageAccount(storageCredentials: _storageCredentials, accountName: _storageAccountName, endpointSuffix: "core.windows.net", useHttps: true);
                    var client = SourceStorageAccount.CreateCloudTableClient();

                    CloudTable table = client.GetTableReference("Filelist");

                    TableQuery <DynamicTableEntity> query = new TableQuery <DynamicTableEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThan, MaxPartitionKey.ToString()));

                    DataTable  dt = new DataTable();
                    DataColumn dc = new DataColumn();
                    dc.ColumnName = "PartitionKey";
                    dc.DataType   = typeof(string);
                    dt.Columns.Add(dc);
                    DataColumn dc1 = new DataColumn();
                    dc1.ColumnName = "RowKey";
                    dc1.DataType   = typeof(string);
                    dt.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn();
                    dc2.ColumnName = "SystemId";
                    dc2.DataType   = typeof(Int64);
                    dt.Columns.Add(dc2);
                    DataColumn dc3 = new DataColumn();
                    dc3.ColumnName = "FilePath";
                    dc3.DataType   = typeof(string);
                    dt.Columns.Add(dc3);

                    string Filelist = "";
                    TableContinuationToken token = null;
                    do
                    {
                        TableQuerySegment <DynamicTableEntity> resultSegment = table.ExecuteQuerySegmentedAsync(query, token).Result;
                        token = resultSegment.ContinuationToken;

                        //load into data table
                        foreach (var entity in resultSegment.Results)
                        {
                            DataRow dr = dt.NewRow();
                            dr["PartitionKey"] = entity.PartitionKey;
                            dr["RowKey"]       = entity.RowKey;
                            dr["SystemId"]     = _SourceSystemId;
                            dr["FilePath"]     = entity.Properties["FilePath"].StringValue;
                            dt.Rows.Add(dr);
                            Filelist += entity.Properties["FilePath"].StringValue + System.Environment.NewLine;
                        }
                    } while (token != null);


                    if (dt.Rows.Count > 0)
                    {
                        Table t = new Table();
                        t.Schema = "dbo";
                        string TableGuid = Guid.NewGuid().ToString();
                        t.Name = $"#AzureStorageListing{TableGuid}";

                        TMD.BulkInsert(dt, t, true, _con);
                        Dictionary <string, string> SqlParams = new Dictionary <string, string>
                        {
                            { "TempTable", t.QuotedSchemaAndName() },
                            { "SourceSystemId", _SourceSystemId.ToString() }
                        };

                        string MergeSQL = GenerateSQLStatementTemplates.GetSQL(Shared.GlobalConfigs.GetStringConfig("SQLTemplateLocation"), "MergeIntoAzureStorageListing", SqlParams);
                        _con.ExecuteWithRetry(MergeSQL, 120);
                        if ((JArray)taskInformation["Alerts"] != null)
                        {
                            foreach (JObject Alert in (JArray)taskInformation["Alerts"])
                            {
                                //Only Send out for Operator Level Alerts
                                if (Alert["AlertCategory"].ToString() == "Task Specific Operator Alert")
                                {
                                    AlertOperator(_SourceSystemId, Alert["AlertEmail"].ToString(), "", Filelist);
                                }
                            }
                        }
                    }

                    _con.Close();
                    _con.Dispose();
                    TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, Guid.Empty, "");
                }
            }

            catch (Exception e)
            {
                logging.LogErrors(e);
                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, Guid.Empty, "Failed when trying to Generate Sas URI and Send Email");

                JObject Root = new JObject
                {
                    ["Result"] = "Failed"
                };

                return(Root);
            }
            return(new { });
        }
        public static async Task <JObject> StartAndStopVMsCore(HttpRequest req, Logging logging)
        {
            string  requestBody     = await new StreamReader(req.Body).ReadToEndAsync();
            JObject data            = JsonConvert.DeserializeObject <JObject>(requestBody);
            string  _TaskInstanceId = data["TaskInstanceId"].ToString();
            string  _ExecutionUid   = data["ExecutionUid"].ToString();

            try
            {
                logging.LogInformation("StartAndStopVMs function processed a request.");
                string Subscription    = data["Target"]["SubscriptionUid"].ToString();
                string VmName          = data["Target"]["VMname"].ToString();
                string VmResourceGroup = data["Target"]["ResourceGroup"].ToString();
                string VmAction        = data["Target"]["Action"].ToString();

                Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureAuth = Microsoft.Azure.Management.Fluent.Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders).Authenticate(Shared.Azure.AzureSDK.GetAzureCreds(Shared._ApplicationOptions.UseMSI));
                IAzure azure = azureAuth.WithSubscription(Subscription);
                logging.LogInformation("Selected subscription: " + azure.SubscriptionId);
                IVirtualMachine vm = azure.VirtualMachines.GetByResourceGroup(VmResourceGroup, VmName);
                if (vm.PowerState == Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "start")
                {
                    logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString());
                    vm.StartAsync().Wait(5000);
                    logging.LogInformation("VM Start Initiated: " + vm.Name);
                }

                if (vm.PowerState != Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "stop")
                {
                    logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString());
                    vm.DeallocateAsync().Wait(5000);
                    logging.LogInformation("VM Stop Initiated: " + vm.Name);
                }

                JObject Root = new JObject {
                    ["Result"] = "Complete"
                };

                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                if (VmName != null)
                {
                    Root["Result"] = "Complete";
                }
                else
                {
                    Root["Result"] = "Please pass a name, resourcegroup and action to request body";
                    TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Task missing VMname, ResourceGroup or SubscriptionUid in Target element.");
                    return(Root);
                }
                //Update Task Instance

                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, System.Guid.Empty, "");

                return(Root);
            }
            catch (System.Exception TaskException)
            {
                logging.LogErrors(TaskException);
                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Failed when trying to start or stop VM");

                JObject Root = new JObject
                {
                    ["Result"] = "Failed"
                };

                return(Root);
            }
        }
        public static dynamic RunFrameworkTasksCore(HttpRequest req, Logging logging)
        {
            TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
            short TaskRunnerId       = System.Convert.ToInt16(req.Query["TaskRunnerId"]);

            try
            {
                TMD.ExecuteSql(string.Format("Insert into Execution values ('{0}', '{1}', '{2}')", logging.DefaultActivityLogItem.ExecutionUid, DateTimeOffset.Now.ToString("u"), DateTimeOffset.Now.AddYears(999).ToString("u")));

                //Fetch Top # tasks
                JArray _Tasks = AdsGoFast.TaskMetaData.TaskInstancesStatic.GetActive_ADFJSON((Guid)logging.DefaultActivityLogItem.ExecutionUid, TaskRunnerId, logging);

                var UtcCurDay = DateTime.UtcNow.ToString("yyyyMMdd");
                foreach (JObject _Task in _Tasks)
                {
                    long _TaskInstanceId = System.Convert.ToInt64(Shared.JsonHelpers.GetDynamicValueFromJSON(logging, "TaskInstanceId", _Task, null, true));
                    logging.DefaultActivityLogItem.TaskInstanceId = _TaskInstanceId;

                    //TO DO: Update TaskInstance yto UnTried if failed
                    string _pipelinename = _Task["DataFactory"]["ADFPipeline"].ToString();
                    System.Collections.Generic.Dictionary <string, object> _pipelineparams = new System.Collections.Generic.Dictionary <string, object>();

                    logging.LogInformation(string.Format("Executing ADF Pipeline for TaskInstanceId {0} ", _TaskInstanceId.ToString()));
                    //Check Task Type and execute appropriate ADF Pipeline
                    //Todo: Potentially extract switch into metadata

                    if (Shared._ApplicationOptions.TestingOptions.GenerateTaskObjectTestFiles)
                    {
                        string FileFullPath = Shared._ApplicationOptions.TestingOptions.TaskObjectTestFileLocation + /*UtcCurDay +*/ "/";
                        // Determine whether the directory exists.
                        if (!System.IO.Directory.Exists(FileFullPath))
                        {
                            // Try to create the directory.
                            System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(FileFullPath);
                        }

                        FileFullPath = FileFullPath + _Task["TaskType"].ToString() + "_" + _pipelinename.ToString() + "_" + _Task["TaskMasterId"].ToString() + ".json";
                        System.IO.File.WriteAllText(FileFullPath, _Task.ToString());
                        TMD.LogTaskInstanceCompletion(_TaskInstanceId, (Guid)logging.DefaultActivityLogItem.ExecutionUid, TaskMetaData.BaseTasks.TaskStatus.Complete, System.Guid.Empty, "Complete");
                    }
                    else
                    {
                        try
                        {
                            if (_Task["TaskExecutionType"].ToString() == "ADF")
                            {
                                _pipelinename = "Master";
                                _pipelineparams.Add("TaskObject", _Task);

                                if (_pipelinename != "")
                                {
                                    JObject _pipelineresult = ExecutePipeline.ExecutePipelineMethod(_Task["DataFactory"]["SubscriptionId"].ToString(), _Task["DataFactory"]["ResourceGroup"].ToString(), _Task["DataFactory"]["Name"].ToString(), _pipelinename, _pipelineparams, logging);
                                    logging.DefaultActivityLogItem.AdfRunUid = Guid.Parse(_pipelineresult["RunId"].ToString());
                                    TMD.GetSqlConnection().Execute(string.Format(@"
                                            INSERT INTO TaskInstanceExecution (
	                                                        [ExecutionUid]
	                                                        ,[TaskInstanceId]
	                                                        ,[DatafactorySubscriptionUid]
	                                                        ,[DatafactoryResourceGroup]
	                                                        ,[DatafactoryName]
	                                                        ,[PipelineName]
	                                                        ,[AdfRunUid]
	                                                        ,[StartDateTime]
	                                                        ,[Status]
	                                                        ,[Comment]
	                                                        )
                                                        VALUES (
	                                                            @ExecutionUid
	                                                        ,@TaskInstanceId
	                                                        ,@DatafactorySubscriptionUid
	                                                        ,@DatafactoryResourceGroup
	                                                        ,@DatafactoryName
	                                                        ,@PipelineName
	                                                        ,@AdfRunUid
	                                                        ,@StartDateTime
	                                                        ,@Status
	                                                        ,@Comment
	                                        )"    ), new
                                    {
                                        ExecutionUid               = logging.DefaultActivityLogItem.ExecutionUid.ToString(),
                                        TaskInstanceId             = System.Convert.ToInt64(_Task["TaskInstanceId"]),
                                        DatafactorySubscriptionUid = _Task["DataFactory"]["SubscriptionId"].ToString(),
                                        DatafactoryResourceGroup   = _Task["DataFactory"]["ResourceGroup"].ToString(),
                                        DatafactoryName            = _Task["DataFactory"]["Name"].ToString(),
                                        PipelineName               = _pipelineresult["PipelineName"].ToString(),
                                        AdfRunUid     = Guid.Parse(_pipelineresult["RunId"].ToString()),
                                        StartDateTime = DateTimeOffset.UtcNow,
                                        Status        = _pipelineresult["Status"].ToString(),
                                        Comment       = ""
                                    });
                                }
                                //To Do // Batch to make less "chatty"
                                //To Do // Upgrade to stored procedure call
                            }

                            else if (_Task["TaskExecutionType"].ToString() == "AF")
                            {
                                //The "AF" branch is for calling Azure Function Based Tasks that do not require ADF. Calls are made async (just like the ADF calls) and calls are made using "AsyncHttp" requests even though at present the "AF" based Tasks reside in the same function app. This is to "future proof" as it is expected that these AF based tasks will be moved out to a separate function app in the future.
                                switch (_pipelinename)
                                {
                                case "AZ-Storage-SAS-Uri-SMTP-Email":
                                    using (var client = new System.Net.Http.HttpClient())
                                    {
                                        //Lets get an access token based on MSI or Service Principal
                                        var secureFunctionAPIURL = string.Format("{0}/api/GetSASUriSendEmailHttpTrigger", Shared._ApplicationOptions.ServiceConnections.CoreFunctionsURL);
                                        var accessToken          = Shared._AzureAuthenticationCredentialProvider.GetAzureRestApiToken(secureFunctionAPIURL);

                                        using HttpRequestMessage httpRequestMessage = new HttpRequestMessage
                                              {
                                                  Method     = HttpMethod.Post,
                                                  RequestUri = new Uri(secureFunctionAPIURL),
                                                  Content    = new StringContent(_Task.ToString(), System.Text.Encoding.UTF8, "application/json"),
                                                  Headers    = { { System.Net.HttpRequestHeader.Authorization.ToString(), "Bearer " + accessToken } }
                                              };


                                        //Todo Add some error handling in case function cannot be reached. Note Wait time is there to provide sufficient time to complete post before the HttpClient is disposed.
                                        var HttpTask = client.SendAsync(httpRequestMessage).Wait(3000);
                                    }
                                    break;

                                case "AZ-Storage-Cache-File-List":
                                    using (var client = new System.Net.Http.HttpClient())
                                    {
                                        //Lets get an access token based on MSI or Service Principal
                                        var secureFunctionAPIURL = string.Format("{0}/api/AZStorageCacheFileListHttpTrigger", Shared._ApplicationOptions.ServiceConnections.CoreFunctionsURL);
                                        var accessToken          = Shared._AzureAuthenticationCredentialProvider.GetAzureRestApiToken(secureFunctionAPIURL);

                                        using HttpRequestMessage httpRequestMessage = new HttpRequestMessage
                                              {
                                                  Method     = HttpMethod.Post,
                                                  RequestUri = new Uri(secureFunctionAPIURL),
                                                  Content    = new StringContent(_Task.ToString(), System.Text.Encoding.UTF8, "application/json"),
                                                  Headers    = { { System.Net.HttpRequestHeader.Authorization.ToString(), "Bearer " + accessToken } }
                                              };


                                        //Todo Add some error handling in case function cannot be reached. Note Wait time is there to provide sufficient time to complete post before the HttpClient is disposed.
                                        var HttpTask = client.SendAsync(httpRequestMessage).Wait(3000);
                                    }
                                    break;

                                case "StartAndStopVMs":
                                    using (var client = new System.Net.Http.HttpClient())
                                    {
                                        //Lets get an access token based on MSI or Service Principal
                                        var accessToken = GetSecureFunctionToken(_pipelinename);

                                        using HttpRequestMessage httpRequestMessage = new HttpRequestMessage
                                              {
                                                  Method     = HttpMethod.Post,
                                                  RequestUri = new Uri(GetSecureFunctionURI(_pipelinename)),
                                                  Content    = new StringContent(_Task.ToString(), System.Text.Encoding.UTF8, "application/json"),
                                                  Headers    = { { System.Net.HttpRequestHeader.Authorization.ToString(), "Bearer " + accessToken } }
                                              };

                                        //Todo Add some error handling in case function cannot be reached. Note Wait time is there to provide sufficient time to complete post before the HttpClient is disposed.
                                        var HttpTask = client.SendAsync(httpRequestMessage).Wait(3000);
                                    }
                                    break;

                                case "Cache-File-List-To-Email-Alert":
                                    using (var client = new System.Net.Http.HttpClient())
                                    {
                                        SendAlert(_Task, logging);
                                    }
                                    break;

                                default:
                                    var msg = $"Could not find execution path for Task Type of {_pipelinename} and Execution Type of {_Task["TaskExecutionType"].ToString()}";
                                    logging.LogErrors(new Exception(msg));
                                    TMD.LogTaskInstanceCompletion((Int64)_TaskInstanceId, (System.Guid)logging.DefaultActivityLogItem.ExecutionUid, BaseTasks.TaskStatus.FailedNoRetry, Guid.Empty, (String)msg);
                                    break;
                                }
                                //To Do // Batch to make less "chatty"
                                //To Do // Upgrade to stored procedure call
                            }
                        }
                        catch (Exception TaskException)
                        {
                            logging.LogErrors(TaskException);
                            TMD.LogTaskInstanceCompletion((Int64)_TaskInstanceId, (System.Guid)logging.DefaultActivityLogItem.ExecutionUid, BaseTasks.TaskStatus.FailedNoRetry, Guid.Empty, (String)"Runner failed to execute task.");
                        }
                    }
                }
            }
            catch (Exception RunnerException)
            {
                //Set Runner back to Idle
                TMD.ExecuteSql(string.Format("exec [dbo].[UpdFrameworkTaskRunner] {0}", TaskRunnerId));
                logging.LogErrors(RunnerException);
                //log and re-throw the error
                throw RunnerException;
            }
            //Set Runner back to Idle
            TMD.ExecuteSql(string.Format("exec [dbo].[UpdFrameworkTaskRunner] {0}", TaskRunnerId));

            //Return success
            JObject Root = new JObject
            {
                ["Succeeded"] = true
            };

            return(Root);
        }
        public static async Task <JObject> SendEmailSASUri(HttpRequest req, Logging logging)
        {
            string  requestBody     = new StreamReader(req.Body).ReadToEndAsync().Result;
            dynamic taskInformation = JsonConvert.DeserializeObject(requestBody);

            string _TaskInstanceId = taskInformation["TaskInstanceId"].ToString();
            string _ExecutionUid   = taskInformation["ExecutionUid"].ToString();

            try
            {
                //Get SAS URI
                string _blobStorageAccountName   = taskInformation["Source"]["StorageAccountName"].ToString();
                string _blobStorageContainerName = taskInformation["Source"]["StorageAccountContainer"].ToString();
                string _blobStorageFolderPath    = taskInformation["Source"]["RelativePath"].ToString();
                string _dataFileName             = taskInformation["Source"]["DataFileName"].ToString();
                int    _accessDuration           = (int)taskInformation["Source"]["SasURIDaysValid"];
                string _targetSystemUidInPHI     = taskInformation["Source"]["TargetSystemUidInPHI"];
                string _FileUploaderWebAppURL    = taskInformation["Source"]["FileUploaderWebAppURL"];

                string SASUri = Storage.CreateSASToken(_blobStorageAccountName, _blobStorageContainerName, _blobStorageFolderPath, _dataFileName, _accessDuration);

                //Send Email
                string _emailRecipient        = taskInformation["Target"]["EmailRecipient"].ToString();
                string _emailRecipientName    = taskInformation["Target"]["EmailRecipientName"].ToString();
                string _emailTemplateFileName = taskInformation["Target"]["EmailTemplateFileName"].ToString();
                string _senderEmail           = taskInformation["Target"]["SenderEmail"].ToString();
                string _senderDescription     = taskInformation["Target"]["SenderDescription"].ToString();
                string _subject = taskInformation["Target"]["EmailSubject"].ToString();

                //Get Plain Text and Email Subject from Template Files
                Dictionary <string, string> Params = new Dictionary <string, string>
                {
                    { "NAME", _emailRecipientName },
                    { "SASTOKEN", SASUri },
                    { "FileUploaderUrl", _FileUploaderWebAppURL },
                    { "TargetSystemUidInPHI", _targetSystemUidInPHI },
                };
                string _plainTextContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".txt");
                _plainTextContent = _plainTextContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                string _htmlContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".html");
                _htmlContent = _htmlContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
                var client = new SendGridClient(new SendGridClientOptions {
                    ApiKey = apiKey, HttpErrorAsException = true
                });
                var msg = new SendGridMessage()
                {
                    From             = new EmailAddress(_senderEmail, _senderDescription),
                    Subject          = _subject,
                    PlainTextContent = _plainTextContent,
                    HtmlContent      = _htmlContent
                };
                msg.AddTo(new EmailAddress(_emailRecipient, _emailRecipientName));
                try
                {
                    var response = await client.SendEmailAsync(msg).ConfigureAwait(false);

                    logging.LogInformation($"SendGrid Response StatusCode - {response.StatusCode}");
                }
                catch (Exception ex)
                {
                    SendGridErrorResponse errorResponse = JsonConvert.DeserializeObject <SendGridErrorResponse>(ex.Message);
                    logging.LogInformation($"Error Message - {ex.Message}");
                    throw new Exception("Could not send email");
                }

                //Update Task Instace

                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, Guid.Empty, "");

                JObject Root = new JObject
                {
                    ["Result"] = "Complete"
                };

                return(Root);
            }
            catch (Exception TaskException)
            {
                logging.LogErrors(TaskException);
                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, Guid.Empty, "Failed when trying to Generate Sas URI and Send Email");

                JObject Root = new JObject
                {
                    ["Result"] = "Failed"
                };

                return(Root);
            }
        }