예제 #1
0
        public SpamFilterPartHandler(
            IRepository<SpamFilterPartRecord> repository,
            ITransactionManager transactionManager,
            ISpamService spamService
            ) {
            _transactionManager = transactionManager;
            _spamService = spamService;

            Filters.Add(StorageFilter.For(repository));

            OnCreating<SpamFilterPart>((context, part) => {
                part.Status = _spamService.CheckForSpam(part);
            });

            OnPublishing<SpamFilterPart>((context, part) => {
                if (part.Status == SpamStatus.Spam) {
                    if (part.Settings.GetModel<SpamFilterPartSettings>().DeleteSpam) {
                        _transactionManager.Cancel();
                    }

                    context.Cancel = true;
                }
            });

        }
예제 #2
0
        public void Sweep()
        {
            var taskEntries = _repository.Fetch(x => x.ScheduledUtc <= _clock.UtcNow)
                              .Select(x => new { x.Id, Action = x.TaskType })
                              .ToArray();

            foreach (var taskEntry in taskEntries)
            {
                _transactionManager.RequireNew();

                try {
                    // fetch the task
                    var taskRecord = _repository.Get(taskEntry.Id);

                    // another server or thread has performed this work before us
                    if (taskRecord == null)
                    {
                        continue;
                    }

                    // removing record first helps avoid concurrent execution
                    _repository.Delete(taskRecord);

                    var context = new ScheduledTaskContext {
                        Task = new Task(_contentManager, taskRecord)
                    };

                    // dispatch to standard or custom handlers
                    foreach (var handler in _handlers)
                    {
                        handler.Process(context);
                    }
                }
                catch (Exception ex) {
                    if (ex.IsFatal())
                    {
                        throw;
                    }
                    Logger.Warning(ex, "Unable to process scheduled task #{0} of type {1}", taskEntry.Id, taskEntry.Action);
                    _transactionManager.Cancel();
                }
            }
        }
        public SpamFilterPartHandler(
            IRepository <SpamFilterPartRecord> repository,
            ITransactionManager transactionManager
            )
        {
            _transactionManager = transactionManager;
            Filters.Add(StorageFilter.For(repository));

            OnPublishing <SpamFilterPart>((context, part) => {
                if (part.Status == SpamStatus.Spam)
                {
                    if (part.Settings.GetModel <SpamFilterPartSettings>().DeleteSpam)
                    {
                        _transactionManager.Cancel();
                    }

                    context.Cancel = true;
                }
            });
        }
예제 #4
0
        public ActionResult CreatePOST()
        {
            //if (!Services.Authorizer.Authorize(Permissions.ManageNewsletterDefinitions, T("Couldn't create newsletter")))
            //    return new HttpUnauthorizedResult();

            var newsletterDefinition = Services.ContentManager.New <NewsletterDefinitionPart>("NewsletterDefinition");

            _contentManager.Create(newsletterDefinition, VersionOptions.Draft);
            dynamic model = _contentManager.UpdateEditor(newsletterDefinition, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
                return(View((object)model));
            }

            Services.ContentManager.Publish(newsletterDefinition.ContentItem);
            return(Redirect(Url.NewsLetterEdit(newsletterDefinition)));
        }
예제 #5
0
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageProduct, T("Couldn't create product")))
            {
                return(new HttpUnauthorizedResult());
            }

            var product = Services.ContentManager.New <ProductPart>("Product");

            _contentManager.Create(product, VersionOptions.Draft);
            var model = _contentManager.UpdateEditor(product, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }

            _contentManager.Publish(product.ContentItem);
            return(Redirect(Url.ProductForAdmin(product)));
        }
예제 #6
0
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageEventTypes, T("Couldn't create event category")))
            {
                return(new HttpUnauthorizedResult());
            }

            var item = Services.ContentManager.New <CategoryPart>("EventCategory");

            Services.ContentManager.Create(item, VersionOptions.Draft);
            var model = Services.ContentManager.UpdateEditor(item, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }

            Services.ContentManager.Publish(item.ContentItem);
            return(Redirect(Url.EventCategoriesForAdmin()));
        }
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageCases, T("Couldn't create case")))
            {
                return(new HttpUnauthorizedResult());
            }

            var cAse = Services.ContentManager.New <CasePart>("Case");

            _contentManager.Create(cAse, VersionOptions.Draft);
            var model = _contentManager.UpdateEditor(cAse, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }

            _contentManager.Publish(cAse.ContentItem);
            return(Redirect(Url.CaseForAdmin(cAse)));
        }
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageBlogs, T("Couldn't create blog")))
            {
                return(new HttpUnauthorizedResult());
            }

            var blog = Services.ContentManager.New <BlogPart>("Blog");

            _contentManager.Create(blog, VersionOptions.Draft);
            var model = _contentManager.UpdateEditor(blog, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }

            _contentManager.Publish(blog.ContentItem);
            return(Redirect(Url.BlogForAdmin(blog)));
        }
예제 #9
0
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageBlogs, T("Couldn't create blog")))
            {
                return(new HttpUnauthorizedResult());
            }

            var blog = Services.ContentManager.New <BlogPart>("Blog");

            _contentManager.Create(blog, VersionOptions.Draft);
            dynamic model = _contentManager.UpdateEditor(blog, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
                return(View((object)model));
            }

            _contentManager.Publish(blog.ContentItem);
            return(Redirect(Url.BlogForAdmin(blog)));
        }
예제 #10
0
        public void Sweep()
        {
            foreach (var task in _tasks)
            {
                var taskName = task.GetType().FullName;

                try {
                    Logger.Information("Start processing background task \"{0}\" on tenant \"{1}\".", taskName, _shellName);
                    _transactionManager.RequireNew();
                    task.Sweep();
                    Logger.Information("Finished processing background task \"{0}\" on tenant \"{1}\".", taskName, _shellName);
                }
                catch (Exception ex) {
                    if (ex.IsFatal())
                    {
                        throw;
                    }

                    _transactionManager.Cancel();
                    Logger.Error(ex, "Error while processing background task \"{0}\" on tenant \"{1}\".", taskName, _shellName);
                }
            }
        }
예제 #11
0
        public ViewResult Update(string session)
        {
            var sessionState    = _objectStore.Get <ElementSessionState>(session);
            var contentId       = sessionState.ContentId;
            var contentType     = sessionState.ContentType;
            var typeName        = sessionState.TypeName;
            var elementData     = ElementDataHelper.Deserialize(sessionState.ElementData);
            var describeContext = CreateDescribeContext(contentId, contentType);
            var descriptor      = _elementManager.GetElementDescriptorByTypeName(describeContext, typeName);
            var data            = elementData.Combine(ElementDataHelper.Deserialize(sessionState.ElementEditorData));
            var element         = _elementManager.ActivateElement(descriptor, e => e.Data = data);
            var context         = CreateEditorContext(session, describeContext.Content, element, elementData, this);
            var editorResult    = _elementManager.UpdateEditor(context);

            var viewModel = new EditElementViewModel {
                Layout       = describeContext.Content.As <ILayoutAspect>(),
                EditorResult = editorResult,
                TypeName     = typeName,
                DisplayText  = descriptor.DisplayText,
                ElementData  = element.Data.Serialize(),
                Tabs         = editorResult.CollectTabs().ToArray(),
                SessionKey   = session
            };

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
            }
            else
            {
                viewModel.ElementHtml        = RenderElement(element, describeContext);
                viewModel.Submitted          = true;
                viewModel.ElementEditorModel = _mapper.ToEditorModel(element, describeContext);
            }
            return(View("Edit", viewModel));
        }
        public bool AddRecords([FromBody] List <TranslationRecord> records)
        {
            try
            {
                if (records == null)
                {
                    Log.Error("TranslatorAPIController.AddRecords error - No data received in TranslationRecord list.");
                    return(false);
                }
                if (records.Where(r => String.IsNullOrWhiteSpace(r.Message) ||
                                  String.IsNullOrWhiteSpace(r.Language) ||
                                  String.IsNullOrWhiteSpace(r.ContainerName) ||
                                  String.IsNullOrWhiteSpace(r.ContainerType)).Any())
                {
                    Log.Error("TranslatorAPIController.AddRecords error - TranslationRecord not valid. At least one of these field is empty: Message, Language, ContainerName and ContainerType. Please verify if T(\"\") is present in your code because it causes an empty Message.");
                    return(false);
                }

                foreach (var record in records)
                {
                    var alreadyExistingRecords = _translatorServices.GetTranslations().Where(r => r.ContainerName == record.ContainerName &&
                                                                                             r.ContainerType == record.ContainerType &&
                                                                                             r.Context == record.Context &&
                                                                                             r.Message == record.Message &&
                                                                                             r.Language == record.Language);
                    var tryAddOrUpdateTranslation = true;
                    if (alreadyExistingRecords.Any())
                    {
                        // verifica maiuscole/minuscole del message
                        if (record.Message.Equals(alreadyExistingRecords.First().Message, StringComparison.InvariantCulture))
                        {
                            tryAddOrUpdateTranslation = false;
                        }
                    }
                    if (tryAddOrUpdateTranslation)
                    {
                        bool success = _translatorServices.TryAddOrUpdateTranslation(record);
                        if (!success)
                        {
                            _transactionManager.Cancel();
                            Log.Error("TranslatorAPIController.AddRecords error - Id: {0}, Message: {1}", record.Id, record.Message);
                            return(false);
                        }
                    }
                }

                var folderList = records.GroupBy(g => new { g.ContainerName, g.ContainerType })
                                 .Select(g => new { g.Key.ContainerName, g.Key.ContainerType });

                foreach (var folder in folderList)
                {
                    if (folder.ContainerType == "M")
                    {
                        _translatorServices.EnableFolderTranslation(folder.ContainerName, ElementToTranslate.Module);
                    }
                    else if (folder.ContainerType == "T")
                    {
                        _translatorServices.EnableFolderTranslation(folder.ContainerName, ElementToTranslate.Theme);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                _transactionManager.Cancel();
                Log.Error(ex, "TranslatorAPIController.AddRecords error.");
                return(false);
            }
        }
        private ActionResult CreatePOST(int id, string returnUrl, Action <ContentItem> conditionallyPublish)
        {
            var form = _contentManager.Get(id);

            if (form == null || !form.Has <CustomFormPart>())
            {
                return(HttpNotFound());
            }

            var customForm  = form.As <CustomFormPart>();
            var contentItem = _contentManager.New(customForm.ContentType);

            if (!Services.Authorizer.Authorize(Permissions.CreateSubmitPermission(customForm.ContentType), contentItem, T("Couldn't create content")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (customForm.SaveContentItem)
            {
                _contentManager.Create(contentItem, VersionOptions.Draft);
            }

            var model = _contentManager.UpdateEditor(contentItem, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();

                // if custom form is inside a widget, we display the form itself
                if (form.ContentType == "CustomFormWidget")
                {
                    foreach (var error in ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage))
                    {
                        Services.Notifier.Error(T(error));
                    }

                    // save the updated editor shape into TempData to survive a redirection and keep the edited values
                    TempData["CustomFormWidget.InvalidCustomFormState"] = model;

                    if (returnUrl != null)
                    {
                        return(this.RedirectLocal(returnUrl));
                    }
                }

                model.ContentItem(form);
                return(View(model));
            }

            contentItem.As <ICommonPart>().Container = customForm.ContentItem;

            // triggers any event
            _rulesManager.TriggerEvent("CustomForm", "Submitted",
                                       () => new Dictionary <string, object> {
                { "Content", contentItem }
            });

            // trigger any workflow
            _workflowManager.TriggerEvent(FormSubmittedActivity.EventName, contentItem,
                                          () => new Dictionary <string, object> {
                { "Content", contentItem }, { "CustomForm", customForm.ContentItem }
            });

            if (customForm.Redirect)
            {
                returnUrl = _tokenizer.Replace(customForm.RedirectUrl, new Dictionary <string, object> {
                    { "Content", contentItem }
                });
            }

            // save the submitted form
            if (customForm.SaveContentItem)
            {
                conditionallyPublish(contentItem);
            }

            // writes a confirmation message
            if (customForm.CustomMessage)
            {
                if (!String.IsNullOrWhiteSpace(customForm.Message))
                {
                    Services.Notifier.Information(T(customForm.Message));
                }
            }

            var referrer = Request.UrlReferrer != null?Request.UrlReferrer.ToString() : null;

            return(this.RedirectLocal(returnUrl, () => this.RedirectLocal(referrer, () => Redirect(Request.RawUrl))));
        }
        /// <summary>
        /// Formato DateTimeField: 2009-06-15T13:45:30  yyyy-MM-ddThh:mm:ss NB: L’ora deve essere riferita all’ora di Greenwich
        /// </summary>
        /// <param name="eObj"></param>
        /// <param name="TheContentItem"></param>
        /// <returns></returns>
        private Response StoreNewContentItem(ExpandoObject eObj)
        {
            // Reasoning on permissions will require us to know the type
            // of the content.
            string tipoContent = ((dynamic)eObj).ContentType;
            // We will also need to know the content's Id in case we are
            // trying to edit an existing ContentItem.
            Int32 IdContentToModify = 0; // new content

            try {
                if ((Int32)(((dynamic)eObj).Id) > 0)
                {
                    IdContentToModify = (Int32)(((dynamic)eObj).Id);
                }
            } catch {
                // Fix per Username nullo
                if (tipoContent == "User")
                {
                    return(_utilsServices.GetResponse(ResponseType.Validation, "Missing user Id"));
                }
            }
            // We will be doing a first check on the ContentType, to validate what's coming
            // to the API. The call to the GetTypeDefinition method will also do null checks
            // on the type name for us.
            var typeDefinition = _contentDefinitionManager.GetTypeDefinition(tipoContent);

            if (typeDefinition == null)
            {
                // return an error of some sort here
                return(_utilsServices.GetResponse(ResponseType.Validation, "Invalid ContentType"));
            }
            // The ContentItem we will create/edit
            ContentItem NewOrModifiedContent;

            if (IdContentToModify == 0)
            {
                // We are going to be creating a new ContentItem
                NewOrModifiedContent = _contentManager.New(tipoContent);
                if (!_authorizer.Authorize(CorePermissions.CreateContent, NewOrModifiedContent))
                {
                    // the user cannot create content of the given type, so
                    // return an error
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
                // since we may create, create
                _contentManager.Create(NewOrModifiedContent, VersionOptions.Draft);
            }
            else
            {
                // we are attempting to modify an existing items
                NewOrModifiedContent = _contentManager.Get(IdContentToModify, VersionOptions.DraftRequired);
            }
            if (NewOrModifiedContent == null)
            {
                // something went horribly wrong, so return an error
                return(_utilsServices.GetResponse(ResponseType.Validation, "No content with this Id"));
            }
            // If either of these validations fail, return an error because we cannot
            // edit the content
            // Validation 1: item should be of the given type
            if (NewOrModifiedContent.TypeDefinition.Name != tipoContent)
            {
                // return an error
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }
            // Validation 2: check EditContent Permissions
            if (!_authorizer.Authorize(CorePermissions.EditContent, NewOrModifiedContent)
                // we also check permissions that may exist for this specific method
                && !_contentExtensionService.HasPermission(tipoContent, Methods.Post, NewOrModifiedContent))
            {
                // return an error
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }
            // Validation 3: if we are also trying to publish, check PublishContent Permissions
            if (NewOrModifiedContent.Has <IPublishingControlAspect>() ||
                NewOrModifiedContent.TypeDefinition.Settings.GetModel <ContentTypeSettings>().Draftable)
            {
                // in this case, simply the EditContent permission is not enough because that
                // would only allow the user to create a draftable
                if (!_authorizer.Authorize(CorePermissions.PublishContent, NewOrModifiedContent))
                {
                    // return an error
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
            }
            // To summarize, here we have a valid ContentItem that we are authorized to edit
            Response rsp = new Response();
            // do some further custom validation
            string validateMessage = ValidateMessage(NewOrModifiedContent, IdContentToModify == 0 ? "Created" : "Modified");

            if (string.IsNullOrEmpty(validateMessage))
            {
                // act like _contentManager.UpdateEditor
                var context = new UpdateContentContext(NewOrModifiedContent);
                // 1. invoke the Updating handlers
                Handlers.Invoke(handler => handler.Updating(context), Logger);
                // 2. do all the update operations
                rsp = _contentExtensionService.StoreInspectExpando(eObj, NewOrModifiedContent);
                if (rsp.Success)
                {
                    try {
                        string language = "";
                        try {
                            language = ((dynamic)eObj).Language;
                        } catch { }
                        if (NewOrModifiedContent.As <LocalizationPart>() != null)
                        {
                            if (!string.IsNullOrEmpty(language))
                            {
                                NewOrModifiedContent.As <LocalizationPart>().Culture = _cultureManager.GetCultureByName(language);
                            }
                            NewOrModifiedContent.As <LocalizationPart>().MasterContentItem = NewOrModifiedContent;
                        }
                        validateMessage = ValidateMessage(NewOrModifiedContent, "");
                        if (!string.IsNullOrEmpty(validateMessage))
                        {
                            rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
                        }
                        // Have a validation actually return a response saying there
                        // was a validation error
                        validateMessage = ValidateMessage(NewOrModifiedContent, "Validation");
                        if (!string.IsNullOrEmpty(validateMessage))
                        {
                            rsp = _utilsServices.GetResponse(ResponseType.Validation, validateMessage);
                            // TODO: define better resolution actions depending
                            // error details?
                            rsp.ResolutionAction = ResolutionAction.AddParameter;
                        }
                        dynamic data = new ExpandoObject();
                        data.Id          = (Int32)(((dynamic)NewOrModifiedContent).Id);
                        data.ContentType = ((dynamic)NewOrModifiedContent).ContentType;
                        if (NewOrModifiedContent.As <AutoroutePart>() != null)
                        {
                            data.DisplayAlias = ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias;
                        }
                        rsp.Data = data;
                    }
                    catch (Exception ex) {
                        rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                    }
                }
                // 3. invoke the Updated handlers
                Handlers.Invoke(handler => handler.Updated(context), Logger);
                // Check whether any handler set some Error notifications (???)
                foreach (var notifi in _notifier.List())
                {
                    if (notifi.Type == NotifyType.Error)
                    {
                        // we'll cancel the transaction later
                        //_transactionManager.Cancel();
                        rsp.Success = false;
                        rsp.Message = "Error on update";
                        Logger.Error(notifi.Message.ToString());
                        break;
                    }
                }
            }
            else
            {
                // Custom validation failed
                // this one has by definition rsp.Success == false
                rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
            }

            if (!rsp.Success)
            {
                // update failed
                _transactionManager.Cancel();
                // return an error
                return(rsp);
            }


            // we want the ContentItem to be published, so it can be "seen" by mobile
            // and the caches generated by the content will be evicted as well
            _contentManager.Publish(NewOrModifiedContent);
            return(rsp);
        }
예제 #15
0
        private ActionResult CreatePOST(int id, string returnUrl, Action <ContentItem> conditionallyPublish)
        {
            var form = _contentManager.Get(id);

            if (form == null || !form.Has <CustomFormPart>())
            {
                return(HttpNotFound());
            }

            var customForm = form.As <CustomFormPart>();

            var contentItem = _contentManager.New(customForm.ContentType);

            if (!Services.Authorizer.Authorize(Permissions.CreateSubmitPermission(customForm.ContentType), contentItem, T("Couldn't create content")))
            {
                return(new HttpUnauthorizedResult());
            }

            _contentManager.Create(contentItem, VersionOptions.Draft);

            dynamic model = _contentManager.UpdateEditor(contentItem, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();

                // if custom form is inside a widget, we display the form itself
                if (form.ContentType == "CustomFormWidget")
                {
                }

                // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
                return(View((object)model));
            }

            contentItem.As <ICommonPart>().Container = customForm.ContentItem;

            // triggers any event
            _rulesManager.TriggerEvent("CustomForm", "Submitted",
                                       () => new Dictionary <string, object> {
                { "Content", contentItem }
            });

            if (customForm.Redirect)
            {
                returnUrl = _tokenizer.Replace(customForm.RedirectUrl, new Dictionary <string, object> {
                    { "Content", contentItem }
                });
            }

            // save the submitted form
            if (!customForm.SaveContentItem)
            {
                Services.ContentManager.Remove(contentItem);
            }
            else
            {
                conditionallyPublish(contentItem);
            }

            // writes a confirmation message
            if (customForm.CustomMessage)
            {
                if (!String.IsNullOrWhiteSpace(customForm.Message))
                {
                    Services.Notifier.Information(T(customForm.Message));
                }
            }

            return(this.RedirectLocal(returnUrl, () => Redirect(Request.RawUrl)));
        }
        protected override DriverResult Editor(HighlightsGroupPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var group           = new HighlightsGroup();
            var httpContext     = _httpContextAccessor.Current();
            var HighlightsItems = _HighlightsService.GetHighlightsItemsByGroupId(part.Id);
            var form            = httpContext.Request.Form;

            int[] Ordinati = new int[form.Count];

            string Suffisso;
            int    Riga = 0;

            foreach (string key in form.Keys)
            {
                if (key.StartsWith("HighlightsItems"))
                {
                    Suffisso = key.Substring(key.IndexOf("].") + 2);
                    switch (Suffisso)
                    {
                    case "Position":
                        //Lista[Riga, 0] = Convert.ToInt32(form[key]);
                        break;

                    case "ItemId":
                        Ordinati[Riga++] = Convert.ToInt32(form[key]);
                        break;

                    default:
                        break;
                    }
                }
            }


            String Messaggio;

            Messaggio = "";
            if (Messaggio != "")
            {
                updater.AddModelError(this.Prefix, T(Messaggio));
            }

            Array.Resize <int>(ref Ordinati, Riga);

            if (updater.TryUpdateModel(group, Prefix, null, null))
            {
                if (group.DisplayPlugin.StartsWith(group.DisplayTemplate.ToString() + " - "))
                {
                    part.DisplayPlugin = group.DisplayPlugin;
                }
                else
                {
                    part.DisplayPlugin = "";
                }
                part.DisplayTemplate = group.DisplayTemplate;
                part.ItemsSourceType = group.ItemsSourceType;
                if (group.ItemsSourceType == Enums.ItemsSourceTypes.ByHand)
                {
                    if (group.HighlightsItemsOrder != null)
                    {
                        for (var i = 0; i < Ordinati.Length; i++)
                        {
                            _HighlightsService.UpdateOrder(Convert.ToInt32(Ordinati[i]), i);
                        }
                    }
                }
                else
                {
                    part.Query_Id = group.Query_Id;
                }
            }
            else
            {
                _transactions.Cancel();
            }
            return(Editor(part, shapeHelper));
        }
예제 #17
0
        public ActionResult Save(string returnUrl)
        {
            var editModel   = new ViewModels.QuestionnaireWithResultsViewModel();
            var currentUser = _orchardServices.WorkContext.CurrentUser;

            try {
                if (TryUpdateModel(editModel, _prefix))
                {
                    TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                    TempData["HasAcceptedTerms"]      = editModel.HasAcceptedTerms;

                    QuestionnairesPartSettingVM questionnairePartSettings = null;
                    var questionnaire = _orchardServices.ContentManager.Get(editModel.Id);
                    if (questionnaire != null && questionnaire.As <QuestionnairePart>() != null)
                    {
                        questionnairePartSettings = questionnaire.As <QuestionnairePart>().Settings.GetModel <QuestionnairesPartSettingVM>();
                    }

                    // verifica se il questionario può essere compilato una volta sola ed è già stato compilato
                    bool canBeFilled = true;
                    var  questionnaireModuleSettings = _orchardServices.WorkContext.CurrentSite.As <QuestionnaireModuleSettingsPart>();
                    if (questionnaireModuleSettings.Disposable)
                    {
                        if (currentUser == null || (questionnairePartSettings != null && questionnairePartSettings.ForceAnonymous))
                        {
                            var cookie = Request.Cookies["Questionnaires"];
                            if (cookie != null)
                            {
                                var ids = cookie.Value;
                                if (ids.Contains("," + editModel.Id + ","))
                                {
                                    canBeFilled = false;
                                }
                            }
                        }
                    }
                    if (canBeFilled)
                    {
                        string uniqueId;
                        var    request = ControllerContext.HttpContext.Request;

                        if (request != null && request.Headers["x-uuid"] != null)
                        {
                            uniqueId = request.Headers["x-uuid"];
                        }
                        else
                        {
                            uniqueId = ControllerContext.HttpContext.Session.SessionID;
                        }

                        canBeFilled = _questionnairesServices.Save(editModel, currentUser, uniqueId);
                    }
                    if (canBeFilled == false)
                    {
                        TempData["QuestError"]       = T("Sorry, you already submitted this questionnaire.");
                        TempData["AlreadySubmitted"] = true;
                    }
                    else
                    {
                        TempData["QuestSuccess"] = T("Thank you for submitting your feedback.");
                    }
                }
                else
                {
                    TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                    _transactionManager.Cancel();
                    var errors = ModelState.Values.Where(w => w.Errors.Count() > 0).Select(s => s.Errors.First().ErrorMessage);
                    TempData["QuestError"] = String.Join("\r\n", errors);
                }
            } catch (Exception ex) {
                TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                _transactionManager.Cancel();
                TempData["QuestError"] = T(ex.Message) + ex.StackTrace;
            }
            return(this.RedirectLocal(returnUrl, "~/"));
        }
예제 #18
0
 public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
 {
     _transactionManager.Cancel();
 }
예제 #19
0
        public ActionResult Create(int id, string task, JobViewModel jobViewModel)
        {
            if (!_authorizer.Authorize(Permissions.ManageCloudMediaJobs, T("You are not authorized to manage cloud jobs.")))
            {
                return(new HttpUnauthorizedResult());
            }

            Logger.Debug("User requested to create job with task of type {0} on cloud video item with ID {1}.", task, id);

            var cloudVideoPart = _contentManager.Get <CloudVideoPart>(id, VersionOptions.Latest);

            if (cloudVideoPart == null)
            {
                Logger.Warning("User requested to create job on cloud video item with ID {0} but no such cloud video item exists.", id);
                return(HttpNotFound(String.Format("No cloud video item with ID {0} was found.", id)));
            }

            var taskProvider    = _taskProviders.Single(x => x.Name == task);
            var inputAsset      = cloudVideoPart.Assets.Single(x => x.Record.Id == jobViewModel.SelectedInputAssetId);
            var videoName       = _contentManager.GetItemMetadata(cloudVideoPart).DisplayText;
            var taskConfig      = (TaskConfiguration)taskProvider.Editor(New, this);
            var taskConnections = taskProvider.GetConnections(taskConfig);
            var taskDisplayText = taskProvider.GetDisplayText(taskConfig);
            var jobName         = !String.IsNullOrWhiteSpace(jobViewModel.Name) ? jobViewModel.Name.TrimSafe() : !String.IsNullOrWhiteSpace(taskDisplayText) ? taskDisplayText : String.Format("{0} ({1})", videoName, taskProvider.Name);
            var jobDescription  = jobViewModel.Description.TrimSafe();

            if (ModelState.IsValid)
            {
                try {
                    var wamsJob        = _wamsClient.CreateNewJob(jobName);
                    var wamsInputAsset = _wamsClient.GetAssetById(inputAsset.WamsAssetId);
                    var wamsTask       = taskProvider.CreateTask(taskConfig, wamsJob.Tasks, new[] { wamsInputAsset });
                    wamsJob.Submit(); // Needs to be done here for job and tasks to get their WAMS ID values.

                    var job = _jobManager.CreateJobFor(cloudVideoPart, j => {
                        j.WamsJobId              = wamsJob.Id;
                        j.Name                   = jobName;
                        j.Description            = jobDescription;
                        j.Status                 = JobStatus.Pending;
                        j.CreatedUtc             = _clock.UtcNow;
                        j.OutputAssetName        = jobViewModel.OutputAssetName.TrimSafe();
                        j.OutputAssetDescription = jobViewModel.OutputAssetDescription.TrimSafe();
                    });

                    _jobManager.CreateTaskFor(job, t => {
                        t.HarvestAssetType = taskConnections.Outputs.First().AssetType;
                        t.HarvestAssetName = taskConnections.Outputs.First().AssetName;
                        t.Settings         = taskProvider.Serialize(taskConfig.Settings);
                        t.Index            = 0;
                        t.TaskProviderName = taskProvider.Name;
                        t.WamsTaskId       = wamsTask.Id;
                    });

                    Logger.Information("Job was created with task of type {0} on cloud video item with ID {1}.", task, id);
                    _notifier.Success(T("The job '{0}' was successfully created.", job.Name));

                    return(Redirect(Url.ItemEditUrl(cloudVideoPart)));
                }
                catch (Exception ex) {
                    _transactionManager.Cancel();

                    Logger.Error(ex, "Error while creating job with task of type {0} on cloud video item with ID {1}.", task, id);
                    _notifier.Error(T("Ar error occurred while creating the job:\n{0}", ex.Message));
                }
            }

            return(View(jobViewModel));
        }
        public void Update(string feature)
        {
            if (_processedFeatures.Contains(feature))
            {
                return;
            }

            _processedFeatures.Add(feature);

            Logger.Information("Updating feature: {0}", feature);

            // proceed with dependent features first, whatever the module it's in
            var dependencies = _extensionManager.AvailableFeatures()
                               .Where(f => String.Equals(f.Id, feature, StringComparison.OrdinalIgnoreCase))
                               .Where(f => f.Dependencies != null)
                               .SelectMany(f => f.Dependencies)
                               .ToList();

            foreach (var dependency in dependencies)
            {
                Update(dependency);
            }

            var migrations = GetDataMigrations(feature);

            // apply update methods to each migration class for the module
            foreach (var migration in migrations)
            {
                // copy the object for the Linq query
                var tempMigration = migration;

                // get current version for this migration
                var dataMigrationRecord = GetDataMigrationRecord(tempMigration);

                var current = 0;
                if (dataMigrationRecord != null)
                {
                    current = dataMigrationRecord.Version.Value;
                }

                try {
                    _transactionManager.RequireNew();

                    // do we need to call Create() ?
                    if (current == 0)
                    {
                        // try to resolve a Create method

                        var createMethod = GetCreateMethod(migration);
                        if (createMethod != null)
                        {
                            current = (int)createMethod.Invoke(migration, new object[0]);
                        }
                    }

                    var lookupTable = CreateUpgradeLookupTable(migration);

                    while (lookupTable.ContainsKey(current))
                    {
                        try {
                            Logger.Information("Applying migration for {0} from version {1}", feature, current);
                            current = (int)lookupTable[current].Invoke(migration, new object[0]);
                        }
                        catch (Exception ex) {
                            Logger.Error(ex, "An unexpected error occurred while applying migration on {0} from version {1}", feature, current);
                            throw;
                        }
                    }

                    // if current is 0, it means no upgrade/create method was found or succeeded
                    if (current == 0)
                    {
                        continue;
                    }
                    if (dataMigrationRecord == null)
                    {
                        _dataMigrationRepository.Create(new DataMigrationRecord {
                            Version = current, DataMigrationClass = migration.GetType().FullName
                        });
                    }
                    else
                    {
                        dataMigrationRecord.Version = current;
                    }
                }
                catch (Exception e) {
                    Logger.Error(e, "Error while running migration version {0} for {1}", current, feature);
                    _transactionManager.Cancel();
                }
            }
        }
 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     _transactionManager.Cancel();
 }
        /// <summary>
        /// Formato DateTimeField: 2009-06-15T13:45:30  yyyy-MM-ddThh:mm:ss NB: L’ora deve essere riferita all’ora di Greenwich
        /// </summary>
        /// <param name="eObj"></param>
        /// <param name="TheContentItem"></param>
        /// <returns></returns>
        private Response StoreNewContentItem(ExpandoObject eObj)
        {
            string tipoContent       = ((dynamic)eObj).ContentType;
            Int32  IdContentToModify = 0; // new content

            try {
                if ((Int32)(((dynamic)eObj).Id) > 0)
                {
                    IdContentToModify = (Int32)(((dynamic)eObj).Id);
                }
            }
            catch {
                // Fix per Username nullo
                if (tipoContent == "User")
                {
                    return(_utilsServices.GetResponse(ResponseType.Validation, "Missing user Id"));
                }
            }
            ContentItem NewOrModifiedContent;
            Response    rsp             = new Response();
            string      validateMessage = "";

            if (IdContentToModify > 0)
            {
                List <ContentItem> li = _orchardServices.ContentManager.GetAllVersions(IdContentToModify).ToList();
                if (li.Count() == 0)
                {
                    return(_utilsServices.GetResponse(ResponseType.Validation, "No content with this Id"));
                }
                else
                {
                    var typeSettings = li[0].TypeDefinition.Settings.TryGetModel <ContentTypeSettings>();
                    if (typeSettings.Draftable)
                    {
                        NewOrModifiedContent = _orchardServices.ContentManager.Get(IdContentToModify, VersionOptions.DraftRequired); // quando edito estraggo sempre il draftrequired (come in Orchard.Core.Contents.Controllers)
                    }
                    else
                    {
                        NewOrModifiedContent = _orchardServices.ContentManager.Get(IdContentToModify, VersionOptions.Latest);
                    }
                }
                if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.EditContent, NewOrModifiedContent))
                {
                    if (!_contentExtensionService.HasPermission(tipoContent, Methods.Post, NewOrModifiedContent))
                    {
                        return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                    }
                }
                validateMessage = ValidateMessage(NewOrModifiedContent, "Modified");
            }
            else
            {
                NewOrModifiedContent = _orchardServices.ContentManager.New(tipoContent);
                if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.EditContent, NewOrModifiedContent))
                {
                    if (!_contentExtensionService.HasPermission(tipoContent, Methods.Post))
                    {
                        return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                    }
                }
                _orchardServices.ContentManager.Create(NewOrModifiedContent, VersionOptions.Draft); // quando creo creo sempre in draft (come in Orchard.Core.Contents.Controllers), se non faccio il create poi non vengono salvati i field
                validateMessage = ValidateMessage(NewOrModifiedContent, "Created");
            }
            if (string.IsNullOrEmpty(validateMessage))
            {
                rsp = _contentExtensionService.StoreInspectExpando(eObj, NewOrModifiedContent);
            }
            else
            {
                rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
            }
            if (rsp.Success)
            {
                try {
                    string language = "";
                    try {
                        language = ((dynamic)eObj).Language;
                    }
                    catch { }
                    if (NewOrModifiedContent.As <LocalizationPart>() != null)
                    {
                        if (!string.IsNullOrEmpty(language))
                        {
                            NewOrModifiedContent.As <LocalizationPart>().Culture = _cultureManager.GetCultureByName(language);
                        }
                        NewOrModifiedContent.As <LocalizationPart>().MasterContentItem = NewOrModifiedContent;
                    }
                    validateMessage = ValidateMessage(NewOrModifiedContent, "");
                    if (string.IsNullOrEmpty(validateMessage) == false)
                    {
                        rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
                    }
                    if (NewOrModifiedContent.As <AutoroutePart>() != null)
                    {
                        dynamic data = new ExpandoObject();
                        data.DisplayAlias = ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias;
                        data.Id           = (Int32)(((dynamic)NewOrModifiedContent).Id);
                        data.ContentType  = ((dynamic)NewOrModifiedContent).ContentType;
                        rsp.Data          = data;
                    }
                }
                catch (Exception ex) {
                    rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                }
            }
            if (!rsp.Success)
            {
                _transactionManager.Cancel();
            }
            else
            {
                // forza il publish solo per i contenuti non draftable
                var typeSettings = NewOrModifiedContent.TypeDefinition.Settings.TryGetModel <ContentTypeSettings>();
                if ((typeSettings == null) || (typeSettings.Draftable == false))
                {
                    NewOrModifiedContent.VersionRecord.Published = false; //not draftable items may have this flag set to published, and that would mean that the .Publish would not actually be executed.
                    _orchardServices.ContentManager.Publish(NewOrModifiedContent);
                }
                // propaga l'evento Updated per il ContentItem
                var context = new UpdateContentContext(NewOrModifiedContent);
                Handlers.Invoke(handler => handler.Updated(context), Logger);

                foreach (var notifi in _notifier.List())
                {
                    if (notifi.Type == NotifyType.Error)
                    {
                        _transactionManager.Cancel();
                        rsp.Success = false;
                        rsp.Message = "Error on update";
                        Logger.Error(notifi.Message.ToString());
                        break;
                    }
                }
            }
            return(rsp);
        }
        public ActionResult PersonListDashboardPost(int id = 0)
        {
            if (!IsAuthorized())
            {
                return(new HttpUnauthorizedResult());
            }

            /*
             * The workflow you see below for content item editing is standard practice:
             * 1) Fetch existing item from the ContentManager or instantiate new one
             * 2) Create item if it's new. Important: the item should be created as Draft.
             * 3) Update
             * 4) Check for validity:
             *      - Cancel transaction if model state is invalid
             *      - Do nothing else if model state is valid
             */

            var item = GetItem(id);

            if (item == null)
            {
                return(new HttpNotFoundResult());
            }

            // If the item's id is 0 then it's not yet persisted; Create() actually persists the item.
            // The version should be Draft so any handler (e.g the one of Autoroute) that depends on the item's content
            // being set runs only when the item is already filled with data and published then.
            if (id == 0)
            {
                _contentManager.Create(item, VersionOptions.Draft);
            }

            // Notice that there's also a _contentManager.Remove(item) method you can use for removing content item.
            // Beware though that removals in Orchard are soft deletes: really nothing is deleted from the database.

            // Updating the item with the model binder through this controller from POST data. The method returns an
            // updated editor shape (that is filled out with the input the user gave) what we can use to display if there
            // were validation errors.
            var editorShape = _contentManager.UpdateEditor(item, this);

            // Here we were updating a content item from POST data with the model binder. This is the case if you take
            // user input and want to update an item with it. However you can directly modify a content item's parts'
            // data directly, by "casting" the item to a part, as following:
            //item.As<PersonListPart>().MaxCount = 5;
            //item.As<TitlePart>().Title = "Custom title"; It works with any other part too, of course!

            if (!ModelState.IsValid)
            {
                // This will prevent the item from saving. Otherwise if we alter a content item's parts' properties
                // those modifications are automatically saved.
                _transactionManager.Cancel();

                // The user will see the filled out form with validation errors emphasized
                return(PersonListDashboardShapeResult(item));
            }

            // Publish the item. This will also run all the handlers (e.g the one of Autoroute) that depend on the item's
            // content being set.
            _contentManager.Publish(item);

            // We use the notifier again and access the current user's data from the WorkContext again
            _orchardServices.Notifier.Information(
                T("{0}, the Person List item was successfully saved.", _orchardServices.WorkContext.CurrentUser.UserName));

            return(RedirectToAction("PersonListDashboard"));

            // NEXT STATION: After you're finished with this controller see the "filters" provided by MVC and how Orchard
            // extends this functionality in Filters/ResourceFilter.cs!
        }
        public bool AddRecords([FromBody] List <TranslationRecord> records)
        {
            try {
                if (records == null)
                {
                    Log.Error("TranslatorAPIController.AddRecords error - No data received in TranslationRecord list.");
                    return(false);
                }
                if (records.Where(r => string.IsNullOrWhiteSpace(r.Message) ||
                                  string.IsNullOrWhiteSpace(r.Language) ||
                                  string.IsNullOrWhiteSpace(r.ContainerName) ||
                                  string.IsNullOrWhiteSpace(r.ContainerType)).Any())
                {
                    Log.Error("TranslatorAPIController.AddRecords error - TranslationRecord not valid. At least one of these field is empty: Message, Language, ContainerName and ContainerType. Please verify if T(\"\") is present in your code because it causes an empty Message.");
                    return(false);
                }

                foreach (var record in records)
                {
                    var alreadyExistingRecords = _translatorServices.GetTranslations().Where(r => r.ContainerName == record.ContainerName &&
                                                                                             r.ContainerType == record.ContainerType &&
                                                                                             r.Context == record.Context &&
                                                                                             r.Message == record.Message &&
                                                                                             r.Language == record.Language);
                    var tryAddOrUpdateTranslation = true;
                    if (alreadyExistingRecords.Any())
                    {
                        // verifica maiuscole/minuscole del message
                        // aggiunto il for perchè nel caso in cui ci fosse più di una traduzione uguale
                        // con differenza di maiuscolo o minuscole deve  effettuare il controllo su tutte
                        foreach (var item in alreadyExistingRecords)
                        {
                            if (record.Message.Equals(item.Message, StringComparison.InvariantCulture))
                            {
                                tryAddOrUpdateTranslation = false;
                                break;
                            }
                        }
                    }
                    if (tryAddOrUpdateTranslation)
                    {
                        bool success = _translatorServices.TryAddOrUpdateTranslation(record);
                        if (!success)
                        {
                            _transactionManager.Cancel();
                            Log.Error("TranslatorAPIController.AddRecords error - Id: {0}, Message: {1}", record.Id, record.Message);
                            return(false);
                        }
                    }
                }

                var folderList = records.GroupBy(g => new { g.ContainerName, g.ContainerType })
                                 .Select(g => new { g.Key.ContainerName, g.Key.ContainerType });

                if (folderList.Any(f => !_validContainerTypes.Contains(f.ContainerType)))
                {
                    Log.Error("TranslatorAPIController.AddRecords error - Some record has invalid ContainerType");
                    return(false);
                }
                foreach (var folder in folderList)
                {
                    var folderType = ElementToTranslate.Module;
                    switch (folder.ContainerType)
                    {
                    case "M":
                        folderType = ElementToTranslate.Module;
                        break;

                    case "T":
                        folderType = ElementToTranslate.Theme;
                        break;

                    case "A":
                        folderType = ElementToTranslate.Tenant;
                        break;

                    case "U":
                        folderType = ElementToTranslate.Undefined;
                        break;

                    case "W":
                        folderType = ElementToTranslate.OrchardModule;
                        break;

                    case "X":
                        folderType = ElementToTranslate.OrchardTheme;
                        break;

                    case "Y":
                        folderType = ElementToTranslate.OrchardCore;
                        break;

                    case "Z":
                        folderType = ElementToTranslate.OrchardFramework;
                        break;
                    }
                    _translatorServices.EnableFolderTranslation(folder.ContainerName, folderType);
                }

                return(true);
            } catch (Exception ex) {
                _transactionManager.Cancel();
                Log.Error(ex, "TranslatorAPIController.AddRecords error.");
                return(false);
            }
        }
예제 #25
0
        public ActionResult Save(string returnUrl)
        {
            var editModel   = new ViewModels.QuestionnaireWithResultsViewModel();
            var currentUser = _orchardServices.WorkContext.CurrentUser;

            try {
                if (TryUpdateModel(editModel, _prefix))
                {
                    TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                    TempData["HasAcceptedTerms"]      = editModel.HasAcceptedTerms;

                    QuestionnairesPartSettingVM questionnairePartSettings = null;
                    var questionnaire = _orchardServices.ContentManager.Get(editModel.Id);
                    if (questionnaire != null && questionnaire.As <QuestionnairePart>() != null)
                    {
                        questionnairePartSettings = questionnaire.As <QuestionnairePart>().Settings.GetModel <QuestionnairesPartSettingVM>();
                    }

                    // verifica se il questionario può essere compilato una volta sola ed è già stato compilato
                    bool canBeFilled = true;
                    var  questionnaireModuleSettings = _orchardServices.WorkContext.CurrentSite.As <QuestionnaireModuleSettingsPart>();
                    if (questionnaireModuleSettings.Disposable)
                    {
                        if (currentUser == null || (questionnairePartSettings != null && questionnairePartSettings.ForceAnonymous))
                        {
                            var cookie = Request.Cookies["Questionnaires"];
                            if (cookie != null)
                            {
                                var ids = cookie.Value;
                                if (ids.Contains("," + editModel.Id + ","))
                                {
                                    canBeFilled = false;
                                }
                            }
                        }
                    }
                    if (canBeFilled)
                    {
                        canBeFilled = _questionnairesServices.Save(editModel, currentUser, ControllerContext.HttpContext.Session.SessionID);
                    }
                    //if (editModel.UseRecaptcha && !_captchaServices.IsCaptchaValid(_orchardServices.WorkContext.HttpContext.Request.Form, _orchardServices.WorkContext.HttpContext.Request.UserHostAddress)) {
                    //    throw new Exception("Invalid captcha!");
                    //}

                    //if (editModel.MustAcceptTerms && !editModel.HasAcceptedTerms) {
                    //    TempData["QuestError"] = T("Please, accept our terms and conditions!");
                    //} else {
                    //    foreach (var q in editModel.QuestionsWithResults) {
                    //        if (q.QuestionType == QuestionType.OpenAnswer) {
                    //            if (!String.IsNullOrWhiteSpace(q.OpenAnswerAnswerText)) {
                    //                var userAnswer = new UserAnswersRecord();
                    //                userAnswer.AnswerText = q.OpenAnswerAnswerText;
                    //                userAnswer.QuestionText = q.Question;
                    //                userAnswer.QuestionRecord_Id = q.Id;
                    //                userAnswer.User_Id = currentUser.Id;
                    //                userAnswer.QuestionnairePartRecord_Id = editModel.Id;
                    //                userAnswer.SessionID = ControllerContext.HttpContext.Session.SessionID;
                    //                _questionnairesServices.CreateUserAnswers(userAnswer);
                    //            }
                    //        } else if (q.QuestionType == QuestionType.SingleChoice) {
                    //            if (q.SingleChoiceAnswer > 0) {
                    //                var userAnswer = new UserAnswersRecord();
                    //                userAnswer.AnswerRecord_Id = q.SingleChoiceAnswer;
                    //                userAnswer.AnswerText = _questionnairesServices.GetAnswer(q.SingleChoiceAnswer).Answer;
                    //                userAnswer.QuestionRecord_Id = q.Id;
                    //                userAnswer.User_Id = currentUser.Id;
                    //                userAnswer.QuestionText = q.Question;
                    //                userAnswer.QuestionnairePartRecord_Id = editModel.Id;
                    //                userAnswer.SessionID = ControllerContext.HttpContext.Session.SessionID;
                    //                _questionnairesServices.CreateUserAnswers(userAnswer);
                    //            }
                    //        } else if (q.QuestionType == QuestionType.MultiChoice) {
                    //            var answerList = q.AnswersWithResult.Where(w => w.Answered);
                    //            foreach (var a in answerList) {
                    //                var userAnswer = new UserAnswersRecord();
                    //                userAnswer.AnswerRecord_Id = a.Id;
                    //                userAnswer.AnswerText = _questionnairesServices.GetAnswer(a.Id).Answer;
                    //                userAnswer.QuestionRecord_Id = q.Id;
                    //                userAnswer.User_Id = currentUser.Id;
                    //                userAnswer.QuestionText = q.Question;
                    //                userAnswer.QuestionnairePartRecord_Id = editModel.Id;
                    //                userAnswer.SessionID = ControllerContext.HttpContext.Session.SessionID;
                    //                _questionnairesServices.CreateUserAnswers(userAnswer);
                    //            }
                    //        }
                    //    }
                    if (canBeFilled == false)
                    {
                        TempData["QuestError"]       = T("Sorry, you already submitted this questionnaire.");
                        TempData["AlreadySubmitted"] = true;
                    }
                    else
                    {
                        TempData["QuestSuccess"] = T("Thank you for submitting your feedback.");
                    }
                    //var content = _orchardServices.ContentManager.Get(editModel.Id);
                    //_workflowManager.TriggerEvent("QuestionnaireSubmitted", content, () => new Dictionary<string, object> { { "Content", content } });


                    //}
                }
                else
                {
                    TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                    _transactionManager.Cancel();
                    var errors = ModelState.Values.Where(w => w.Errors.Count() > 0).Select(s => s.Errors.First().ErrorMessage);
                    TempData["QuestError"] = String.Join("\r\n", errors);
                }
            } catch (Exception ex) {
                TempData["QuestUpdatedEditModel"] = editModel; // devo avere modo di fare non perdere le risposte date finora!!!
                _transactionManager.Cancel();
                TempData["QuestError"] = T(ex.Message) + ex.StackTrace;
            }
            return(this.RedirectLocal(returnUrl, "~/"));
        }
예제 #26
0
        private void BatchedInvoke(RecipeExecutionContext context, string batchLabel, Action <string, string, XElement, ImportContentSession, IDictionary <string, XElement> > contentItemAction)
        {
            var importContentSession = new ImportContentSession(_tomeltServices.ContentManager);

            // Populate local dictionary with elements and their ids.
            var elementDictionary = CreateElementDictionary(context.RecipeStep.Step);

            // Populate import session with all identities to be imported.
            foreach (var identity in elementDictionary.Keys)
            {
                importContentSession.Set(identity, elementDictionary[identity].Name.LocalName);
            }

            // Determine if the import is to be batched in multiple transactions.
            var batchSize  = GetBatchSizeForDataStep(context.RecipeStep.Step);
            var startIndex = 0;
            var itemIndex  = 0;

            Logger.Debug("Using batch size {0} for '{1}'.", batchSize, batchLabel);

            try {
                while (startIndex < elementDictionary.Count)
                {
                    Logger.Debug("Batch '{0}' execution starting at index {1}.", batchLabel, startIndex);
                    importContentSession.InitializeBatch(startIndex, batchSize);

                    // The session determines which items are included in the current batch
                    // so that dependencies can be managed within the same transaction.
                    var nextIdentity = importContentSession.GetNextInBatch();
                    while (nextIdentity != null)
                    {
                        var itemId            = "";
                        var nextIdentityValue = nextIdentity.ToString();
                        if (elementDictionary[nextIdentityValue].HasAttributes)
                        {
                            itemId = elementDictionary[nextIdentityValue].FirstAttribute.Value;
                        }
                        Logger.Information("Handling content item '{0}' (item {1}/{2} of '{3}').", itemId, itemIndex + 1, elementDictionary.Count, batchLabel);
                        try {
                            contentItemAction(itemId, nextIdentityValue, elementDictionary[nextIdentityValue], importContentSession, elementDictionary);
                        }
                        catch (Exception ex) {
                            Logger.Error(ex, "Error while handling content item '{0}' (item {1}/{2} of '{3}').", itemId, itemIndex + 1, elementDictionary.Count, batchLabel);
                            throw;
                        }
                        itemIndex++;
                        nextIdentity = importContentSession.GetNextInBatch();
                    }

                    startIndex += batchSize;

                    // Create a new transaction for each batch.
                    if (startIndex < elementDictionary.Count)
                    {
                        _transactionManager.RequireNew();
                    }

                    Logger.Debug("Finished batch '{0}' starting at index {1}.", batchLabel, startIndex);
                }
            }
            catch (Exception) {
                // Ensure a failed batch is rolled back.
                _transactionManager.Cancel();
                throw;
            }
        }
        // <Data />
        // Import Data
        public void ExecuteRecipeStep(RecipeContext recipeContext)
        {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Data", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var importContentSession = new ImportContentSession(_orchardServices.ContentManager);

            // Populate local dictionary with elements and their ids
            var elementDictionary = CreateElementDictionary(recipeContext.RecipeStep.Step);

            //Populate import session with all identities to be imported
            foreach (var identity in elementDictionary.Keys)
            {
                Logger.Debug("Importing {0}", identity);
                importContentSession.Set(identity, elementDictionary[identity].Name.LocalName);
            }

            //Determine if the import is to be batched in multiple transactions
            var startIndex = 0;
            int batchSize  = GetBatchSizeForDataStep(recipeContext.RecipeStep.Step);

            //Run the import
            try {
                while (startIndex < elementDictionary.Count)
                {
                    importContentSession.InitializeBatch(startIndex, batchSize);

                    //the session determines which items are included in the current batch
                    //so that dependencies can be managed within the same transaction
                    var nextIdentity = importContentSession.GetNextInBatch();
                    while (nextIdentity != null)
                    {
                        if (!string.IsNullOrEmpty(recipeContext.ExecutionId) && elementDictionary[nextIdentity.ToString()].HasAttributes)
                        {
                            var itemId = elementDictionary[nextIdentity.ToString()].FirstAttribute.Value;
                            _recipeJournal.WriteJournalEntry(recipeContext.ExecutionId, T("Data: Importing {0}.", itemId).Text);
                        }
                        _orchardServices.ContentManager.Import(
                            elementDictionary[nextIdentity.ToString()],
                            importContentSession);
                        nextIdentity = importContentSession.GetNextInBatch();
                    }

                    startIndex += batchSize;

                    //Create a new transaction for each batch
                    if (startIndex < elementDictionary.Count)
                    {
                        _transactionManager.RequireNew();
                    }
                }
            }
            catch (Exception) {
                //Ensure a failed batch is rolled back
                _transactionManager.Cancel();
                throw;
            }

            recipeContext.Executed = true;
        }
예제 #28
0
        public ActionResult ListPOST(ContentOptions options, IEnumerable <int> itemIds, string returnUrl)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageTemplates, T("Not authorized to manage templates")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (itemIds != null)
            {
                var checkedContentItems = _contentManager.GetMany <ContentItem>(itemIds, VersionOptions.Latest, QueryHints.Empty);
                switch (options.BulkAction)
                {
                case ContentsBulkAction.None:
                    break;

                case ContentsBulkAction.PublishNow:
                    foreach (var item in checkedContentItems)
                    {
                        if (!Services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected content.")))
                        {
                            _transactionManager.Cancel();
                            return(new HttpUnauthorizedResult());
                        }

                        _contentManager.Publish(item);
                    }
                    Services.Notifier.Success(T("Content successfully published."));
                    break;

                case ContentsBulkAction.Unpublish:
                    foreach (var item in checkedContentItems)
                    {
                        if (!Services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected content.")))
                        {
                            _transactionManager.Cancel();
                            return(new HttpUnauthorizedResult());
                        }

                        _contentManager.Unpublish(item);
                    }
                    Services.Notifier.Success(T("Content successfully unpublished."));
                    break;

                case ContentsBulkAction.Remove:
                    foreach (var item in checkedContentItems)
                    {
                        if (!Services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected content.")))
                        {
                            _transactionManager.Cancel();
                            return(new HttpUnauthorizedResult());
                        }

                        _contentManager.Remove(item);
                    }
                    Services.Notifier.Success(T("Content successfully removed."));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(this.RedirectLocal(returnUrl, () => RedirectToAction("List")));
        }
예제 #29
0
        // <Data />
        // Import Data.
        public override void Execute(RecipeExecutionContext context)
        {
            var importContentSession = new ImportContentSession(_orchardServices.ContentManager);

            // Populate local dictionary with elements and their ids.
            var elementDictionary = CreateElementDictionary(context.RecipeStep.Step);

            // Populate import session with all identities to be imported.
            foreach (var identity in elementDictionary.Keys)
            {
                importContentSession.Set(identity, elementDictionary[identity].Name.LocalName);
            }

            // Determine if the import is to be batched in multiple transactions.
            var startIndex = 0;
            var itemIndex  = 0;
            var batchSize  = GetBatchSizeForDataStep(context.RecipeStep.Step);

            Logger.Debug("Using batch size {0}.", batchSize);

            // Run the import.
            try {
                while (startIndex < elementDictionary.Count)
                {
                    Logger.Debug("Importing batch starting at index {0}.", startIndex);
                    importContentSession.InitializeBatch(startIndex, batchSize);

                    // The session determines which items are included in the current batch
                    // so that dependencies can be managed within the same transaction.
                    var nextIdentity = importContentSession.GetNextInBatch();
                    while (nextIdentity != null)
                    {
                        var itemId = "";
                        if (elementDictionary[nextIdentity.ToString()].HasAttributes)
                        {
                            itemId = elementDictionary[nextIdentity.ToString()].FirstAttribute.Value;
                        }
                        Logger.Information("Importing data item '{0}' (item {1}/{2}).", itemId, itemIndex + 1, elementDictionary.Count);
                        try {
                            _orchardServices.ContentManager.Import(
                                elementDictionary[nextIdentity.ToString()],
                                importContentSession);
                        }
                        catch (Exception ex) {
                            Logger.Error(ex, "Error while importing data item '{0}'.", itemId);
                            throw;
                        }
                        itemIndex++;
                        nextIdentity = importContentSession.GetNextInBatch();
                    }

                    startIndex += batchSize;

                    // Create a new transaction for each batch.
                    if (startIndex < elementDictionary.Count)
                    {
                        _transactionManager.RequireNew();
                    }

                    Logger.Debug("Finished importing batch starting at index {0}.", startIndex);
                }
            }
            catch (Exception) {
                // Ensure a failed batch is rolled back.
                _transactionManager.Cancel();
                throw;
            }
        }
예제 #30
0
 public void OnException(ExceptionContext filterContext)
 {
     _transactionManager.Cancel();
 }
        protected override DriverResult Editor(SmsContactPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            View_SmsVM oldviewModel = new View_SmsVM();

            updater.TryUpdateModel(oldviewModel, Prefix, null, null);
            bool error = false;

            _transaction.Demand();
            foreach (View_SmsVM_element vmel in oldviewModel.Elenco)
            {
                if ((vmel.Delete || string.IsNullOrEmpty(vmel.Sms)) && vmel.Id > 0)
                {
                    CommunicationSmsRecord cmr = _repoSms.Fetch(x => x.Id == vmel.Id).FirstOrDefault();
                    _repoSms.Delete(cmr);
                }
                else
                if (!vmel.Delete)
                {
                    if (!string.IsNullOrEmpty(vmel.Sms))
                    {
                        if (_repoSms.Fetch(x => x.Sms == vmel.Sms && x.Prefix == vmel.Prefix && x.Id != vmel.Id).Count() > 0)
                        {
                            error = true;
                            updater.AddModelError("Error", T("Sms can't be assigned is linked to other contact"));
                        }
                    }
                    if (vmel.Id > 0)
                    {
                        CommunicationSmsRecord cmr = _repoSms.Fetch(x => x.Id == vmel.Id).FirstOrDefault();
                        if (cmr.Sms != vmel.Sms || cmr.Prefix != vmel.Prefix || cmr.Validated != vmel.Validated ||
                            cmr.AccettatoUsoCommerciale != vmel.AccettatoUsoCommerciale ||
                            cmr.AutorizzatoTerzeParti != vmel.AutorizzatoTerzeParti)
                        {
                            cmr.Sms       = vmel.Sms;
                            cmr.Prefix    = vmel.Prefix;
                            cmr.Validated = vmel.Validated;
                            cmr.AccettatoUsoCommerciale = vmel.AccettatoUsoCommerciale;
                            cmr.AutorizzatoTerzeParti   = vmel.AutorizzatoTerzeParti;
                            cmr.DataModifica            = DateTime.Now;
                            _repoSms.Update(cmr);
                        }
                    }
                    else
                    {
                        View_SmsVM_element     vm  = new View_SmsVM_element();
                        CommunicationSmsRecord cmr = new CommunicationSmsRecord();
                        _mapper.Map <View_SmsVM_element, CommunicationSmsRecord>(vm, cmr);
                        cmr.Sms       = vmel.Sms;
                        cmr.Validated = vmel.Validated;
                        cmr.AccettatoUsoCommerciale = vmel.AccettatoUsoCommerciale;
                        cmr.AutorizzatoTerzeParti   = vmel.AutorizzatoTerzeParti;
                        cmr.Prefix = vmel.Prefix;
                        cmr.SmsContactPartRecord_Id = part.Id;
                        _repoSms.Create(cmr);
                    }
                }
            }
            if (error == true)
            {
                _transaction.Cancel();
            }
            else
            {
                _repoSms.Flush();
            }
            return(Editor(part, shapeHelper));
        }