/// <summary> /// get the featured related posts /// </summary> /// <param name="contentItem"></param> /// <param name="multilistFieldID"></param> /// <returns></returns> private List <Blog> GetRelatedPosts(Item contentItem, ID multilistFieldID) { List <Blog> relatedPosts = null; //get the list of items selected in the multilist field IList <Item> featuredItems = SitecoreUtility.GetSelectedItemsInMultilistField(contentItem, multilistFieldID); //check for each item if it is of valid template and active.If yes, then add it to the list if (featuredItems != null && featuredItems.Count > 0) { relatedPosts = new List <Blog>(); foreach (Item featuredItem in featuredItems) { if (featuredItem.TemplateID == References.Templates.BlogPage.ID) { Blog blogItem = new Blog(featuredItem); if (blogItem != null && blogItem.IsActive) { relatedPosts.Add(blogItem); } } } } return(relatedPosts); }
/// <summary> /// get the featured more courses /// </summary> /// <param name="contentItem"></param> /// <param name="multilistFieldID"></param> /// <returns></returns> private List <CourseDetails> GetMoreCourses(Item contentItem, ID multilistFieldID) { List <CourseDetails> moreCourses = null; //get the list of items selected in the multilist field IList <Item> featuredItems = SitecoreUtility.GetSelectedItemsInMultilistField(contentItem, multilistFieldID); //check for each item if it is of valid template and active.If yes, then add it to the list if (featuredItems != null && featuredItems.Count > 0) { moreCourses = new List <CourseDetails>(); foreach (Item featuredItem in featuredItems) { if (featuredItem.TemplateID == References.Templates.CourseDetailsPage.ID) { CourseDetails courseDetailsItem = new CourseDetails(featuredItem); if (courseDetailsItem != null && courseDetailsItem.IsActive) { courseDetailsItem.Instructor = GetInstructor(courseDetailsItem.SelectedInstructorItemID); moreCourses.Add(courseDetailsItem); } } } } return(moreCourses); }
protected void RemoveSiteAttributes(SiteInfo siteInfo) { Item sFolder = MasterDB.GetItem(Constants.Paths.Sites); if (sFolder != null) { Item siteItem = sFolder.Axes.GetChild(siteInfo.Name); //set login url on the site node using (new EditContext(siteItem)) { siteItem[Sitecore.Extranet.Core.Constants.ExtranetAttributes.LoginPage] = string.Empty; } IEnumerable <Item> atts = siteItem.Axes.GetDescendants().Where(a => a.Template.IsID(Constants.TemplateIDs.SiteAttribute) && Sitecore.Extranet.Core.Constants.ExtranetAttributes.Keys.Contains(a.Key)); if (atts != null && atts.Any()) { foreach (Item a in atts) { a.Recycle(); } } SitecoreUtility.PublishContent(siteItem, true); } else { FileUtility.RemoveFile(string.Format(Sitecore.Extranet.Core.Wizards.ExtranetSetupWizard.Constants.FilePatterns.ExtranetSiteConfig, siteInfo.Name)); } }
public ActionResult RenderBanner() { Banner banner = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.Banner.ID) { banner = new Banner(renderingDatasourceItem); if (!banner.IsActive) { banner = null; } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/Banner.cshtml", banner)); }
public ActionResult RenderPopularPosts() { PopularPostsSource viewModel = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.PopularPostsSource.ID) { viewModel = new PopularPostsSource(renderingDatasourceItem); if (!viewModel.IsActive) { viewModel = null; } else { viewModel.FeaturedBlogs = GetRelatedPosts(renderingDatasourceItem, References.Templates.PopularPostsSource.Fields.FeaturedBlogs); } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/PopularPosts.cshtml", viewModel)); }
/// <summary> /// get the featured timetable events /// </summary> /// <param name="contentItem"></param> /// <param name="multilistFieldID"></param> /// <returns></returns> private List <TimetableEvent> GetTimetableEvents(Item contentItem, ID multilistFieldID) { List <TimetableEvent> timetableEvents = null; //get the list of items selected in the multilist field IList <Item> featuredItems = SitecoreUtility.GetSelectedItemsInMultilistField(contentItem, multilistFieldID); //check for each item if it is of valid template and active.If yes, then add it to the list if (featuredItems != null && featuredItems.Count > 0) { timetableEvents = new List <TimetableEvent>(); foreach (Item featuredItem in featuredItems) { if (featuredItem.TemplateID == References.Templates.TimetableEvent.ID) { TimetableEvent timetableEventItem = new TimetableEvent(featuredItem); if (timetableEventItem != null && timetableEventItem.IsActive) { timetableEventItem.Instructor = GetInstructor(timetableEventItem.SelectedInstructorItemID); timetableEvents.Add(timetableEventItem); } } } } return(timetableEvents); }
protected override void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); SubmitButton.Text = FormTextUtility.Provider.GetTextByKey("/EditAccount/ChangePassword"); BackLink.NavigateUrl = SitecoreUtility.GetItemURL(PreferredDataSource.Parent); }
protected override void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); SubmitButton.Text = FormTextUtility.Provider.GetTextByKey("/EditAccount/ChangeEmail"); //set the current email to the form OldEmail.Text = Sitecore.Context.User.Profile.Email; BackLink.NavigateUrl = SitecoreUtility.GetItemURL(PreferredDataSource.Parent); }
/// <summary> /// Instantiates an instance of the proxy class /// </summary> /// <param name="proxy">Proxy that will be used to authenticate the user</param> public AutoRefreshSecurityToken(TProxy proxy) { if (null == proxy) { throw new ArgumentNullException("proxy"); } this._proxy = proxy; _expirationWindow = SitecoreUtility.GetSitecoreSetting <int>("AlphaSolutions.ExtendedCRMProvider.V5.TokenExpirationWindow", 15); }
/// <summary> /// get pagewise blog teasers based on the filters like category & tag /// </summary> /// <param name="selectedPage"></param> /// <param name="categoryID"></param> /// <param name="tagID"></param> /// <param name="blogArchivePageItemID"></param> /// <param name="totalPages"></param> /// <returns></returns> private List <Blog> GetBlogTeasersByFilters(int selectedPage, string categoryID, string tagID, string blogArchivePageItemID, out int totalPages) { List <Item> blogPageItems = new List <Item>(); List <Blog> blogsByPage = new List <Blog>(); totalPages = 1; Item blogArchivePageItem = !string.IsNullOrEmpty(blogArchivePageItemID) ? SitecoreUtility.GetItem(new ID(blogArchivePageItemID)) : null; if (blogArchivePageItem != null && blogArchivePageItem.HasChildren) { blogPageItems = SitecoreUtility.GetItemsByTemplate(blogArchivePageItem, References.Templates.BlogPage.ID) .Where(x => x.Fields[References.Templates.Blog.Fields.IsActive].Value == "1").ToList(); if (blogPageItems != null && blogPageItems.Count > 0) { int maxTeasersPerPage = Constants.MaxBlogTeasersPerPage; if (!string.IsNullOrEmpty(categoryID)) { Item categoryItem = SitecoreUtility.GetItem(new ID(categoryID)); if (categoryItem != null && categoryItem.Fields[References.Templates.BlogCategory.Fields.IsActive].Value == "1") { blogPageItems = blogPageItems.Where(x => x.Fields[References.Templates.Blog.Fields.BlogCategories].Value.Contains(categoryID)).ToList(); } } else if (!string.IsNullOrEmpty(tagID)) { Item tagItem = SitecoreUtility.GetItem(new ID(tagID)); if (tagItem != null && tagItem.Fields[References.Templates.BlogTag.Fields.IsActive].Value == "1") { blogPageItems = blogPageItems.Where(x => x.Fields[References.Templates.Blog.Fields.BlogTags].Value.Contains(tagID)).ToList(); } } if (blogPageItems != null && blogPageItems.Count > 0) { foreach (Item item in blogPageItems) { blogsByPage.Add(new Blog(item)); } } if (blogsByPage != null && blogsByPage.Count > 0) { blogsByPage = blogsByPage.OrderByDescending(x => x.PostedDateTime).ToList(); blogsByPage = SitecoreUtility.GetPagewiseRecords <Blog>(blogsByPage, maxTeasersPerPage, selectedPage, out totalPages); } } } return(blogsByPage); }
// GET: Footer public ActionResult RenderFooter() { FooterSource viewModel = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.FooterSource.ID) { viewModel = new FooterSource(renderingDatasourceItem); if (viewModel.IsActive) { viewModel.Identity = new Identity(viewModel.IdentitySourceItem); //get the list of items selected in the multilist field IList <Item> featuredItems = SitecoreUtility.GetSelectedItemsInMultilistField(viewModel.InnerItem, References.Templates.FooterSource.Fields.SocialLinks); //check for each item if it is of valid template and active.If yes, then add it to the list if (featuredItems != null && featuredItems.Count > 0) { viewModel.SocialLinks = new List <FooterSocialLink>(); foreach (Item featuredItem in featuredItems) { if (featuredItem.TemplateID == References.Templates.FooterSocialLink.ID) { FooterSocialLink oblFeaturedItem = new FooterSocialLink(featuredItem); if (oblFeaturedItem != null && oblFeaturedItem.IsActive) { viewModel.SocialLinks.Add(oblFeaturedItem); } } } } } else { viewModel = null; } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/Footer.cshtml", viewModel)); }
public ActionResult RenderCourseTeasersCarousel() { CourseTeasersCarouselSource viewModel = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.CourseTeasersCarouselSource.ID) { viewModel = new CourseTeasersCarouselSource(renderingDatasourceItem); if (viewModel.IsActive) { Item courseArchivePageItem = SitecoreUtility.GetItem(new ID(viewModel.CourseArchivePageID)); if (courseArchivePageItem != null) { //get all the active course items List <Item> coursePageItems = SitecoreUtility.GetItemsByTemplate(courseArchivePageItem, References.Templates.CourseDetailsPage.ID) .Where(x => x.Fields[References.Templates.CourseDetails.Fields.IsActive].Value == "1").ToList(); if (coursePageItems != null && coursePageItems.Count > 0) { viewModel.CourseTeasers = new List <CourseDetails>(); foreach (Item item in coursePageItems) { CourseDetails courseDetails = new CourseDetails(item); courseDetails.Instructor = GetInstructor(courseDetails.SelectedInstructorItemID); viewModel.CourseTeasers.Add(courseDetails); } } } } else { viewModel = null; } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/CourseTeasersCarousel.cshtml", viewModel)); }
/// <summary> /// Get the selected intructor /// </summary> /// <param name="selectedInstructorItemID"></param> /// <returns></returns> private Instructor GetInstructor(string selectedInstructorItemID) { Instructor instructor = null; if (!string.IsNullOrEmpty(selectedInstructorItemID)) { Item instructorItem = SitecoreUtility.GetItem(new ID(selectedInstructorItemID)); if (instructorItem != null) { instructor = new Instructor(instructorItem); } } return(instructor); }
protected void RemoveExtranetPages(SiteInfo siteItem) { Item HomeItem = MasterDB.GetItem(string.Format("{0}{1}", siteItem.RootPath, siteItem.StartItem)); IEnumerable <Item> pages = HomeItem.Axes.GetDescendants().Where(a => a.Template.IsID(Constants.TemplateIDs.ExtranetFolder) || a.Template.Is(Constants.TempateName.ExtranetLogin)); if (pages == null || !pages.Any()) { return; } foreach (Item p in pages) { Item par = p.Parent; p.Recycle(); SitecoreUtility.PublishContent(par, true); } }
public ActionResult RenderBannerCarousel() { BannerCarouselSource viewModel = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.BannerCarouselSource.ID) { viewModel = new BannerCarouselSource(renderingDatasourceItem); if (!viewModel.IsActive) { viewModel = null; } else { //get all the active carousel slide items selected in the multilist field List <Item> selectedItems = SitecoreUtility.GetSelectedItemsInMultilistField(renderingDatasourceItem, References.Templates.BannerCarouselSource.Fields.Slides) .Where(x => x.Fields[References.Templates.BannerCarouselSlide.Fields.IsActive].Value == "1").ToList(); if (selectedItems != null && selectedItems.Count > 0) { viewModel.Slides = new List <BannerCarouselSlide>(); foreach (Item item in selectedItems) { BannerCarouselSlide featuredItem = new BannerCarouselSlide(item); viewModel.Slides.Add(featuredItem); } } } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/BannerCarousel.cshtml", viewModel)); }
public ActionResult SaveContactUsFormData(ContactUsFormData contactUsFormDataModel) { string statusCode = "0"; string statusMessage = string.Empty; try { List <KeyValuePair <ID, string> > fieldValueCollection = new List <KeyValuePair <ID, string> >(); fieldValueCollection.Add(new KeyValuePair <ID, string>(References.Templates.ContactUsFormData.Fields.FullName, contactUsFormDataModel.Fullname)); fieldValueCollection.Add(new KeyValuePair <ID, string>(References.Templates.ContactUsFormData.Fields.Email, contactUsFormDataModel.Email)); fieldValueCollection.Add(new KeyValuePair <ID, string>(References.Templates.ContactUsFormData.Fields.Subject, contactUsFormDataModel.Subject)); fieldValueCollection.Add(new KeyValuePair <ID, string>(References.Templates.ContactUsFormData.Fields.Comments, contactUsFormDataModel.Comments)); string itemName = contactUsFormDataModel.Email.Replace("@", "").Replace(".", "") + SitecoreUtility.GenerateRandomNumber(5); Item newItem = SitecoreUtility.CreateItem(itemName, References.Content.ContactUsFormDataFolder, References.Templates.ContactUsFormData.ID.ToString(), fieldValueCollection); if (newItem != null) { statusCode = "1"; statusMessage = "We've received your message and will get back to you shortly."; } else { statusCode = "0"; statusMessage = "A problem occurred while processing your request. Please try again later."; } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); statusCode = "0"; statusMessage = "A problem occurred while processing your request. Please try again later."; } return(Json(new { Status = statusCode, Message = statusMessage }, JsonRequestBehavior.AllowGet)); }
public ActionResult RenderTagsOrCategoriesSidebarFilter() { TagsOrCategoriesSidebarFilter viewModel = null; try { string blogArchivePageItemID = SitecoreUtility.GetRenderingParameters(References.Templates.TagsOrCategoriesSidebarFilter.ID, References.Templates.TagsOrCategoriesSidebarFilter.Fields.BlogArchivePage); if (!string.IsNullOrEmpty(blogArchivePageItemID)) { Item blogArchivePageItem = SitecoreUtility.GetItem(new ID(blogArchivePageItemID)); if (blogArchivePageItem != null) { viewModel = new TagsOrCategoriesSidebarFilter(); viewModel.SectionTitle = SitecoreUtility.GetRenderingParameters(References.Templates.TagsOrCategoriesSidebarFilter.ID, References.Templates.TagsOrCategoriesSidebarFilter.Fields.SectionTitle); viewModel.DisplayItemsAsTags = SitecoreUtility.GetRenderingParameters(References.Templates.TagsOrCategoriesSidebarFilter.ID, References.Templates.TagsOrCategoriesSidebarFilter.Fields.DisplayItemsAsTags) == "1"; viewModel.BlogArchivePageURL = SitecoreUtility.GetItemURL(blogArchivePageItem); if (!viewModel.DisplayItemsAsTags) { List <BlogCategory> categoriesUsedByBlogs = new List <BlogCategory>(); Item blogCategoriesFolderItem = SitecoreUtility.GetItem(References.Content.BlogCategoriesFolder); if (blogCategoriesFolderItem != null && blogCategoriesFolderItem.HasChildren) { List <Item> activeCategories = SitecoreUtility.GetItemsByTemplate(blogCategoriesFolderItem, References.Templates.BlogCategory.ID) .Where(x => x.Fields[References.Templates.BlogCategory.Fields.IsActive].Value == "1").ToList(); if (activeCategories != null && activeCategories.Count > 0) { foreach (Item category in activeCategories) { if (SitecoreUtility.HasReferrers(category, References.Templates.BlogPage.ID, References.Templates.Blog.Fields.IsActive)) { BlogCategory blogCategory = new BlogCategory(category); categoriesUsedByBlogs.Add(blogCategory); } } viewModel.BlogCategories = categoriesUsedByBlogs; } } } else { List <BlogTag> tagsUsedByBlogs = new List <BlogTag>(); Item blogTagsFolderItem = SitecoreUtility.GetItem(References.Content.BlogTagsFolder); if (blogTagsFolderItem != null && blogTagsFolderItem.HasChildren) { List <Item> activeTags = SitecoreUtility.GetItemsByTemplate(blogTagsFolderItem, References.Templates.BlogTag.ID) .Where(x => x.Fields[References.Templates.BlogTag.Fields.IsActive].Value == "1").ToList(); if (activeTags != null && activeTags.Count > 0) { foreach (Item tag in activeTags) { if (SitecoreUtility.HasReferrers(tag, References.Templates.BlogPage.ID, References.Templates.Blog.Fields.IsActive)) { BlogTag blogTag = new BlogTag(tag); tagsUsedByBlogs.Add(blogTag); } } viewModel.BlogTags = tagsUsedByBlogs; } } } } } } catch (System.Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "PageContent/TagsOrCategoriesSidebarFilter.cshtml", viewModel)); }
protected string GetURL(string template) { Item p = PreferredDataSource.ChildByTemplateID(template); return((p != null) ? SitecoreUtility.GetItemURL(p) : string.Empty); }
public ActionResult RenderTopMenu() { TopMenuSource topMenuSource = null; try { //get the datasource item assigned to the rendering Item renderingDatasourceItem = SitecoreUtility.GetRenderingDatasourceItem(); if (renderingDatasourceItem != null && renderingDatasourceItem.TemplateID == References.Templates.TopMenuSource.ID && renderingDatasourceItem.HasChildren) { topMenuSource = new TopMenuSource(renderingDatasourceItem); if (topMenuSource != null) { if (topMenuSource.IdentitySourceItem != null) { topMenuSource.Identity = new Identity(topMenuSource.IdentitySourceItem); } topMenuSource.TopMenuItems = new List <NavigationItem>(); //loop through all the child items and add active menu items to the list foreach (Item menuItem in renderingDatasourceItem.Children) { if (menuItem.TemplateID == References.Templates.NavigationItem.ID) { NavigationItem topMenuItem = new NavigationItem(menuItem); if (topMenuItem.IsActive) { if (menuItem.HasChildren) { topMenuItem.SubmenuItems = new List <NavigationItem>(); //loop through all the sub items of the menu item and add active items to its subitem list foreach (Item submenuItem in menuItem.Children) { if (submenuItem.TemplateID == References.Templates.NavigationItem.ID) { NavigationItem smItem = new NavigationItem(submenuItem); if (smItem.IsActive) { topMenuItem.SubmenuItems.Add(smItem); } } } } topMenuSource.TopMenuItems.Add(topMenuItem); } } } } } } catch (Exception ex) { LogManager.SaveLog(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, ex, LogManager.LogTypes.Error, string.Empty); } return(View(GlobalConstants.SUBLAYOUTS_PATH + "Navigation/TopMenu.cshtml", topMenuSource)); }
/// <summary> /// Method to get users in given Role. in CRM Marketing list. /// This method has been customized to support dynamic lists. /// </summary> /// <param name="roleName"></param> /// <returns></returns> public override string[] GetUsersInRole(string roleName) { //setting that disabled the dynamic list functionality. if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.DynamicLists", false)) { return(base.GetUsersInRole(roleName)); } Assert.ArgumentNotNull(roleName, "roleName"); ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole"); string text = base.CacheService.MembersCache.Get(roleName); if (text != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole"); return(text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)); } // set up a query for the list to check type Microsoft.Xrm.Sdk.Query.ColumnSet columnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "listname", "query", "type" }); Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression(); query.ColumnSet = columnSet; Microsoft.Xrm.Sdk.Query.ConditionExpression listnameCondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression(); listnameCondition.AttributeName = "listname"; listnameCondition.Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal; listnameCondition.Values.Add(roleName); Microsoft.Xrm.Sdk.Query.FilterExpression filterList = new Microsoft.Xrm.Sdk.Query.FilterExpression(); filterList.Conditions.Add(listnameCondition); filterList.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And; query.EntityName = "list"; query.Criteria = filterList; // Execute the query Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest req = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest(); req.Query = query; Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse res = (Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse) this.OrganizationService.Execute(req); if (res != null && res.EntityCollection != null && res.EntityCollection.Entities.Count > 0) { Entity myList = res.EntityCollection.Entities[0]; if (myList.Attributes.Keys.Contains("query")) { // Define the fetch attributes. // Set the number of records per page to retrieve. int fetchCount = Settings.FetchThrottlingPageSize; // Initialize the page number. int pageNumber = 1; // Initialize the number of records. int recordCount = 0; // Specify the current paging cookie. For retrieving the first page, // pagingCookie should be null. string pagingCookie = null; //Convert fetchXML to Query Expression var xml = myList["query"].ToString(); HashSet <string> hashSet = new HashSet <string>(); try { while (true) { string xmlpaging = CreateXml(xml, pagingCookie, pageNumber, fetchCount, Settings.UniqueKeyProperty); Microsoft.Xrm.Sdk.Query.FetchExpression f = new Microsoft.Xrm.Sdk.Query.FetchExpression(xmlpaging); RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest(); retrieveMultipleRequest.Query = f; RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)this.OrganizationService.Execute(retrieveMultipleRequest); if (retrieveMultipleResponse != null && retrieveMultipleResponse.EntityCollection != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, retrieveMultipleResponse.EntityCollection.Entities.Count), this, TimerAction.Tick, "getUsersInRole"); foreach (Entity current in retrieveMultipleResponse.EntityCollection.Entities) { try { base.CacheService.UserCache.Add(this.ContactToUserConverter.Convert(current)); hashSet.Add((string)current[Settings.UniqueKeyProperty]); } catch (Exception e) { ConditionalLog.Error(string.Format("GetUsersInRole({0}). Error in converting contact to user. Number of attributes gotten: {1}", current.LogicalName, current.Attributes.Count), e, this); } } // Check for morerecords, if it returns 1. if (retrieveMultipleResponse.EntityCollection.MoreRecords) { // Increment the page number to retrieve the next page. pageNumber++; } else { // If no more records in the result nodes, exit the loop. break; } pagingCookie = retrieveMultipleResponse.EntityCollection.PagingCookie; } } var ret = hashSet.ToArray <string>(); base.CacheService.MembersCache.Add(roleName, string.Join("|", ret)); return(ret); } catch (System.Exception sourceException) { ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), sourceException, this); } } else { return(base.GetUsersInRole(roleName)); } } return(new string[0]); }
protected T Resolve <T>(ConfigurationSettings settings) { //setting to disable customized code all together if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.Customizations", false)) { return(base.Resolve <T>(settings)); } //have the original base class handle older API versions. if (settings.ApiVersion != ApiVersion.V5) { return(base.Resolve <T>(settings)); } if (_unityContainer == null) { lock (Locker) { if (_unityContainer == null) { UnityContainer container = new UnityContainer(); switch (settings.ApiVersion) { case ApiVersion.V3: { throw new NotImplementedException("V3 has not yet been implemented. Should be handled by base class."); break; } case ApiVersion.V4: { throw new NotImplementedException("V3 has not yet been implemented. Should be handled by base class."); break; } case ApiVersion.V5: { var rv3 = new CrmServiceCreatorV5(); container.RegisterInstance <IOrganizationService>( rv3.CreateOrganizationService(settings), new ContainerControlledLifetimeManager()) .RegisterType <ICacheService, CacheService>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <IContactToUserConverterV5, ContactToUserConverterV5>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <IMarketingListToRoleConverterV5, MarketingListToRoleConverterV5>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <UserRepositoryBase, UserRepositoryV5>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <RoleRepositoryBase, RoleRepositoryV5>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <ProfileRepositoryBase, ProfileRepositoryV5>( new ContainerControlledLifetimeManager(), new InjectionMember[0]) .RegisterType <EntityRepositoryBase, EntityRepository>( new ContainerControlledLifetimeManager(), new InjectionMember[0]); break; } } _unityContainer = container; } } } return(_unityContainer.Resolve <T>(new ResolverOverride[0])); }
public IOrganizationService CreateOrganizationService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); ConditionalLog.Info("CreateOrganizationService(settings). Started.", this, TimerAction.Start, "createOrganizationService"); IOrganizationService service = null; try { IServiceManagement <IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(settings.Url)); AuthenticationCredentials authenticationCredentials = new AuthenticationCredentials(); switch (serviceManagement.AuthenticationType) { case AuthenticationProviderType.ActiveDirectory: authenticationCredentials.ClientCredentials.Windows.ClientCredential = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); service = new OrganizationServiceProxy(serviceManagement, authenticationCredentials.ClientCredentials); break; case AuthenticationProviderType.Federation: case AuthenticationProviderType.LiveId: case AuthenticationProviderType.OnlineFederation: { authenticationCredentials.ClientCredentials.UserName.UserName = settings.User; authenticationCredentials.ClientCredentials.UserName.Password = settings.Password; AuthenticationCredentials credentials2 = serviceManagement.Authenticate(authenticationCredentials); //setting to be able to configure using the custom token service proxy if ( SitecoreUtility.GetSitecoreSetting <bool>( "AlphaSolutions.ExtendedCRMProvider.V5.Disable.AuthenticationCustomization", false)) { service = new CRMSecurityProvider.Repository.V5.ManagedTokenOrganizationServiceProxy(serviceManagement, credentials2.SecurityTokenResponse); } else { service = new ManagedTokenOrganizationServiceProxy(serviceManagement, credentials2.SecurityTokenResponse, authenticationCredentials); } break; } } if (service == null) { ConditionalLog.Error("CreateOrganizationService(settings). service could not be initialized.", this); return(null); } service.Execute(new WhoAmIRequest()); ConditionalLog.Info("CreateOrganizationService(settings). CRM organization service has been created.", this, TimerAction.Tick, "createOrganizationService"); } catch (Exception exception) { ConditionalLog.Error("Couldn't create CRM organization service.", exception, this); return(null); } finally { ConditionalLog.Info("CreateOrganizationService(settings). Finished.", this, TimerAction.Stop, "createOrganizationService"); } return(service); }
/// <summary> /// gets courses by page /// </summary> /// <param name="parentItem">If its first page, parent item should be passed. All its child pages will be verified.</param> /// <param name="pageNumber">1 is for first page, 2 is for next page & 0 is for previous page</param> /// <param name="referenceCourseItemID">the course item id of the first or last course teaser on page</param> /// <returns></returns> private List <CourseDetails> GetCoursesByPage(string coursesRootItemID, string pageNumber, string referenceCourseItemIDs, out bool showPrevButton, out bool showNextButton) { showPrevButton = false; showNextButton = false; List <CourseDetails> lstCourses = new List <CourseDetails>(); List <Item> featuredItems = new List <Item>(); int maxTeasersPerPage = Constants.MaxCourseTeasersPerPage; int itemsInList = 0; if (pageNumber == "1" && !string.IsNullOrEmpty(coursesRootItemID)) { Item coursesRootItem = SitecoreUtility.GetItem(new ID(coursesRootItemID)); //get the list of courses for first page featuredItems = coursesRootItem != null?SitecoreUtility.GetItemsByTemplate(coursesRootItem, References.Templates.CourseDetailsPage.ID) : null; if (featuredItems != null && featuredItems.Count > 0) { foreach (Item featuredItem in featuredItems) { if (itemsInList < maxTeasersPerPage) { CourseDetails courseDetailsItem = new CourseDetails(featuredItem); if (courseDetailsItem != null && courseDetailsItem.IsActive) { courseDetailsItem.Instructor = GetInstructor(courseDetailsItem.SelectedInstructorItemID); lstCourses.Add(courseDetailsItem); itemsInList++; } } } } } else if (!string.IsNullOrEmpty(referenceCourseItemIDs)) { string[] arrItemIDs = referenceCourseItemIDs.Split(','); if (arrItemIDs != null && arrItemIDs.Length > 0) { Item referenceCourseItemFirst = !string.IsNullOrEmpty(arrItemIDs[0]) ? SitecoreUtility.GetItem(new ID(arrItemIDs[0])) : null; Item referenceCourseItemLast = arrItemIDs.Length > 1 && !string.IsNullOrEmpty(arrItemIDs[1]) ? SitecoreUtility.GetItem(new ID(arrItemIDs[1])) : null; Item siblingCourseItem = null; while (itemsInList < maxTeasersPerPage) { if (pageNumber == "0") { //get previous page items siblingCourseItem = referenceCourseItemFirst != null?SitecoreUtility.GetPreceedingSiblingItemByTemplate(referenceCourseItemFirst, References.Templates.CourseDetailsPage.ID, References.Templates.CourseDetails.Fields.IsActive) : null; } else if (pageNumber == "2") { //get next page items siblingCourseItem = referenceCourseItemLast != null?SitecoreUtility.GetSucceedingSiblingItemByTemplate(referenceCourseItemLast, References.Templates.CourseDetailsPage.ID, References.Templates.CourseDetails.Fields.IsActive) : null; } if (siblingCourseItem != null) { referenceCourseItemFirst = siblingCourseItem; referenceCourseItemLast = siblingCourseItem; CourseDetails courseDetailsItem = new CourseDetails(siblingCourseItem); if (courseDetailsItem != null && courseDetailsItem.IsActive) { courseDetailsItem.Instructor = GetInstructor(courseDetailsItem.SelectedInstructorItemID); lstCourses.Add(courseDetailsItem); itemsInList++; } } else { break; } } } } if (lstCourses != null && lstCourses.Count > 0) { //If the 'Previous' button was clicked, then the sibling items are added with the first item in page as reference. //so this list should be reversed ideally. if (lstCourses.Count > 1 && pageNumber == "0") { lstCourses.Reverse(); } showPrevButton = SitecoreUtility.GetPreceedingSiblingItemByTemplate(lstCourses.FirstOrDefault().InnerItem, References.Templates.CourseDetailsPage.ID, References.Templates.CourseDetails.Fields.IsActive) != null; showNextButton = SitecoreUtility.GetSucceedingSiblingItemByTemplate(lstCourses.LastOrDefault().InnerItem, References.Templates.CourseDetailsPage.ID, References.Templates.CourseDetails.Fields.IsActive) != null; } return(lstCourses); }
/// <summary> /// gets courses by page /// </summary> /// <param name="parentItem">If its first page, parent item should be passed. All its child pages will be verified.</param> /// <param name="pageNumber">1 is for first page, 2 is for next page & 0 is for previous page</param> /// <param name="referenceCourseItemID">the course item id of the first or last course teaser on page</param> /// <returns></returns> private Blog GetBlogByPage(string pageNumber, string currentBlogItemID) { Blog blog = null; Item currentBlogItem = null; Item parentItem = null; List <Item> activeBlogItems = null; int indexOfCurrentItem = -1; if (!string.IsNullOrEmpty(pageNumber)) { if (pageNumber == "1" && Sitecore.Context.Item.TemplateID == References.Templates.BlogPage.ID) { blog = new Blog(Sitecore.Context.Item); parentItem = Sitecore.Context.Item.Parent; activeBlogItems = parentItem != null?parentItem.Children .Where(x => x.TemplateID == References.Templates.BlogPage.ID && x.Fields[References.Templates.Blog.Fields.IsActive].Value == "1") .OrderBy(b => Sitecore.DateUtil.ToServerTime(Sitecore.DateUtil.IsoDateToDateTime(b.Fields[References.Templates.Blog.Fields.PostedDate].Value))).ToList() : null; if (activeBlogItems != null && activeBlogItems.Count > 1) { indexOfCurrentItem = activeBlogItems.FindIndex(x => x.ID == Sitecore.Context.Item.ID); } } else if (!string.IsNullOrEmpty(currentBlogItemID) && (pageNumber == "0" || pageNumber == "2")) { currentBlogItem = SitecoreUtility.GetItem(new ID(currentBlogItemID)); parentItem = currentBlogItem != null ? currentBlogItem.Parent : null; activeBlogItems = parentItem != null?parentItem.Children .Where(x => x.TemplateID == References.Templates.BlogPage.ID && x.Fields[References.Templates.Blog.Fields.IsActive].Value == "1") .OrderBy(b => Sitecore.DateUtil.ToServerTime(Sitecore.DateUtil.IsoDateToDateTime(b.Fields[References.Templates.Blog.Fields.PostedDate].Value))).ToList() : null; if (activeBlogItems != null && activeBlogItems.Count > 1) { indexOfCurrentItem = activeBlogItems.FindIndex(x => x.ID == currentBlogItem.ID); Item siblingBlogItem = null; if (pageNumber == "0" && indexOfCurrentItem > 0) { //get previous blog item siblingBlogItem = activeBlogItems[indexOfCurrentItem - 1]; } else if (pageNumber == "2" && indexOfCurrentItem < (activeBlogItems.Count - 1)) { //get next blog item siblingBlogItem = activeBlogItems[indexOfCurrentItem + 1]; } if (siblingBlogItem != null) { blog = new Blog(siblingBlogItem); indexOfCurrentItem = activeBlogItems.FindIndex(x => x.ID == siblingBlogItem.ID); } } } if (blog != null && blog.IsActive) { blog.RelatedPosts = GetRelatedPosts(blog.InnerItem, References.Templates.Blog.Fields.RelatedPosts); blog.PreviousBlogURL = indexOfCurrentItem > 0 ? SitecoreUtility.GetItemURL(activeBlogItems[indexOfCurrentItem - 1]) : ""; blog.NextBlogURL = indexOfCurrentItem < (activeBlogItems.Count - 1) ? SitecoreUtility.GetItemURL(activeBlogItems[indexOfCurrentItem + 1]) : ""; } else { blog = null; } } return(blog); }