Example #1
0
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // don't touch temp data if there's no work to perform
            if (!_notifier.List().Any())
            {
                return;
            }

            var tempData = filterContext.Controller.TempData;

            // initialize writer with current data
            var sb = new StringBuilder();

            if (tempData.ContainsKey(TempDataMessages))
            {
                sb.Append(tempData[TempDataMessages]);
            }

            // accumulate messages, one line per message
            foreach (var entry in _notifier.List())
            {
                sb.Append(Convert.ToString(entry.Type))
                .Append(':')
                .AppendLine(entry.Message.ToString())
                .AppendLine("-");
            }

            // assign values into temp data
            // string data type used instead of complex array to be session-friendly
            tempData[TempDataMessages] = sb.ToString();
        }
Example #2
0
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!notifier.List().Any())
            {
                return;
            }

            var tempData = filterContext.Controller.TempData;

            var sb = new StringBuilder();

            if (tempData.ContainsKey(TempDataMessages))
            {
                sb.Append(tempData[TempDataMessages]);
            }

            foreach (var entry in notifier.List())
            {
                sb.Append(Convert.ToString(entry.Type))
                .Append(':')
                .AppendLine(entry.Message)
                .AppendLine("-");
            }

            tempData[TempDataMessages] = sb.ToString();
        }
        public void InstallPackage(string packageId, string location)
        {
            try {
                _packageManager.Install(packageId, Version, Path.GetFullPath(location), ApplicationPath);

                foreach (var message in _notifier.List())
                {
                    Context.Output.WriteLine(message.Message);
                }
            }
            catch (Exception e) {
                // Exceptions area thrown by NuGet as error messages
                Context.Output.WriteLine(HttpUtility.HtmlDecode(T("Could not install the package: {0}", e.Message).Text));
            }
        }
Example #4
0
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var messageEntries = _notifier.List();

            _existingEntries = _existingEntries ?? new List <NotifyEntry>();

            // Don't touch temp data if there's no work to perform.
            if (!messageEntries.Any() && !_existingEntries.Any())
            {
                return;
            }

            // Assign values to the Items collection instead of TempData and
            // combine any existing entries added by the previous request with new ones.

            _existingEntries = messageEntries.Concat(_existingEntries).ToList();

            // Result is not a view, so assume a redirect and assign values to TemData.
            // String data type used instead of complex array to be session-friendly.
            if (!(filterContext.Result is ViewResult) && _existingEntries.Any())
            {
                _httpContextAccessor.HttpContext.Response.Cookies.Append(CookiePrefix, SerializeNotifyEntry(_existingEntries.ToArray()), new CookieOptions {
                    HttpOnly = true, Path = _tenantPath
                });
            }
        }
Example #5
0
        private void OnHandlerExecuted(FilterContext filterContext)
        {
            var messageEntries = _notifier.List().ToArray();

            // Don't touch temp data if there's no work to perform.
            if (messageEntries.Length == 0 && _existingEntries.Length == 0)
            {
                return;
            }

            // Assign values to the Items collection instead of TempData and
            // combine any existing entries added by the previous request with new ones.

            _existingEntries = messageEntries.Concat(_existingEntries).Distinct(new NotifyEntryComparer(_htmlEncoder)).ToArray();
            object result = filterContext is ActionExecutedContext ace ? ace.Result : ((PageHandlerExecutedContext)filterContext).Result;

            // Result is not a view, so assume a redirect and assign values to TemData.
            // String data type used instead of complex array to be session-friendly.
            if (!(result is ViewResult || result is PageResult) && _existingEntries.Length > 0)
            {
                filterContext.HttpContext.Response.Cookies.Append(CookiePrefix, SerializeNotifyEntry(_existingEntries), new CookieOptions {
                    HttpOnly = true, Path = _tenantPath
                });
            }
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Don't touch temp data if there's no work to perform.
            if (!_notifier.List().Any())
            {
                return;
            }

            var messageEntries = _notifier.List().ToList();

            if (filterContext.Result is ViewResultBase)
            {
                // Assign values to the Items collection instead of TempData and
                // combine any existing entries added by the previous request with new ones.
                var existingEntries = filterContext.HttpContext.Items[TempDataMessages] as IList <NotifyEntry> ?? new List <NotifyEntry>();
                messageEntries = messageEntries.Concat(existingEntries).ToList();
                filterContext.HttpContext.Items[TempDataMessages] = messageEntries;

                return;
            }

            var tempData = filterContext.Controller.TempData;

            // Initialize writer with current data.
            var sb = new StringBuilder();

            if (tempData.ContainsKey(TempDataMessages))
            {
                sb.Append(tempData[TempDataMessages]);
            }

            // Accumulate messages, one line per message.
            foreach (var entry in messageEntries)
            {
                sb.Append(Convert.ToString(entry.Type))
                .Append(':')
                .AppendLine(entry.Message.ToString())
                .AppendLine("-");
            }

            // Result is not a view, so assume a redirect and assign values to TemData.
            // String data type used instead of complex array to be session-friendly.
            tempData[TempDataMessages] = sb.ToString();
        }
        public void Enable(params string[] featureNames)
        {
            Context.Output.WriteLine(T("Enabling features {0}", string.Join(",", featureNames)));
            var listAvailableFeatures = false;
            var featuresToEnable      = new List <string>();
            var availableFeatures     = _featureManager.GetAvailableFeatures().Select(x => x.Id).OrderBy(x => x).ToArray();

            foreach (var featureName in featureNames)
            {
                if (availableFeatures.Contains(featureName, StringComparer.OrdinalIgnoreCase))
                {
                    featuresToEnable.Add(featureName);
                }
                else
                {
                    Context.Output.WriteLine(T("Could not find feature {0}", featureName));
                    listAvailableFeatures = true;
                }
            }
            if (featuresToEnable.Count != 0)
            {
                _moduleService.EnableFeatures(featuresToEnable, true);
                foreach (var entry in _notifier.List())
                {
                    Context.Output.WriteLine(entry.Message);
                }
            }
            else
            {
                Context.Output.WriteLine(T("Could not enable features: {0}", string.Join(",", featureNames)));
                listAvailableFeatures = true;
            }
            if (listAvailableFeatures)
            {
                Context.Output.WriteLine(T("Available features are : {0}", string.Join(",", availableFeatures)));
            }
        }
        /// <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);
        }
        /// <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);
        }