public CommentPartHandler( IRepository<CommentPartRecord> commentsRepository, IContentManager contentManager, ICommentService commentService ) { Filters.Add(StorageFilter.For(commentsRepository)); OnLoading<CommentPart>((context, comment) => { comment.CommentedOnContentItemField.Loader( item => contentManager.Get(comment.CommentedOn) ); comment.CommentedOnContentItemMetadataField.Loader( item => contentManager.GetItemMetadata(comment.CommentedOnContentItem) ); }); OnRemoving<CommentPart>((context, comment) => { foreach(var response in contentManager.Query<CommentPart, CommentPartRecord>().Where(x => x.RepliedOn == comment.Id).List()) { contentManager.Remove(response.ContentItem); } }); // keep CommentsPart.Count in sync OnPublished<CommentPart>((context, part) => commentService.ProcessCommentsCount(part.CommentedOn)); OnUnpublished<CommentPart>((context, part) => commentService.ProcessCommentsCount(part.CommentedOn)); OnVersioned<CommentPart>((context, part, newVersionPart) => commentService.ProcessCommentsCount(newVersionPart.CommentedOn)); OnRemoved<CommentPart>((context, part) => commentService.ProcessCommentsCount(part.CommentedOn)); OnIndexing<CommentPart>((context, commentPart) => context.DocumentIndex .Add("commentText", commentPart.Record.CommentText)); }
public TermsPartHandler( IContentDefinitionManager contentDefinitionManager, IRepository<TermsPartRecord> repository, ITaxonomyService taxonomyService, IContentManager contentManager) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; Filters.Add(StorageFilter.For(repository)); OnPublished<TermsPart>((context, part) => RecalculateCount(contentManager, taxonomyService, part)); OnUnpublished<TermsPart>((context, part) => RecalculateCount(contentManager, taxonomyService, part)); OnRemoved<TermsPart>((context, part) => RecalculateCount(contentManager, taxonomyService, part)); // tells how to load the field terms on demand OnLoaded<TermsPart>((context, part) => { foreach(var field in part.ContentItem.Parts.SelectMany(p => p.Fields).OfType<TaxonomyField>()) { var tempField = field.Name; var fieldTermRecordIds = part.Record.Terms.Where(t => t.Field == tempField).Select(tci => tci.TermRecord.Id); field.Terms.Loader(value => fieldTermRecordIds.Select(id => _contentManager.Get<TermPart>(id))); } }); OnIndexing<TermsPart>( (context, part) => { foreach (var term in part.Terms) { var value = context.ContentManager.Get(term.TermRecord.Id).As<TitlePart>().Title; context.DocumentIndex.Add(term.Field, value).Analyze(); context.DocumentIndex.Add(term.Field + "-id", term.Id).Store(); } }); }
public CommentPartHandler( IRepository<CommentPartRecord> commentsRepository, IContentManager contentManager) { Filters.Add(StorageFilter.For(commentsRepository)); OnLoading<CommentPart>((context, comment) => { comment.CommentedOnContentItemField.Loader( item => contentManager.Get(comment.CommentedOn) ); comment.CommentedOnContentItemMetadataField.Loader( item => contentManager.GetItemMetadata(comment.CommentedOnContentItem) ); }); OnRemoving<CommentPart>((context, comment) => { foreach(var response in contentManager.Query<CommentPart, CommentPartRecord>().Where(x => x.RepliedOn == comment.Id).List()) { contentManager.Remove(response.ContentItem); } }); OnIndexing<CommentPart>((context, commentPart) => context.DocumentIndex .Add("commentText", commentPart.Record.CommentText)); }
public CustomerPartHandler( IContentManager contentManager, ICustomersService customersService, IRepository<CustomerPartRecord> repository ) { Filters.Add(StorageFilter.For(repository)); OnActivated<CustomerPart>((context, part) => { // User field part._user.Loader(user => contentManager.Get<IUser>(part.UserId)); part._user.Setter(user => { part.UserId = (user != null ? user.Id : 0); return user; }); // Default address field part._defaultAddress.Loader(address => customersService.GetAddress(part.DefaultAddressId)); part._defaultAddress.Setter(address => { part.DefaultAddressId = (address != null ? address.Id : 0); return address; }); // Addresses field part._addresses.Loader(addresses => customersService.GetAddressesForCustomer(part)); }); OnRemoving<CustomerPart>((context, part) => { foreach (var address in part.Addresses) { contentManager.Remove(address.ContentItem); } }); }
public ContentMenuItemPartHandler(IContentManager contentManager, IRepository<ContentMenuItemPartRecord> repository) { _contentManager = contentManager; Filters.Add(new ActivatingFilter<ContentMenuItemPart>("ContentMenuItem")); Filters.Add(StorageFilter.For(repository)); OnLoading<ContentMenuItemPart>((context, part) => part._content.Loader(p => contentManager.Get(part.Record.ContentMenuItemRecord.Id))); }
public NotificationBatchPartHandler( IContentManager contentManager, Lazy<IRoleService> roleServiceLazy, Lazy<IRepository<UserRolesPartRecord>> userRolesRepositoryLazy) { OnActivated<NotificationBatchPart>((context, part) => { part.RecipientsTypeField.Loader(() => { var recipientsType = part.Retrieve<string>("RecipientsType"); if (string.IsNullOrEmpty(recipientsType)) return NotificationBatchRecipientsType.Role; return (NotificationBatchRecipientsType)Enum.Parse(typeof(NotificationBatchRecipientsType), recipientsType); }); part.RecipientsTypeField.Setter(recipientsType => { part.Store("RecipientsType", recipientsType.ToString()); return recipientsType; }); part.AvailableRolesField.Loader(() => roleServiceLazy.Value.GetRoles()); part.RecipientListField.Loader(() => contentManager.Get(part.RecipientListId)); part.AvailableRecipientListsField.Loader(() => contentManager.Query(Constants.RecipientListContentType).List()); part.RecipientListField.Setter(recipientsList => { part.RecipientListId = recipientsList != null ? recipientsList.ContentItem.Id : 0; return recipientsList; }); part.ActualRecipientIdsField.Loader(() => { IEnumerable<int> recipientIds; switch (part.RecipientsType) { case NotificationBatchRecipientsType.Role: recipientIds = userRolesRepositoryLazy.Value.Table .Where(record => record.Role.Id == part.RecipientsRoleId) .Select(record => record.UserId); break; case NotificationBatchRecipientsType.RecipientList: recipientIds = part.RecipientList.As<NotificationRecipientsPart>().RecipientIds; break; case NotificationBatchRecipientsType.AdhocRecipients: recipientIds = part.As<NotificationRecipientsPart>().RecipientIds; break; default: throw new InvalidOperationException("Not supported recipient type."); } return recipientIds; }); part.ActualRecipientsField.Loader(() => contentManager.GetMany<IUser>(part.ActualRecipientIds, VersionOptions.Published, new QueryHints().ExpandParts<UserPart>())); }); }
public ContentMenuItemPartHandler(IContentManager contentManager, IRepository<ContentMenuItemPartRecord> repository) { _contentManager = contentManager; Filters.Add(new ActivatingFilter<ContentMenuItemPart>("ContentMenuItem")); Filters.Add(StorageFilter.For(repository)); OnLoading<ContentMenuItemPart>((context, part) => part._content.Loader(p => { if (part.ContentItemId != null) { return contentManager.Get(part.ContentItemId.Value); } return null; })); }
public OfflinePaymentSettingsPartHandler(IContentManager contentManager) { _contentManager = contentManager; Filters.Add(new ActivatingFilter<OfflinePaymentSettingsPart>("Site")); OnLoading<OfflinePaymentSettingsPart>((context, part) => part._content.Loader(p => { if (part.ContentItemId != null) { return contentManager.Get(part.ContentItemId.Value); } return null; })); }
public ProductPart GetProduct(int productId) { return(_contentManager.Get <ProductPart>(productId)); }
public QueryPart GetQuery(int id) { return(_contentManager.Get <QueryPart>(id)); }
private ContentItem GetItem(int id) => // Instantiating a new content item of type PersonList. We'll use this new item object that only resides in // the memory for now (nothing persisted yet) to build an editor shape (it's form). id == 0 ? _contentManager.New("PersonList") : _contentManager.Get(id); // Fetching an existing content item with the id
public void Sweep() { var awaiting = _awaitingActivityRepository.Table.Where(x => x.ActivityRecord.Name == "Timer").ToList(); foreach (var action in awaiting) { try { var contentItem = action.WorkflowRecord.ContentItemRecord != null?_contentManager.Get(action.WorkflowRecord.ContentItemRecord.Id, VersionOptions.Latest) : null; var tokens = new Dictionary <string, object> { { "Content", contentItem } }; var workflowState = FormParametersHelper.FromJsonString(action.WorkflowRecord.State); workflowState.TimerActivity_StartedUtc = null; action.WorkflowRecord.State = FormParametersHelper.ToJsonString(workflowState); _workflowManager.TriggerEvent("Timer", contentItem, () => tokens); } catch (Exception ex) { if (ex.IsFatal()) { throw; } Logger.Error(ex, "TimerBackgroundTask: Error while processing background task \"{0}\".", action.ActivityRecord.Name); } } }
protected ImagePart GetImage(int id) { return(_contentManager.Get <ImagePart>(id, VersionOptions.Published)); }
public void Calculate(Calculus calculus) { // look for the corresponding external function var function = _functions.Where(f => f.Name == calculus.FunctionName).FirstOrDefault(); if (function == null) { // no corresponding function found return; } // if an optimized calculation can't be executed, convert it to a Rebuild if (calculus.Mode == CalculationModes.Create && !function.CanCreate || calculus.Mode == CalculationModes.Delete && !function.CanDelete || calculus.Mode == CalculationModes.Update && !function.CanUpdate) { calculus = new RebuildCalculus { ContentId = calculus.ContentId, FunctionName = calculus.FunctionName, Dimension = calculus.Dimension }; } lock (_queue) { // if a rebuild is already waiting for the same content item and function, don't add a new one)) if (_queue.Any(c => c.Mode == CalculationModes.Rebuild && c.ContentId == calculus.ContentId && c.FunctionName == calculus.FunctionName && c.Dimension == calculus.Dimension)) { return; } _queue.Enqueue(calculus); } if (Monitor.TryEnter(_queue)) { while (_queue.Count > 0) { var currentCalculus = _queue.Dequeue(); calculus.GetVotes = () => { return(_voteRepository .Fetch(v => v.ContentItemRecord.Id == currentCalculus.ContentId && v.Dimension == currentCalculus.Dimension) .ToList()); }; // get the current result for this function and content item var result = _resultRepository .Fetch(r => r.ContentItemRecord.Id == currentCalculus.ContentId && r.FunctionName == currentCalculus.FunctionName) .SingleOrDefault(); var contentItem = _contentManager.Get(currentCalculus.ContentId); if (result == null) { result = new ResultRecord { Dimension = calculus.Dimension, ContentItemRecord = contentItem.Record, ContentType = contentItem.ContentType, FunctionName = calculus.FunctionName, Value = 0, Count = 0 }; } // either it's a new result or not, do update the CreatedUtc result.CreatedUtc = _clock.UtcNow; currentCalculus.Execute(function, result); if (result.Id == 0) { _resultRepository.Create(result); } // invalidates the cached result _signals.Trigger(DefaultVotingService.GetCacheKey(result.ContentItemRecord.Id, result.FunctionName, result.Dimension)); _eventHandler.Calculated(result); } Monitor.Exit(_queue); } }
public TemplatePart GetTemplate(int id) { return(_contentManager.Get <TemplatePart>(id)); }
private Response ExecPost(List <AnswerWithResultViewModel> Risps, string QuestionnaireContext = "") { #if DEBUG Logger.Error(Request.Headers.ToString()); #endif int QuestionId = 0; if (_orchardServices.Authorizer.Authorize(Permissions.SubmitQuestionnaire)) { if (Risps.Count > 0) { var currentUser = _orchardServices.WorkContext.CurrentUser; if (Risps[0].Id > 0) { QuestionId = _repositoryAnswer.Fetch(x => x.Id == Risps[0].Id).FirstOrDefault().QuestionRecord_Id; } else { QuestionId = Risps[0].QuestionRecord_Id; } Int32 id = _repositoryQuestions.Fetch(x => x.Id == QuestionId).FirstOrDefault().QuestionnairePartRecord_Id; var content = _contentManager.Get(id); var qp = content.As <QuestionnairePart>(); QuestionnaireWithResultsViewModel qVM = _questionnairesServices.BuildViewModelWithResultsForQuestionnairePart(qp); foreach (QuestionWithResultsViewModel qresult in qVM.QuestionsWithResults) { if (qresult.QuestionType == QuestionType.OpenAnswer) { foreach (AnswerWithResultViewModel Risp in Risps) { if (qresult.Id == Risp.QuestionRecord_Id && !(string.IsNullOrEmpty(Risp.AnswerText))) { qresult.OpenAnswerAnswerText = Risp.AnswerText; } } } else { foreach (AnswerWithResultViewModel asw in qresult.AnswersWithResult) { foreach (AnswerWithResultViewModel Risp in Risps) { if (asw.Id == Risp.Id) { if (qresult.QuestionType == QuestionType.SingleChoice) { qresult.SingleChoiceAnswer = asw.Id; } else { asw.Answered = true; } } } } } } var context = new ValidationContext(qVM, serviceProvider: null, items: null); var results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(qVM, context, results); if (!isValid) { string messaggio = ""; foreach (var validationResult in results) { messaggio += validationResult.ErrorMessage + " "; } return(_utilsServices.GetResponse(ResponseType.Validation, "Validation:" + messaggio)); } else { qVM.Context = QuestionnaireContext; if (_questionnairesServices.Save(qVM, currentUser, HttpContext.Current.Session.SessionID)) { return(_utilsServices.GetResponse(ResponseType.Success)); } else { return(_utilsServices.GetResponse(ResponseType.Validation, "Questionnaire already submitted.")); } } } else { return(_utilsServices.GetResponse(ResponseType.Validation, "Validation: data list is empty.")); } } else { return(_utilsServices.GetResponse(ResponseType.UnAuthorized)); } }
public void Evaluate(dynamic context) { context.For <ContentPickerField>("ContentPickerField") .Token("Content", (Func <ContentPickerField, object>)(field => field.Ids[0])) .Chain("Content", "Content", (Func <ContentPickerField, object>)(field => _contentManager.Get(field.Ids[0]))) ; }
public IContent GetMenu(int menuId) { return(_contentManager.Get(menuId, VersionOptions.Published)); }
public ContentItem Get(string id, string contentTypeHint = null) { var contentIdentity = new ContentIdentity(id); // lookup in local cache if (_identities.ContainsKey(contentIdentity)) { var result = _contentManager.Get(_identities[contentIdentity], VersionOptions.DraftRequired); // if two identities are conflicting, then ensure that there types are the same // e.g., importing a blog as home page (alias=) and the current home page is a page, the blog // won't be imported, and blog posts will be attached to the page if (contentTypeHint == null || result.ContentType == contentTypeHint) { return(result); } } // no result ? then check if there are some more content items to load from the db if (_lastIndex != int.MaxValue) { var equalityComparer = new ContentIdentity.ContentIdentityEqualityComparer(); IEnumerable <ContentItem> block; // load identities in blocks while ((block = _contentManager.HqlQuery() .ForVersion(VersionOptions.Latest) .OrderBy(x => x.ContentItemVersion(), x => x.Asc("Id")) .Slice(_lastIndex, BulkPage)).Any()) { foreach (var item in block) { _lastIndex++; // ignore content item if it has already been imported if (_contentItemIds.ContainsKey(item.Id)) { continue; } var identity = _contentManager.GetItemMetadata(item).Identity; // ignore content item if the same identity is already present if (_identities.ContainsKey(identity)) { continue; } _identities.Add(identity, item.Id); _contentItemIds.Add(item.Id, identity); if (equalityComparer.Equals(identity, contentIdentity)) { return(_contentManager.Get(item.Id, VersionOptions.DraftRequired)); } } _contentManager.Flush(); _contentManager.Clear(); } } _lastIndex = int.MaxValue; if (!_contentTypes.ContainsKey(contentIdentity)) { throw new ArgumentException("Unknown content type for " + id); } var contentItem = _contentManager.Create(_contentTypes[contentIdentity], VersionOptions.Draft); _identities[contentIdentity] = contentItem.Id; _contentItemIds[contentItem.Id] = contentIdentity; return(contentItem); }
protected void LazyLoadHandlers(WishListItemPart part) { part.WishListField.Loader(() => _contentManager.Get <WishListListPart>(part.WishListId, VersionOptions.Published, QueryHints.Empty)); }
// POST protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); var workContext = _workContextAccessor.GetContext(); // applying moderate/approve actions var httpContext = workContext.HttpContext; var name = httpContext.Request.Form["submit.Save"]; if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) { _commentService.UnapproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully moderated.")); return(Editor(part, shapeHelper)); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) { _commentService.ApproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment approved.")); return(Editor(part, shapeHelper)); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) { _commentService.DeleteComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully deleted.")); return(Editor(part, shapeHelper)); } } // if editing from the admin, don't update the owner or the status if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) { _orchardServices.Notifier.Information(T("Comment saved.")); return(Editor(part, shapeHelper)); } part.CommentDateUtc = _clock.UtcNow; if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) { part.SiteName = "http://" + part.SiteName; } var currentUser = workContext.CurrentUser; part.UserName = (currentUser != null ? currentUser.UserName : null); if (currentUser != null) { part.Author = currentUser.UserName; } var moderateComments = workContext.CurrentSite.As <CommentSettingsPart>().Record.ModerateComments; part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved; var commentedOn = _contentManager.Get <ICommonPart>(part.CommentedOn); // prevent users from commenting on a closed thread by hijacking the commentedOn property var commentsPart = commentedOn.As <CommentsPart>(); if (!commentsPart.CommentsActive) { _orchardServices.TransactionManager.Cancel(); return(Editor(part, shapeHelper)); } if (commentedOn != null && commentedOn.Container != null) { part.CommentedOnContainer = commentedOn.Container.ContentItem.Id; } commentsPart.Record.CommentPartRecords.Add(part.Record); return(Editor(part, shapeHelper)); }
public ContentItem Import(ImportSettings importSettings, object objectToImport, IContent parentContent) { Post blogPostToImport = (Post)objectToImport; var blogPostPart = _blogPostService.Get(parentContent.As <BlogPart>()).FirstOrDefault(rr => rr.As <IAliasAspect>().Path == blogPostToImport.PostUrl); if (importSettings.Override && blogPostPart != null) { blogPostPart = _contentManager.Get(blogPostPart.ContentItem.Id, VersionOptions.DraftRequired).As <BlogPostPart>(); } ContentItem contentItem = null; if (blogPostPart != null) { contentItem = blogPostPart.ContentItem; if (!importSettings.Override) { if (blogPostToImport.DateModified.IsEarlierThan(contentItem.As <ICommonPart>().ModifiedUtc) || blogPostToImport.DateModified.Equals(contentItem.As <ICommonPart>().ModifiedUtc)) { return(contentItem); } } } else { contentItem = _contentManager.Create("BlogPost", VersionOptions.Draft); contentItem.As <ICommonPart>().Container = parentContent; if (!string.IsNullOrEmpty(blogPostToImport.PostUrl)) { contentItem.As <AutoroutePart>().DisplayAlias = blogPostToImport.PostUrl.TrimStart('/'); } } contentItem.As <TitlePart>().Title = blogPostToImport.Title; contentItem.As <BodyPart>().Text = _dataCleaner.Clean(blogPostToImport.Content.Value, importSettings); var user = blogPostToImport.Authors.AuthorReferenceList.FirstOrDefault(); if (user != null) { contentItem.As <ICommonPart>().Owner = _userServices.GetUser(user.ID, true); } contentItem.As <CommentsPart>().CommentsActive = blogPostToImport.Comments.Enabled; if (blogPostToImport.HasExcerpt) { ((dynamic)contentItem).ExcerptPart.Excerpt.Value = blogPostToImport.Excerpt.Value; } ImportAdditionalContentItems(importSettings, blogPostToImport.Categories, contentItem); ImportAdditionalContentItems(importSettings, blogPostToImport.Tags, contentItem); if (blogPostToImport.Approved) { _contentManager.Publish(contentItem); if (blogPostToImport.DateModified.IsNotEmpty()) { contentItem.As <ICommonPart>().PublishedUtc = blogPostToImport.DateModified; contentItem.As <ICommonPart>().VersionPublishedUtc = blogPostToImport.DateModified; } } if (blogPostToImport.DateModified.IsNotEmpty()) { contentItem.As <ICommonPart>().ModifiedUtc = blogPostToImport.DateModified; contentItem.As <ICommonPart>().VersionModifiedUtc = blogPostToImport.DateModified; } if (blogPostToImport.DateCreated.IsNotEmpty()) { contentItem.As <ICommonPart>().CreatedUtc = blogPostToImport.DateCreated; contentItem.As <ICommonPart>().VersionCreatedUtc = blogPostToImport.DateCreated; } ImportAdditionalContentItems(importSettings, blogPostToImport.Comments, contentItem); //ImportAdditionalContentItems(importSettings, // blogPostToImport.Comments.CommentList.Where(o => DateTime.Parse(o.DateModified).IsLaterThan(contentItem.As<ICommonPart>().ModifiedUtc)), contentItem); return(contentItem); }
public void RemoveItemFromWishlist(WishListListPart wishlist, int itemId) { RemoveItemFromWishlist(wishlist, _contentManager.Get <WishListItemPart>(itemId)); }
public void Evaluate(EvaluateContext context) { context.For <IShoppingCart>("Cart") .Token("Items", c => string.Join(T(", ").Text, (c ?? _shoppingCart).GetProducts().Select(p => p.ToString()))) .Chain("Items", "CartItems", c => (c ?? _shoppingCart).GetProducts()) .Token("Country", c => (c ?? _shoppingCart).Country) .Token("ZipCode", c => (c ?? _shoppingCart).ZipCode) .Token("Shipping", c => (c ?? _shoppingCart).ShippingOption.ToString()) .Chain("Shipping", "ShippingOption", c => (c ?? _shoppingCart).ShippingOption) .Token("Subtotal", c => _currencyProvider.GetPriceString((c ?? _shoppingCart).Subtotal())) .Token("Taxes", c => { var taxes = (c ?? _shoppingCart).Taxes(); return(taxes == null ? _currencyProvider.GetPriceString(0.0) : _currencyProvider.GetPriceString(taxes.Amount)); }) .Chain("Taxes", "TaxAmount", c => (c ?? _shoppingCart).Taxes() ?? new TaxAmount { Amount = 0, Name = "" }) .Token("Total", c => _currencyProvider.GetPriceString((c ?? _shoppingCart).Total())) .Token("Count", c => (c ?? _shoppingCart).ItemCount()); context.For <IEnumerable <ShoppingCartQuantityProduct> >("CartItems") .Token(s => s.StartsWith("Format:", StringComparison.OrdinalIgnoreCase) ? s.Substring("Format:".Length) : null, (s, q) => { var separator = ""; var colonIndex = s.IndexOf(':'); if (colonIndex != -1 && s.Length > colonIndex + 1) { separator = s.Substring(0, colonIndex); s = s.Substring(colonIndex + 1); } var format = s .Replace("$quantity", "{0}") .Replace("$sku", "{1}") .Replace("$product", "{2}") .Replace("$price", "{3}"); return(String.Join(separator, q.Select(qp => String.Format(format, qp.Quantity, qp.Product.Sku, qp.Product.As <TitlePart>().Title + " " + string.Join(", ", qp.AttributeIdsToValues.Select(kvp => "[{{" + kvp.Key + "}} " + _contentManager.GetItemMetadata(_contentManager.Get(kvp.Key)).DisplayText + ": " + kvp.Value.ToString() + "]") ), _currencyProvider.GetPriceString(qp.Price))))); }); context.For <ShippingOption>("ShippingOption") .Token("Price", option => _currencyProvider.GetPriceString(option.Price)) .Token("Description", option => option.Description) .Chain("Description", "Text", option => option.Description) .Token("Company", option => option.ShippingCompany) .Chain("Company", "Text", option => option.ShippingCompany); context.For <TaxAmount>("TaxAmount") .Token("Name", amount => amount.Name) .Chain("Name", "Text", amount => amount.Name) .Token("Amount", amount => _currencyProvider.GetPriceString(amount.Amount)); context.For <ShoppingCartItem>("Item") .Token(s => s.StartsWith("Format:", StringComparison.OrdinalIgnoreCase) ? s.Substring("Format:".Length) : null, (s, sci) => { var colonIndex = s.IndexOf(':'); if (colonIndex != -1 && s.Length > colonIndex + 1) { s = s.Substring(colonIndex + 1); } var format = s .Replace("$quantity", "{0}") .Replace("$sku", "{1}") .Replace("$product", "{2}") .Replace("$price", "{3}"); var product = _contentManager.Get <ProductPart>(sci.ProductId); return(string.Format(format, sci.Quantity, product.Sku, product.As <TitlePart>().Title + " " + string.Join(", ", sci.AttributeIdsToValues.Select(kvp => "[{{" + kvp.Key + "}} " + _contentManager.GetItemMetadata(_contentManager.Get(kvp.Key)).DisplayText + ": " + kvp.Value.ToString() + "]") ), _currencyProvider.GetPriceString(product.Price))); }); }
public LayoutPart GetLayout(int id) { return(_contentManager.Get <LayoutPart>(id)); }
/// <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)) { // 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) == false) { rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage); } 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 _contentManager.Publish(NewOrModifiedContent); return(rsp); }
public ActionResult Edit(int id) { var part = _contentManager.Get <CloudVideoPart>(id, VersionOptions.Latest); return(EditImplementation(part, null)); }
public void Execute(FeedContext context) { var termParthId = context.ValueProvider.GetValue("term"); if (termParthId == null) { return; } var limitValue = context.ValueProvider.GetValue("limit"); var limit = 20; if (limitValue != null) { limit = (int)limitValue.ConvertTo(typeof(int)); } var containerId = (int)termParthId.ConvertTo(typeof(int)); var container = _contentManager.Get <TermPart>(containerId); if (container == null) { return; } var inspector = new ItemInspector(container, _contentManager.GetItemMetadata(container)); if (context.Format == "rss") { var link = new XElement("link"); context.Response.Element.SetElementValue("title", inspector.Title); context.Response.Element.Add(link); context.Response.Element.SetElementValue("description", inspector.Description); context.Response.Contextualize(requestContext => { var urlHelper = new UrlHelper(requestContext); var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/")) { Path = urlHelper.RouteUrl(inspector.Link) }; link.Add(uriBuilder.Uri.OriginalString); }); } else { context.Builder.AddProperty(context, null, "title", inspector.Title); context.Builder.AddProperty(context, null, "description", inspector.Description); context.Response.Contextualize(requestContext => { var urlHelper = new UrlHelper(requestContext); context.Builder.AddProperty(context, null, "link", urlHelper.RouteUrl(inspector.Link)); }); } var items = _taxonomyService.GetContentItems(container, 0, limit); foreach (var item in items) { // call item.ContentItem to force a cast to ContentItem, and // thus use CorePartsFeedItemBuilder context.Builder.AddItem(context, item.ContentItem); } }
public ContentItem Get(int id, VersionOptions versionOptions) { var blogPart = _contentManager.Get <BlogPart>(id, versionOptions); return(blogPart == null ? null : blogPart.ContentItem); }
private void PrintRoleRecord(RoleRecord roleRecord, int initialIndent = 0) { var secondIndent = initialIndent + 2; Context.Output.Write(new string(' ', initialIndent)); Context.Output.WriteLine(T("{0}", roleRecord.Name)); if (IncludePermissions) { Context.Output.Write(new string(' ', secondIndent)); Context.Output.WriteLine(T("List of Permissions")); Context.Output.Write(new string(' ', secondIndent)); Context.Output.WriteLine(T("--------------------------")); var permissionsEnumerable = roleRecord.RolesPermissions .Where(record => WithFeature == null || record.Permission.FeatureName == WithFeature) .Where(record => WithPermission == null || record.Permission.Name == WithPermission); var orderedPermissionsEnumerable = permissionsEnumerable .OrderBy(record => record.Permission.FeatureName) .ThenBy(record => record.Permission.Name); foreach (var rolesPermissionsRecord in orderedPermissionsEnumerable) { Context.Output.Write(new string(' ', secondIndent)); Context.Output.Write("Feature Name:".PadRight(15)); Context.Output.WriteLine(rolesPermissionsRecord.Permission.FeatureName); Context.Output.Write(new string(' ', secondIndent)); Context.Output.Write("Permission:".PadRight(15)); Context.Output.WriteLine(rolesPermissionsRecord.Permission.Name); Context.Output.Write(new string(' ', secondIndent)); Context.Output.Write("Description:".PadRight(15)); Context.Output.WriteLine(rolesPermissionsRecord.Permission.Description); Context.Output.WriteLine(); } } if (IncludeUsers) { var userRolesPartRecords = _userRolesRepository.Fetch(record => record.Role.Name == roleRecord.Name); Context.Output.Write(new string(' ', secondIndent)); Context.Output.WriteLine(T("List of Users")); Context.Output.Write(new string(' ', secondIndent)); Context.Output.WriteLine(T("--------------------------")); foreach (var userRolesPartRecord in userRolesPartRecords) { var userRolesPart = _contentManager.Get <UserRolesPart>(userRolesPartRecord.UserId); var user = userRolesPart.As <IUser>(); Context.Output.Write(new string(' ', secondIndent)); Context.Output.Write("UserName:"******"Email:".PadRight(15)); Context.Output.WriteLine(user.Email); Context.Output.WriteLine(); } } }
private void LazyLoadHandlers(ActivatedContentContext context, NotificationsPart part) { part._contentItem.Loader(() => part.NotificationsPlanPartRecord == null ? null : _contentManager.Get <NotificationsPlanPart>(part.NotificationsPlanPartRecord.Id)); }
public TaxonomyPart GetTaxonomy(int id) { return(_contentManager.Get(id, VersionOptions.Published, new QueryHints().ExpandParts <TaxonomyPart, AutoroutePart, TitlePart>()).As <TaxonomyPart>()); }
private MediaPart MediaPart(MediaLibraryPickerField field) { var mediaId = field.Ids.FirstOrDefault(); return(_contentManager.Get <MediaPart>(mediaId)); }
public MenuPart Get(int menuPartId) { return(_contentManager.Get <MenuPart>(menuPartId)); }
public ContentMenuItemPartHandler(IContentManager contentManager, IRepository <ContentMenuItemPartRecord> repository) { _contentManager = contentManager; Filters.Add(new ActivatingFilter <ContentMenuItemPart>("ContentMenuItem")); Filters.Add(StorageFilter.For(repository)); OnLoading <ContentMenuItemPart>((context, part) => part._content.Loader(p => contentManager.Get(part.Record.ContentMenuItemRecord.Id))); }
public RoutePartHandler( IOrchardServices services, IRepository<RoutePartRecord> repository, IRoutablePathConstraint routablePathConstraint, IRoutableService routableService, IContentManager contentManager, IWorkContextAccessor workContextAccessor, IEnumerable<IHomePageProvider> homePageProviders) { _services = services; _routablePathConstraint = routablePathConstraint; _routableService = routableService; _contentManager = contentManager; _workContextAccessor = workContextAccessor; _routableHomePageProvider = homePageProviders.SingleOrDefault(p => p.GetProviderName() == RoutableHomePageProvider.Name); T = NullLocalizer.Instance; Filters.Add(StorageFilter.For(repository)); Action<RoutePart> processSlug = ( routable => { if (!_routableService.ProcessSlug(routable)) _services.Notifier.Warning(T("Permalinks in conflict. \"{0}\" is already set for a previously created {2} so now it has the slug \"{1}\"", routable.Slug, routable.GetEffectiveSlug(), routable.ContentItem.ContentType)); }); OnGetDisplayShape<RoutePart>(SetModelProperties); OnGetEditorShape<RoutePart>(SetModelProperties); OnUpdateEditorShape<RoutePart>(SetModelProperties); Action<PublishContentContext, RoutePart> handler = (context, route) => { FinalizePath(route, context, processSlug); if (_routableHomePageProvider == null) return; var homePageSetting = _workContextAccessor.GetContext().CurrentSite.HomePage; var currentHomePageId = !string.IsNullOrWhiteSpace(homePageSetting) ? _routableHomePageProvider.GetHomePageId(homePageSetting) : 0; if (route.Id != 0 && (route.Id == currentHomePageId || route.PromoteToHomePage)) { if (currentHomePageId != route.Id) { // reset the path on the current home page var currentHomePage = _contentManager.Get(currentHomePageId); if (currentHomePage != null) FinalizePath(currentHomePage.As<RoutePart>(), context, processSlug); // set the new home page _services.WorkContext.CurrentSite.HomePage = _routableHomePageProvider.GetSettingValue(route.ContentItem.Id); } // readjust the constraints of the current current home page _routablePathConstraint.RemovePath(route.Path); route.Path = ""; _routableService.FixContainedPaths(route); _routablePathConstraint.AddPath(route.Path); } }; OnPublished<RoutePart>(handler); OnUnpublished<RoutePart>(handler); OnRemoved<RoutePart>((context, route) => { if (!string.IsNullOrWhiteSpace(route.Path)) _routablePathConstraint.RemovePath(route.Path); }); OnIndexing<RoutePart>((context, part) => context.DocumentIndex.Add("title", part.Record.Title).RemoveTags().Analyze()); }
public ActionResult Add(int id, int quantity = 1, bool isAjaxRequest = false) { // Manually parse product attributes because of a breaking change // in MVC 5 dictionary model binding var form = HttpContext.Request.Form; var files = HttpContext.Request.Files; var productattributes = form.AllKeys .Where(key => key.StartsWith(AttributePrefix)) .ToDictionary( key => int.Parse(key.Substring(AttributePrefix.Length)), key => { var extensionProvider = _attributeExtensionProviders.SingleOrDefault(e => e.Name == form[ExtensionPrefix + key + ".provider"]); Dictionary <string, string> extensionFormValues = null; if (extensionProvider != null) { extensionFormValues = form.AllKeys.Where(k => k.StartsWith(ExtensionPrefix + key + ".")) .ToDictionary( k => k.Substring((ExtensionPrefix + key + ".").Length), k => form[k]); return(new ProductAttributeValueExtended { Value = form[key], ExtendedValue = extensionProvider.Serialize(form[ExtensionPrefix + key], extensionFormValues, files), ExtensionProvider = extensionProvider.Name }); } return(new ProductAttributeValueExtended { Value = form[key], ExtendedValue = null, ExtensionProvider = null }); }); // Retrieve minimum order quantity Dictionary <int, List <string> > productMessages = new Dictionary <int, List <string> >(); var productPart = _contentManager.Get <ProductPart>(id); string productTitle = _contentManager.GetItemMetadata(productPart.ContentItem).DisplayText; if (productPart != null) { if (quantity < productPart.MinimumOrderQuantity) { quantity = productPart.MinimumOrderQuantity; if (productMessages.ContainsKey(id)) { productMessages[id].Add(T("Quantity increased to match minimum possible for {0}.", productTitle).Text); } else { productMessages.Add(id, new List <string>() { T("Quantity increased to match minimum possible for {0}.", productTitle).Text }); } } //only add to cart if there are at least as many available products as the requested quantity if (quantity > productPart.Inventory && !productPart.AllowBackOrder && (!productPart.IsDigital || (productPart.IsDigital && productPart.ConsiderInventory)) ) { quantity = productPart.Inventory; if (productMessages.ContainsKey(id)) { productMessages[id].Add(T("Quantity decreased to match inventory for {0}.", productTitle).Text); } else { productMessages.Add(id, new List <string>() { T("Quantity decreased to match inventory for {0}.", productTitle).Text }); } } } _shoppingCart.Add(id, quantity, productattributes); var newItem = new ShoppingCartItem(id, quantity, productattributes); foreach (var handler in _cartLifeCycleEventHandlers) { handler.ItemAdded(newItem); } // Test isAjaxRequest too because iframe posts won't return true for Request.IsAjaxRequest() if (Request.IsAjaxRequest() || isAjaxRequest) { return(new ShapePartialResult( this, BuildCartShape(true, _shoppingCart.Country, _shoppingCart.ZipCode, null, productMessages))); } return(RedirectToAction("Index", productMessages)); }
public void GetByIdShouldDetermineTypeAndLoadParts() { var modelRecord = CreateModelRecord(DefaultAlphaName); var contentItem = _manager.Get(modelRecord.Id); Assert.That(contentItem.ContentType, Is.EqualTo(DefaultAlphaName)); Assert.That(contentItem.Id, Is.EqualTo(modelRecord.Id)); }
public TaxonomyPart GetTaxonomy(int id) { return(_contentManager.Get(id, VersionOptions.Published).As <TaxonomyPart>()); }
public CaptchaService(IContentManager contentManager, ISiteService siteService) { CaptchaPart = contentManager.Get<CaptchaSettingsPart>(1); CurrentCulture = siteService.GetSiteSettings().SiteCulture; T = NullLocalizer.Instance; }