/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var query = GetAttributeValue(action, "SQLQuery"); var parametersValue = GetAttributeValue(action, "Parameters"); var parameterList = new Field.Types.KeyValueListFieldType().GetValuesFromString(null, parametersValue, null, false); var mergeFields = GetMergeFields(action); query = query.ResolveMergeFields(mergeFields); var parameters = new Dictionary <string, object>(); foreach (var p in parameterList) { var value = p.Value != null?p.Value.ToString().ResolveMergeFields(mergeFields) : null; parameters.AddOrReplace(p.Key, value); } try { object sqlResult = DbService.ExecuteScaler(query, System.Data.CommandType.Text, parameters); action.AddLogEntry("SQL query has been run"); if (sqlResult != null) { string resultValue = sqlResult.ToString(); var attribute = SetWorkflowAttributeValue(action, "ResultAttribute", resultValue); if (attribute != null) { action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, resultValue)); } } return(true); } catch (Exception ex) { action.AddLogEntry(ex.Message, true); if (!GetAttributeValue(action, "ContinueOnError").AsBoolean()) { errorMessages.Add(ex.Message); return(false); } else { return(true); } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var mergeFields = GetMergeFields(action); string method = GetAttributeValue(action, METHOD); string url = GetAttributeValue(action, URL).ResolveMergeFields(mergeFields); var parametersValue = GetAttributeValue(action, PARAMETERS); var parameterList = new Field.Types.KeyValueListFieldType().GetValuesFromString(null, parametersValue, null, false); var parameters = new Dictionary <string, object>(); foreach (var p in parameterList) { var value = p.Value != null?p.Value.ToString().ResolveMergeFields(mergeFields) : null; parameters.AddOrReplace(p.Key, value); } var headersValue = GetAttributeValue(action, HEADERS); var headerList = new Field.Types.KeyValueListFieldType().GetValuesFromString(null, headersValue, null, false); var headers = new Dictionary <string, object>(); foreach (var p in headerList) { var value = p.Value != null?p.Value.ToString().ResolveMergeFields(mergeFields) : null; headers.AddOrReplace(p.Key, value); } string basicAuthUserName = GetAttributeValue(action, BASIC_AUTH_USERNAME); string basicAuthPassword = GetAttributeValue(action, BASIC_AUTH_PASSWORD); string body = GetAttributeValue(action, BODY).ResolveMergeFields(mergeFields); var requestContentType = this.GetAttributeValue(action, REQUEST_CONTENT_TYPE).ConvertToEnum <RequestContentType>(RequestContentType.JSON); var responseContentType = this.GetAttributeValue(action, RESPONSE_CONTENT_TYPE).ConvertToEnum <ResponseContentType>(ResponseContentType.JSON); if (!string.IsNullOrWhiteSpace(url)) { var client = new RestClient(url); var request = new RestRequest(method.ToUpper().ConvertToEnum <Method>(Method.GET)); client.Timeout = 12000; // handle basic auth if (!string.IsNullOrEmpty(basicAuthUserName) && !string.IsNullOrEmpty(basicAuthPassword)) { client.Authenticator = new HttpBasicAuthenticator(basicAuthUserName, basicAuthPassword); } foreach (var parameter in parameters) { request.AddParameter(parameter.Key, parameter.Value); } // add headers foreach (var header in headers) { request.AddHeader(header.Key, header.Value.ToString()); } if (!string.IsNullOrWhiteSpace(body)) { if (requestContentType == RequestContentType.JSON) { request.RequestFormat = DataFormat.Json; request.AddParameter("application/json", body, ParameterType.RequestBody); } else { request.RequestFormat = DataFormat.Xml; request.AddParameter("application/xml", body, ParameterType.RequestBody); } } switch (responseContentType) { case ResponseContentType.JSON: { request.AddHeader("Accept", "application/json"); } break; case ResponseContentType.XML: { request.AddHeader("Accept", "application/xml"); } break; } IRestResponse response = client.Execute(request); var responseString = response.Content; var attribute = SetWorkflowAttributeValue(action, RESPONSE_ATTRIBUTE, responseString); if (attribute != null) { action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, responseString)); } } return(true); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { var jobDataMap = context.JobDetail.JobDataMap; var contentChannelGuid = jobDataMap.GetString(AttributeKey.ContentChannel).AsGuidOrNull(); if (!contentChannelGuid.HasValue) { context.Result = $"The Service Job {jobDataMap.GetString( "Name" )} did not specify a valid Content Channel"; ExceptionLogService.LogException(context.Result.ToString()); return; } var errors = new List <string>(); List <Exception> exceptions = new List <Exception>(); var rockContext = new RockContext(); var contentChannelId = new ContentChannelService(rockContext).GetId(contentChannelGuid.Value); var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(i => i.ContentChannelId == contentChannelId).ToList(); var attributeLinks = new Field.Types.KeyValueListFieldType().GetValuesFromString(null, jobDataMap.GetString(AttributeKey.AttributeLinks), null, false); var itemMergeFields = new Dictionary <string, object>(Lava.LavaHelper.GetCommonMergeFields(null)); var jobResultStringBuilder = new StringBuilder(); var totalItems = contentChannelItems.Count(); var updatedItems = 0; var updatedAttributes = 0; var itemId = 0; foreach (var contentChannelItem in contentChannelItems) { itemMergeFields.AddOrReplace("ContentChannelItem", contentChannelItem); foreach (var attributeLink in attributeLinks) { try { // merge the template lava and put the rendered text into the target key contentChannelItem.LoadAttributes(); var lavaTemplate = contentChannelItem.GetAttributeValue(attributeLink.Key); var lavaOutput = contentChannelItem.GetAttributeValue(attributeLink.Value.ToString()); if (lavaTemplate == null || lavaOutput == null) { var errorMessage = $"Template with key '{attributeLink.Key}' or target with key '{attributeLink.Value}' not found."; errors.Add(errorMessage); continue; } var mergedContent = lavaTemplate.ResolveMergeFields(itemMergeFields); if (lavaOutput.Equals(mergedContent)) { continue; } contentChannelItem.SetAttributeValue(attributeLink.Value.ToString(), mergedContent); updatedAttributes++; if (contentChannelItem.Id != itemId) { itemId = contentChannelItem.Id; updatedItems++; } } catch (Exception ex) { exceptions.Add(ex); jobResultStringBuilder.AppendLine($"<i class='fa fa-circle text-danger'></i> error(s) occurred. See exception log for details."); ExceptionLogService.LogException(ex); continue; } contentChannelItem.SaveAttributeValues(rockContext); } } jobResultStringBuilder.AppendLine($"Updated {updatedAttributes} ContentChannelItem {"attribute".PluralizeIf( updatedAttributes != 1 )} in {updatedItems} of {totalItems} ContentChannelItems"); foreach (var error in errors) { jobResultStringBuilder.AppendLine($"<i class='fa fa-circle text-warning'></i> {error}"); } context.Result = jobResultStringBuilder.ToString(); rockContext.SaveChanges(); if (exceptions.Any() || errors.Any()) { var exceptionList = new AggregateException("One or more exceptions occurred in ContentChannelItemSelfUpdate.", exceptions); throw new RockJobWarningException("ContentChannelItemSelfUpdate completed with warnings", exceptionList); } }