Exemplo n.º 1
0
        private Response StoreNewContentItem(ExpandoObject eObj, ContentItem TheContentItem)
        {
            string tipoContent       = ((dynamic)eObj).ContentType;
            Int32  IdContentToModify = 0; // new content

            // NewContent.As<TitlePart>.Title = "Creazione";
            try {
                if ((Int32)(((dynamic)eObj).Id) > 0)
                {
                    IdContentToModify = (Int32)(((dynamic)eObj).Id);
                }
            }
            catch {
            }
            ContentItem NewOrModifiedContent;
            Response    rsp             = new Response();
            string      validateMessage = "";

            if (IdContentToModify > 0)
            {
                NewOrModifiedContent = _orchardServices.ContentManager.Get(IdContentToModify, VersionOptions.Latest);
                //if (NewOrModifiedContent==null){
                //    var pippo = _orchardServices.ContentManager.GetAllVersions(IdContentToModify);
                //}
                //  endif IdContentToModify).Where(x=>x.VersionRecord.Id>);
                if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.EditContent, 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))
                {
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
                _orchardServices.ContentManager.Create(NewOrModifiedContent, VersionOptions.Draft);// se non faccio il create poi non vengono salvati i field
                validateMessage = ValidateMessage(NewOrModifiedContent, "Created");
            }

            if (string.IsNullOrEmpty(validateMessage))
            {
                rsp = _contentExtensionsServices.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))
                    {
                        _orchardServices.ContentManager.Create(NewOrModifiedContent, VersionOptions.DraftRequired);
                    }
                    else
                    {
                        rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
                    }

                    // _localizationService.SetContentCulture(NewContent, language);
                    if (((dynamic)NewOrModifiedContent).AutoroutePart != null)
                    {
                        ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias = _autorouteService.Value.GenerateAlias(((dynamic)NewOrModifiedContent).AutoroutePart);
                        _autorouteService.Value.ProcessPath(((dynamic)NewOrModifiedContent).AutoroutePart);
                        _autorouteService.Value.PublishAlias(((dynamic)NewOrModifiedContent).AutoroutePart);
                        dynamic data = new ExpandoObject();
                        data.DisplayAlias = ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias;
                        rsp.Data          = data;
                    }
                    //   Handlers.Invoke(handler => handler.Updating(context), Logger);
                }
                catch (Exception ex) {
                    try {
                        _orchardServices.ContentManager.Remove(NewOrModifiedContent);
                    }
                    catch (Exception ex2) {
                        rsp = _utilsServices.GetResponse(ResponseType.None, ex2.Message);
                    }
                    rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                }
            }
            else
            {
                try {
                    _orchardServices.ContentManager.Remove(NewOrModifiedContent);
                }
                catch (Exception ex2) {
                    rsp = _utilsServices.GetResponse(ResponseType.None, ex2.Message);
                }
            }
            //if (this.ExternalContentCreated != null) {
            //    this.ExternalContentCreated(this, new EventArgs());
            //}

            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)
        {
            // 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);
        }