예제 #1
0
        public virtual APIResult <CardPointsCampaign> AddPoints(string numPoints, string campaignId, string customerId)
        {
            APIResult <CardPointsCampaign> res = new APIResult <CardPointsCampaign>();
            FidelityCustomer customer;

            if (customerId == null)
            {
                customer = GetCustomerFromAuthenticatedUser();
            }
            else
            {
                customer = GetCustomerFromIdOrEmail(customerId);
            }

            FidelityCampaign campaign = new FidelityCampaign();

            campaign.Id = campaignId;
            if (customer != null)
            {
                APIResult <bool> resAdd = _sendService.SendAddPoints(settingsPart, customer, campaign, numPoints);
                if (!resAdd.success)
                {
                    res = new APIResult <CardPointsCampaign> {
                        success = false, data = null, message = resAdd.message
                    };
                }
                else
                {
                    APIResult <FidelityCustomer> resCust = _sendService.SendCustomerDetails(settingsPart, customer);
                    if (!resCust.success)
                    {
                        res = new APIResult <CardPointsCampaign> {
                            success = false, data = null, message = resCust.message
                        };
                    }
                    else
                    {
                        res.success = resAdd.success;
                        res.message = resAdd.message;
                        CardPointsCampaign data = new CardPointsCampaign()
                        {
                            idCampaign = campaignId,
                            idCustomer = customer.Id,
                            points     = resCust.data.PointsInCampaign[campaignId]
                        };
                        res.data = data;
                    }
                }
            }
            else
            {
                res = new APIResult <CardPointsCampaign> {
                    success = false, data = null, message = "The user is not configured to use " + GetProviderName()
                };
            }
            _workflowManager.TriggerEvent("AddFidelityPoints", null, () => new Dictionary <string, object> {
                { "result", res }
            });
            return(res);
        }
        public ActionResult Add(int id, int quantity = 1, bool isAjaxRequest = false)
        {
            // Manually parse product attributes because of a breaking change
            // in MVC 5 dictionary model binding
            var form              = HttpContext.Request.Form;
            var files             = HttpContext.Request.Files;
            var productattributes = form.AllKeys
                                    .Where(key => key.StartsWith(AttributePrefix))
                                    .ToDictionary(
                key => int.Parse(key.Substring(AttributePrefix.Length)),
                key => {
                var extensionProvider = _attributeExtensionProviders.SingleOrDefault(e => e.Name == form[ExtensionPrefix + key + ".provider"]);
                Dictionary <string, string> extensionFormValues = null;
                if (extensionProvider != null)
                {
                    extensionFormValues = form.AllKeys.Where(k => k.StartsWith(ExtensionPrefix + key + "."))
                                          .ToDictionary(
                        k => k.Substring((ExtensionPrefix + key + ".").Length),
                        k => form[k]);
                    return(new ProductAttributeValueExtended {
                        Value = form[key],
                        ExtendedValue = extensionProvider.Serialize(form[ExtensionPrefix + key], extensionFormValues, files),
                        ExtensionProvider = extensionProvider.Name
                    });
                }
                return(new ProductAttributeValueExtended {
                    Value = form[key],
                    ExtendedValue = null,
                    ExtensionProvider = null
                });
            });

            // Retrieve minimum order quantity
            var productPart = _contentManager.Get <ProductPart>(id);

            if (productPart != null)
            {
                if (quantity < productPart.MinimumOrderQuantity)
                {
                    quantity = productPart.MinimumOrderQuantity;
                }
            }

            _shoppingCart.Add(id, quantity, productattributes);

            _workflowManager.TriggerEvent("CartUpdated",
                                          _wca.GetContext().CurrentSite,
                                          () => new Dictionary <string, object> {
                { "Cart", _shoppingCart }
            });

            // Test isAjaxRequest too because iframe posts won't return true for Request.IsAjaxRequest()
            if (Request.IsAjaxRequest() || isAjaxRequest)
            {
                return(new ShapePartialResult(
                           this,
                           BuildCartShape(true, _shoppingCart.Country, _shoppingCart.ZipCode)));
            }
            return(RedirectToAction("Index"));
        }
예제 #3
0
        public WorkflowContentHandler(IWorkflowManager workflowManager) {

            OnPublished<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentPublished",
                    context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));

            OnRemoving<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentRemoved",
                    context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));

            OnVersioned<ContentPart>(
                (context, part1, part2) =>
                    workflowManager.TriggerEvent("ContentVersioned",
                    context.BuildingContentItem,
                    () => new Dictionary<string, object> { { "Content", context.BuildingContentItem } }));

            OnCreated<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentCreated", context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));

            OnUpdated<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentUpdated", context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));
        }
        public void AccessDenied(global::Orchard.Security.IUser user)
        {
            var content = user.ContentItem;

            _workflowManager.TriggerEvent("OnUserEvent", content, () => new Dictionary <string, object> {
                { "Content", content }, { "Action", "AccessDenied" }
            });
        }
예제 #5
0
 public void Finalized()
 {
     _workflowManager.TriggerEvent("CartFinalized",
                                   _wca.GetContext().CurrentSite,
                                   () => new Dictionary <string, object> {
         { "Cart", _shoppingCart }
     });
 }
        public void OnSuccess(int paymentId, int contentItemId)
        {
            var ci      = _orchardServices.ContentManager.Get(contentItemId);
            var payment = _repository.Get(paymentId);

            _workflowManager.TriggerEvent("PaymentEnded", ci, () => new Dictionary <string, object> {
                { "Payment", payment }
            });
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            LocalizedString messageout = null;
            string          result     = "";
            HttpVerbs       verb       = HttpVerbs.Get;
            var             model      = new APICallEdit {
                Url              = activityContext.GetState <string>("Url"),
                RequestType      = activityContext.GetState <string>("RequestType"),
                HttpVerb         = activityContext.GetState <string>("HttpVerb"),
                Payload          = activityContext.GetState <string>("Payload").ToString(),
                RequiredPolicies = activityContext.GetState <string>("RequiredPolicies")
            };

            Enum.TryParse <HttpVerbs>(model.HttpVerb.ToString(), true, out verb);
            JObject payload = JObject.Parse("{" + model.Payload + "}");

            // In case in the url we kept the "default" fake tokens {list-id} and {member-id}
            // we can try to replace them by checking the site settings and the payload
            var urlApiCall = _service.TryReplaceTokenInUrl(model.Url, payload);

            // updated model with replaced parameters at the url
            model.Url = urlApiCall;
            var done = _apiservice.TryApiCall(verb, urlApiCall, payload, ref result);

            // this trigger is only valid for the member's put and delete
            if (verb == HttpVerbs.Put && model.RequestType.ToLower() == RequestTypes.Member.ToString().ToLower())
            {
                _workflowManager.TriggerEvent("UserCreatedOnMailchimp",
                                              null,
                                              () => new Dictionary <string, object> {
                    { "Syncronized", done },
                    { "APICallEdit", model },
                    { "Email", payload["email_address"] == null ? "" : payload["email_address"].ToString() }
                });
            }
            else if (verb == HttpVerbs.Delete && model.RequestType.ToLower() == RequestTypes.Member.ToString().ToLower())
            {
                _workflowManager.TriggerEvent("UserDeletedOnMailchimp",
                                              null,
                                              () => new Dictionary <string, object> {
                    { "Syncronized", done },
                    { "APICallEdit", model },
                    { "Email", payload["email_address"] == null ? "" : payload["email_address"].ToString() }
                });
            }
            if (done)
            {
                messageout = T("Succeeded");
            }
            else
            {
                messageout = T("Failed");
            }
            yield return(messageout);
        }
 public void Created(CreatedOpenAuthUserContext context)
 {
     _workflowManager.TriggerEvent("OpenAuthUserCreated",
                                   context.User.ContentItem,
                                   () => new Dictionary <string, object> {
         { "User", context.User },
         { "ProviderName", context.ProviderName },
         { "ProviderUserId", context.ProviderUserId },
         { "ExtraData", context.ExtraData }
     });
 }
 protected override void Anonymized(AnonymizeContentContext context)
 {
     // this check returns true if the item has a GDPRPart. It should not be required
     // but it's there for safety
     if (context.ShouldProcess(context.GDPRPart))
     {
         _workflowManager.TriggerEvent("ContentAnonymized", context.ContentItem,
                                       () => new Dictionary <string, object> {
             { "Content", context.ContentItem },
             { "GDPRContentContext", context }
         });
     }
 }
예제 #10
0
        public WorkflowContentHandler(IWorkflowManager workflowManager)
        {
            OnPublished <ContentPart>(
                (context, part) =>
                workflowManager.TriggerEvent("ContentPublished",
                                             context.ContentItem,
                                             () => new Dictionary <string, object> {
                { "Content", context.ContentItem }
            }));

            OnRemoving <ContentPart>(
                (context, part) =>
                workflowManager.TriggerEvent("ContentRemoved",
                                             context.ContentItem,
                                             () => new Dictionary <string, object> {
                { "Content", context.ContentItem }
            }));

            OnVersioned <ContentPart>(
                (context, part1, part2) =>
                workflowManager.TriggerEvent("ContentVersioned",
                                             context.BuildingContentItem,
                                             () => new Dictionary <string, object> {
                { "Content", context.BuildingContentItem }
            }));

            OnCreated <ContentPart>(
                (context, part) =>
                workflowManager.TriggerEvent("ContentCreated", context.ContentItem,
                                             () => new Dictionary <string, object> {
                { "Content", context.ContentItem }
            }));

            OnUpdated <ContentPart>(
                (context, part) => {
                if (context.ContentItemRecord == null)
                {
                    return;
                }

                workflowManager.TriggerEvent(
                    "ContentUpdated",
                    context.ContentItem,
                    () => new Dictionary <string, object> {
                    { "Content", context.ContentItem }
                }
                    );
            });
        }
        private void RaiseWorkflow(SVNServerRecord hostRecord, SvnLogEventArgs log)
        {
            var contentManager    = this.orchardServices.ContentManager;
            var svnLogContentItem = contentManager.New(SVNLogPart.ContentItemTypeName);
            var svnLogPart        = svnLogContentItem.As <SVNLogPart>();


            svnLogPart.LogMessage = log.LogMessage;
            svnLogPart.Author     = log.Author;
            svnLogPart.Revision   = log.Revision;
            svnLogPart.Time       = log.Time;
            svnLogPart.LogOrigin  = log.LogOrigin.AbsolutePath;

            contentManager.Create(svnLogContentItem);
            contentManager.Publish(svnLogContentItem);

            workflowManager.TriggerEvent(
                SVNLogReceivedActivity.ActivityName,
                svnLogContentItem,
                () => new Dictionary <string, object> {
                { "Content", svnLogContentItem }
            });

            hostRecord.LastRevision = log.Revision;
            this.svnServerRepository.Flush();
        }
        public HttpResponseMessage Get()
        {
            var tokens = new Dictionary <string, object>();
            var site   = _contentManager.Get(1);

            tokens.Add("Content", site);
            // add content of query string in tokens of the workflow
            var queryString = Request.GetQueryNameValuePairs();

            foreach (var item in queryString)
            {
                // add only if token does not exist yet, so "Content" cannot be overwritten
                if (tokens.ContainsKey(item.Key) == false)
                {
                    tokens.Add(item.Key, item.Value);
                }
            }
            _workflowManager.TriggerEvent("WebTrackingEvent", site, () => tokens);
            // return an invisible image
            var result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            result.Headers.Clear();
            var content = new ByteArrayContent(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Modules/Laser.Orchard.TemplateManagement/Styles/1x1.png")));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
            result.Content = content;
            return(result);
        }
        private void RaiseWorkflow(GITServerBranchRecord hostRecord, Commit log)
        {
            var contentManager    = this.orchardServices.ContentManager;
            var gitLogContentItem = contentManager.New(GITCommitPart.ContentItemTypeName);
            var gitLogPart        = gitLogContentItem.As <GITCommitPart>();


            gitLogPart.LogMessage = log.Message;
            gitLogPart.Author     = log.Author.Name;
            gitLogPart.Sha        = log.Sha;
            gitLogPart.Time       = log.Author.When.DateTime;

            contentManager.Create(gitLogContentItem);
            contentManager.Publish(gitLogContentItem);

            workflowManager.TriggerEvent(
                GITCommitReceivedActivity.ActivityName,
                gitLogContentItem,
                () => new Dictionary <string, object> {
                { "Content", gitLogContentItem }
            });

            hostRecord.Sha = log.Sha;
            this.svnServerRepository.Flush();
        }
예제 #14
0
        protected override DriverResult Editor(ContentPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var httpContext = _httpContextAccessor.Current();
            var name        = httpContext.Request.Form["submit.Save"];

            if (!string.IsNullOrEmpty(name) && name.StartsWith("usertask-"))
            {
                name = name.Substring("usertask-".Length);

                var user = Services.WorkContext.CurrentUser;

                var awaiting = _awaitingActivityRepository.Table.Where(x => x.WorkflowRecord.ContentItemRecord == part.ContentItem.Record && x.ActivityRecord.Name == "UserTask").ToList();
                var actions  = awaiting.Where(x => UserIsInRole(x, user)).SelectMany(ListAction).ToList();

                if (!actions.Contains(name))
                {
                    Services.Notifier.Error(T("Not authorized to trigger {0}.", name));
                }
                else
                {
                    _workflowManager.TriggerEvent("UserTask", part, () => new Dictionary <string, object> {
                        { "Content", part.ContentItem }, { "UserTask.Action", name }
                    });
                }
            }

            return(Editor(part, shapeHelper));
        }
예제 #15
0
        private RestApiResponse InnerSignalInvocation(string verb, string actionName, int contentId)
        {
            // we want what we return here to map to HttpResponseMessage
            RestApiResponse restResult = new RestApiResponse();
            var             signalName = SignalName(verb, actionName);

            try {
                var content = _contentManager.Get(contentId);
                var tokens  = new Dictionary <string, object> {
                    // Content called for the action, if any.
                    { "Content", content },
                    // Custom Api configuration.
                    { "HttpVerb", verb },
                    { "RESTActionName", actionName },
                    { "AllowedMethods", AllowedMethods(actionName) },
                    // Workflow signal activity to invoke.
                    { SignalActivity.SignalEventName, signalName },
                    // Workflow will have to change this response.
                    { "RESTApiResponse", restResult }
                };
                _workflowManager
                .TriggerEvent(SignalActivity.SignalEventName, content, () => tokens);
            } catch (Exception ex) {
                Log.Error("CustomApiController.SignalInvocation: " + Environment.NewLine
                          + "verb: " + verb + Environment.NewLine
                          + "actionName: " + actionName + Environment.NewLine
                          + "contentId: " + contentId.ToString() + Environment.NewLine
                          + "signalName: " + signalName + Environment.NewLine
                          + "Exception.Message: " + ex.Message + Environment.NewLine
                          + "Exception.StackTrace: " + ex.StackTrace);
                return(new RestApiResponse(HttpStatusCode.InternalServerError));
            }
            return(restResult);
        }
예제 #16
0
        public void Sweep()
        {
            var awaiting = _awaitingActivityRepository.Table.Where(x => x.ActivityRecord.Name == "Timer").ToList();


            foreach (var action in awaiting)
            {
                try {
                    var contentItem = action.WorkflowRecord.ContentItemRecord != null?_contentManager.Get(action.WorkflowRecord.ContentItemRecord.Id, VersionOptions.Latest) : null;

                    var tokens = new Dictionary <string, object> {
                        { "Content", contentItem }
                    };
                    var workflowState = FormParametersHelper.FromJsonString(action.WorkflowRecord.State);
                    workflowState.TimerActivity_StartedUtc = null;
                    action.WorkflowRecord.State            = FormParametersHelper.ToJsonString(workflowState);
                    _workflowManager.TriggerEvent("Timer", contentItem, () => tokens);
                }
                catch (Exception ex) {
                    if (ex.IsFatal())
                    {
                        throw;
                    }
                    Logger.Error(ex, "TimerBackgroundTask: Error while processing background task \"{0}\".", action.ActivityRecord.Name);
                }
            }
        }
예제 #17
0
        public void Process(ScheduledTaskContext context)
        {
            try {
                var btnName = ButtonName(context.Task.TaskType);
                if (btnName == null)
                {
                    return;
                }
                if (string.IsNullOrWhiteSpace(btnName))
                {
                    btnName = context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().ButtonName;
                }
                if (string.IsNullOrWhiteSpace(btnName))
                {
                    // failed to figure out a valid button name
                    return;
                }

                _workflowManager.TriggerEvent("DynamicButtonEvent", context.Task.ContentItem, () =>
                                              new Dictionary <string, object> {
                    { "ButtonName", btnName },
                    { "Content", context.Task.ContentItem }
                });
            } catch (Exception ex) {
                Logger.Error(ex,
                             "Error in DynamicButtonToWorflowsScheduledTaskHandler. ContentItem: {0}, ScheduledUtc: {1:yyyy-MM-dd HH.mm.ss}",
                             context.Task.ContentItem, context.Task.ScheduledUtc);
            } finally {
                if (context.Task.ContentItem.Has <DynamicButtonToWorkflowsPart>())
                {
                    context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().ButtonName     = "";
                    context.Task.ContentItem.As <DynamicButtonToWorkflowsPart>().MessageToWrite = "";
                }
            }
        }
        public DynamicButtonToWorkflowsPartHandler(
            INotifier notifier,
            IScheduledTaskManager scheduledTaskManager,
            IWorkflowManager workflowManager)
        {
            _notifier             = notifier;
            _scheduledTaskManager = scheduledTaskManager;
            T = NullLocalizer.Instance;
            _workflowManager = workflowManager;

            OnUpdated <DynamicButtonToWorkflowsPart>((context, part) => {
                try {
                    if (!string.IsNullOrWhiteSpace(part.ButtonName))
                    {
                        var content = context.ContentItem;

                        if (part.ActionAsync)
                        {
                            // the task will need to use part.ButtonName to invoke the correct
                            // process. We generate a task that contains that in its type. Then
                            // we will parse that out when processing the task.
                            _scheduledTaskManager
                            .CreateTask(
                                DynamicButtonToWorflowsScheduledTaskHandler.TaskType(part.ButtonName),
                                DateTime.UtcNow.AddMinutes(1),
                                part.ContentItem);

                            if (!string.IsNullOrEmpty(part.MessageToWrite))
                            {
                                _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                            }
                        }
                        else
                        {
                            _workflowManager
                            .TriggerEvent("DynamicButtonEvent",
                                          content,
                                          () => new Dictionary <string, object> {
                                { "ButtonName", part.ButtonName },
                                { "Content", content }
                            });

                            if (!string.IsNullOrEmpty(part.MessageToWrite))
                            {
                                _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                            }
                        }
                        part.ButtonName     = "";
                        part.MessageToWrite = "";
                    }
                } catch (Exception ex) {
                    Logger.Error(ex, "Error in DynamicButtonToWorkflowsPartHandler. ContentItem: {0}", context.ContentItem);

                    part.ButtonName     = "";
                    part.MessageToWrite = "";
                }
            });
        }
예제 #19
0
 private void InvokeValidation(CheckoutConditionValidationContext context)
 {
     _workflowManager.TriggerEvent(
         ValidateCheckoutActivity.EventName,
         null,
         () => new Dictionary <string, object> {
         { "Context", context }
     });
 }
예제 #20
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var tokens = new Dictionary <string, object> {
                { "Content", workflowContext.Content }, { SignalActivity.SignalEventName, activityContext.GetState <string>(SignalActivity.SignalEventName) }
            };

            _workflowManager.TriggerEvent(SignalActivity.SignalEventName, workflowContext.Content, () => tokens);

            yield return(T("Done"));
        }
 public void OnError(int paymentId, int contentItemId) {
     var payment = _paymentService.GetPayment(paymentId);
     if (payment != null) {
         var order = _contentManager.Get<OrderPart>(payment.ContentItemId, VersionOptions.Latest);
         //order.Status = OrderPart.Cancelled;
         //_contentManager.Publish(order.ContentItem);
         _updateStatusService.UpdateOrderStatusChanged(order, Constants.PaymentFailed);
         
         _workflowManager.TriggerEvent(
             "OrderError", 
             order,
             () => new Dictionary<string, object> {
                 {"Content", order},
                 {"Order", order},
                 {"CheckoutError", payment.Error}
             });
         order.LogActivity(Constants.PaymentFailed, payment.Error, "System");
         //order.LogActivity(OrderPart.Error, string.Format("Transaction failed (payment id: {0}).", payment.Id));
     }
 }
예제 #22
0
        public WorkflowContentHandler(IWorkflowManager workflowManager) {

            OnPublished<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentPublished",
                    context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));

            OnRemoving<ContentPart>(
                (context, part) =>
                    workflowManager.TriggerEvent("ContentRemoved",
                    context.ContentItem,
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));

            OnVersioned<ContentPart>(
                (context, part1, part2) =>
                    workflowManager.TriggerEvent("ContentVersioned",
                    context.BuildingContentItem,
                    () => new Dictionary<string, object> { { "Content", context.BuildingContentItem } }));

            OnUpdated<ContentPart>(
                (context, part) => {
                    workflowManager.TriggerEvent("ContentUpdated",
                        context.ContentItem,
                        () => new Dictionary<string, object> { { "Content", context.ContentItem } });

                    // Trigger the ContentCreated event only when its values have been updated
                    if(_contentCreated.Contains(context.ContentItem.Id)) {
                        workflowManager.TriggerEvent("ContentCreated",
                            context.ContentItem,
                            () => new Dictionary<string, object> {{"Content", context.ContentItem}});
                    }
                });

            OnCreated<ContentPart>(
                // Flag the content item as "just created" but actually trigger the event
                // when its content has been updated as it is what users would expect.
                (context, part) => _contentCreated.Add(context.ContentItem.Id)
            );

        }
        private void StartWorkflow(int UserId, string text, TextSourceTypeOptions sourceType, int count)
        {
            var contentItem = _contentManager.Get(UserId);
            var contact     = _contentManager.Query().ForType("CommunicationContact").List().Where(x => ((dynamic)x).CommunicationContactPart.UserIdentifier == UserId).FirstOrDefault();        //("CommunicationContact").Where(x => x.UserIdentifier_Id == UserId).List().FirstOrDefault();

            _workflowManager.TriggerEvent("UserTracking", contact, () => new Dictionary <string, object> {
                { "contact", contact },
                { "text", text },
                { "sourceType", sourceType },
                { "count", count },
                { "UserId", UserId }
            });
        }
        public void Process(ScheduledTaskContext context)
        {
            var taskType = context.Task.TaskType;

            if (Constants.DefaultEventNames.Contains(taskType))
            {
                var contentItem = context.Task.ContentItem;
                _workflowManager.TriggerEvent(taskType, contentItem,
                                              () => new Dictionary <string, object> {
                    { "Content", contentItem }
                });
            }
        }
예제 #25
0
        public WorkflowProductHandler(IWorkflowManager workflowManager) {
            OnPublished<ContentPart>(
                (ctx, part) => {
                    var settings = ctx.ContentItem.TypeDefinition.Settings;
                    var isProduct = settings.ContainsKey("Stereotype") && settings["Stereotype"] == Constants.ProductName;
                    if (!isProduct)
                        return;

                    workflowManager.TriggerEvent("ProductPublished",
                        ctx.ContentItem,
                        () => new Dictionary<string, object>{{"Content", ctx.ContentItem}});
                });
        }
        public void WriteChangesToStreamActivity(int?userId, int contentId, int versionId, ActivityStreamChangeItem[] changes, string contentDescription, RouteValueDictionary route, bool createLinkToTheChange)
        {
            var noneEmptyItems = changes.Where(c => !string.IsNullOrEmpty(c.Change));
            var changesInOriginalStreamRecord = noneEmptyItems.Where(c => c.RequireNewRecord == false).Select(c => c.Change).ToArray();
            var seconadaryChangesWhichNeedNewRecordPerChange = noneEmptyItems.Where(c => c.RequireNewRecord);

            string description             = this.Encode(changesInOriginalStreamRecord, contentDescription, route, createLinkToTheChange);
            ActivityStreamRecord newRecord = new ActivityStreamRecord();

            newRecord.RelatedContent = new ContentItemRecord {
                Id = contentId
            };
            newRecord.RelatedVersion = new ContentItemVersionRecord {
                Id = versionId
            };
            newRecord.Description = description;
            newRecord.User        = userId.HasValue ? new UserPartRecord {
                Id = userId.Value
            } : null;
            newRecord.CreationDateTime = DateTime.UtcNow;
            repository.Create(newRecord);

            foreach (var item in seconadaryChangesWhichNeedNewRecordPerChange)
            {
                description = this.Encode(new[] { item.Change }, contentDescription, null, createLinkToTheChange);
                ActivityStreamRecord secondaryChangeRecord = new ActivityStreamRecord();
                secondaryChangeRecord.RelatedContent = new ContentItemRecord {
                    Id = item.RelatedContentId.HasValue ? item.RelatedContentId.Value : contentId
                };
                secondaryChangeRecord.RelatedVersion = new ContentItemVersionRecord {
                    Id = item.RelatedContentVersionId.HasValue ? item.RelatedContentVersionId.Value : versionId
                };
                secondaryChangeRecord.Description = description;
                secondaryChangeRecord.User        = userId.HasValue ? new UserPartRecord {
                    Id = userId.Value
                } : null;
                secondaryChangeRecord.CreationDateTime = DateTime.UtcNow;
                repository.Create(secondaryChangeRecord);
            }

            repository.Flush();

            var contentItem = this.services.ContentManager.Get(contentId);

            if (contentItem != null)
            {
                workflowManager.TriggerEvent(NewActivityStreamActivity.ActivityStreamActivityName, contentItem, () => new Dictionary <string, object> {
                    { "Content", contentItem }, { NewActivityStreamActivity.ActivityStreamRecordKey, newRecord }
                });
            }
        }
        public override void Validated(FormValidatedEventContext context)
        {
            if (!context.ModelState.IsValid)
            {
                return;
            }

            var form                 = context.Form;
            var formName             = form.Name;
            var values               = context.Values;
            var formService          = context.FormService;
            var formValuesDictionary = values.ToTokenDictionary();
            var formTokenContext     = new FormSubmissionTokenContext {
                Form         = form,
                ModelState   = context.ModelState,
                PostedValues = values
            };
            var tokenData = new Dictionary <string, object>(formValuesDictionary)
            {
                { "Updater", context.Updater },
                { "FormSubmission", formTokenContext },
                { "Content", context.Content }
            };

            // Store the submission.
            if (form.StoreSubmission == true)
            {
                formService.CreateSubmission(formName, values);
            }

            // Create content item.
            var contentItem = default(ContentItem);

            if (form.CreateContent == true && !String.IsNullOrWhiteSpace(form.FormBindingContentType))
            {
                contentItem = formService.CreateContentItem(form, context.ValueProvider);
                formTokenContext.CreatedContent = contentItem;
            }

            // Notifiy.
            if (!String.IsNullOrWhiteSpace(form.Notification))
            {
                _notifier.Success(T(_tokenizer.Replace(T(form.Notification).Text, tokenData)));
            }

            // Trigger workflow event.
            _workflowManager.TriggerEvent(DynamicFormSubmittedActivity.EventName, contentItem, () => tokenData);
        }
        public DynamicButtonToWorkflowsPartHandler(INotifier notifier, IScheduledTaskManager scheduledTaskManager, IWorkflowManager workflowManager)
        {
            _notifier             = notifier;
            _scheduledTaskManager = scheduledTaskManager;
            _workflowManager      = workflowManager;
            T = NullLocalizer.Instance;

            OnUpdated <DynamicButtonToWorkflowsPart>((context, part) => {
                try {
                    if (!string.IsNullOrWhiteSpace(part.ButtonName))
                    {
                        var content = context.ContentItem;

                        if (part.ActionAsync)
                        {
                            _scheduledTaskManager.CreateTask("Laser.Orchard.DynamicButtonToWorkflows.Task", DateTime.UtcNow.AddMinutes(1), part.ContentItem);

                            if (!string.IsNullOrEmpty(part.MessageToWrite))
                            {
                                _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                            }
                        }
                        else
                        {
                            _workflowManager.TriggerEvent("DynamicButtonEvent", content, () => new Dictionary <string, object> {
                                { "ButtonName", part.ButtonName }, { "Content", content }
                            });

                            if (!string.IsNullOrEmpty(part.MessageToWrite))
                            {
                                _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                            }

                            part.ButtonName     = "";
                            part.MessageToWrite = "";
                            part.ActionAsync    = false;
                        }
                    }
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error in DynamicButtonToWorkflowsPartHandler. ContentItem: {0}", context.ContentItem);

                    part.ButtonName     = "";
                    part.MessageToWrite = "";
                    part.ActionAsync    = false;
                }
            });
        }
        public Response TriggerSignal(string signalName, int contentId)
        {
            Response triggerResult = _utilsServices.GetResponse(ResponseType.Success);

            try {
                var content = _orchardServices.ContentManager.Get(contentId, VersionOptions.Published);
                var tokens  = new Dictionary <string, object> {
                    { "Content", content },
                    { SignalActivity.SignalEventName, signalName },
                    { "WebApiResponse", triggerResult }
                };
                _workflowManager.TriggerEvent(SignalActivity.SignalEventName, content, () => tokens);
            } catch (Exception ex) {
                Log.Error("TriggerSignal " + ex.Message + "stack" + ex.StackTrace);
            }
            return(triggerResult);
        }
예제 #30
0
        public void Sweep()
        {
            var awaiting = _awaitingActivityRepository.Table.Where(x => x.ActivityRecord.Name == "Timer").ToList();


            foreach (var action in awaiting)
            {
                var contentItem = _contentManager.Get(action.WorkflowRecord.ContentItemRecord.Id, VersionOptions.Latest);
                var tokens      = new Dictionary <string, object> {
                    { "Content", contentItem }
                };
                var workflowState = FormParametersHelper.FromJsonString(action.WorkflowRecord.State);
                workflowState.TimerActivity_StartedUtc = null;
                action.WorkflowRecord.State            = FormParametersHelper.ToJsonString(workflowState);
                _workflowManager.TriggerEvent("Timer", contentItem, () => tokens);
            }
        }
예제 #31
0
        public ButtonToWorkflowsPartHandler(IWorkflowManager workflowManager, INotifier notifier, IScheduledTaskManager scheduledTaskManager)
        {
            _workflowManager      = workflowManager;
            _notifier             = notifier;
            _scheduledTaskManager = scheduledTaskManager;
            T = NullLocalizer.Instance;

            OnUpdated <ButtonToWorkflowsPart>((context, part) => {
                if (!string.IsNullOrEmpty(part.ActionToExecute))
                {
                    var content = context.ContentItem;
                    if (part.ActionAsync)
                    {
                        //  part.ButtonsDenied = true;
                        _scheduledTaskManager.CreateTask("Laser.Orchard.ButtonToWorkflows.Task", DateTime.UtcNow.AddMinutes(1), part.ContentItem);
                    }
                    else
                    {
                        _workflowManager.TriggerEvent(part.ActionToExecute, content, () => new Dictionary <string, object> {
                            { "Content", content }
                        });
                        part.MessageToWrite  = "";
                        part.ActionToExecute = "";
                        part.ActionAsync     = false;
                    }
                    try {
                        if (!string.IsNullOrEmpty(part.MessageToWrite))
                        {
                            _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                        }
                    }
                    catch { }
                }

                //  if (context.ContentItem.As<CommonPart>() != null) {
                //    var currentUser = _orchardServices.WorkContext.CurrentUser;
                //if (currentUser != null) {
                //    ((dynamic)context.ContentItem.As<CommonPart>()).LastModifier.Value = currentUser.Id;
                //    if (((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value == null)
                //        //  ((NumericField) CommonPart.Fields.Where(x=>x.Name=="Creator").FirstOrDefault()).Value = currentUser.Id;
                //        ((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value = currentUser.Id;
                //}
                //   }
            });
        }
예제 #32
0
        private void RaiseWorkflow(IMAPHostRecord hostRecord, MailMessage mail, uint id)
        {
            var contentManager   = this.orchardServices.ContentManager;
            var emailContentItem = contentManager.New(IMAPEmailPart.ContentItemTypeName);
            var emailPart        = emailContentItem.As <IMAPEmailPart>();

            // I don't know why it is null
            if (emailPart == null)
            {
                emailPart = new IMAPEmailPart();
                emailContentItem.Weld(emailPart);
            }

            emailPart.MailMessage = mail;
            dynamic sender = new JObject();

            sender.Name  = mail.From.DisplayName;
            sender.Email = mail.From.Address;
            var user = this.userRepository.Table.FirstOrDefault(c => c.Email.ToLower() == mail.From.Address.ToLower());

            if (user != null)
            {
                var commonPart = emailContentItem.As <CommonPart>();
                commonPart.Owner = contentManager.Get <IUser>(user.Id);
                sender.UserId    = user.Id;
                sender.UserName  = user.UserName;
            }

            emailPart.From    = JsonConvert.SerializeObject(sender);
            emailPart.Subject = string.IsNullOrEmpty(mail.Subject) ? this.T("[No subject]").Text : mail.Subject;
            emailPart.UId     = id;

            contentManager.Create(emailContentItem);
            contentManager.Publish(emailContentItem);

            workflowManager.TriggerEvent(
                IMapEmailReceivedActivity.ActivityName,
                emailContentItem,
                () => new Dictionary <string, object> {
                { "Content", emailContentItem }
            });

            hostRecord.EmailUid = id;
            this.imapHostRecordService.Save(hostRecord);
        }
예제 #33
0
        public override void Validating(FormValidatingEventContext context)
        {
            var form   = context.Form;
            var values = context.Values;
            var formValuesDictionary = values.ToTokenDictionary();

            var formTokenContext = new FormSubmissionTokenContext {
                Form         = form,
                ModelState   = context.ModelState,
                PostedValues = values
            };
            var tokensData = new Dictionary <string, object>(formValuesDictionary)
            {
                { "Updater", context.Updater },
                { "FormSubmission", formTokenContext },
            };

            _workflowManager.TriggerEvent(name: DynamicFormValidatingActivity.EventName, target: null, tokensContext: () => tokensData);
        }