Showing posts with label Glass. Show all posts
Showing posts with label Glass. Show all posts

Tuesday, December 8, 2015

Instantiating Glass SitecoreContext

Glass.Mapper.Sc.SitecoreContext can only be instantiated in a constructor.

public class TravelDealsApplicationLogic : BaseApplicationLogicClass, ITravelDealsApplicationLogic
    {
        #region constructor
        /// <summary>
        /// constructor to initialize the key
        /// </summary>
        /// <param name="apiKey"></param>
        public TravelDealsApplicationLogic(string apiKey)
        {
            ApiKey = apiKey;
            this.SitecoreContext = new SitecoreContext();
        }

        #endregion

        #region PRIVATE PROPERTIES

       
             private char[] Delimeter = new char[] { '|' };


             protected readonly SitecoreContext SitecoreContext;

Tuesday, September 22, 2015

Logbook Group

using System.Linq;
using System;
using System.Collections.Generic;
using Glass.Mapper.Sc;
using Glass.Mapper.Sc.Web.Ui;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq.Utilities;
using Sitecore.Data;
using Sitecore.Diagnostics;
using TxtAv.Sc.Search.SearchResultItems;
using TxtAv.Sc.Search.Util;
using TxtAv.TDS.CodeGeneration.Models.sitecore.templates.TxtAv.Logbook;

namespace TxtAv.Web.Sublayouts.Shared.Components
{
    public partial class LogbookGroup : GlassUserControl<TDS.CodeGeneration.Models.sitecore.templates.Shared.Components.LogbookGroup>
    {
        protected List<BaseLogbookEntry> LogbookItems = new List<BaseLogbookEntry>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Model.EntriesCount == 0)
            {
                Log.Warn("TxtAv logbook page size is not set or is set to zero. Defaulting to four entries", this);
                Model.EntriesCount = 4;
            }

            ISearchIndex index = ContentSearchManager.GetIndex(SearchUtil.Settings.IndexName);
            using (var context = index.CreateSearchContext())
            {
                List<ID> templatesIdsToFind = new List<ID>
                        {
                            ILogbookArticleEntryConstants.TemplateId,
                            ILogbookPhotoEntryConstants.TemplateId,
                            ILogbookVideoEntryConstants.TemplateId,
                            ILogbookCampaignEntryConstants.TemplateId
                        };

                // Build an "or" predicate for each type
                var typePredicate = PredicateBuilder.True<LogbookSearchResultItem>();
                typePredicate = templatesIdsToFind.Aggregate(typePredicate,
                    (current, id) => current.Or(l => l.TemplateId == id));

                // Build an "or" predicate for each category
                var categoryPredicate = PredicateBuilder.True<LogbookSearchResultItem>();
                foreach (Guid guid in Model.Categories)
                {
                    ID id = new ID(guid);
                    categoryPredicate = categoryPredicate.Or(l => l.Categories.Contains(id));
                }

                var queryable = context.GetQueryable<LogbookSearchResultItem>()
                    .Where(item => item.LatestVersion)
                    .Where(typePredicate)
                    .Where(categoryPredicate)
                    .Where(item => item.Language == Sitecore.Context.Language.Name)
                    .OrderByDescending(item => item.ModifiedEntryDate)
                    .Take(Model.EntriesCount);  

                // Get the results
                var results = queryable.GetResults();

                LogbookItems = results.Hits
                    .Select(item => item.Document.GetItem().GlassCast<BaseLogbookEntry>())
                    .Where(item => item != null).ToList();
            }
        }
    }

}

<div class="row full-width logbook">
       <div class="small-10 small-centered columns">
              <h2><%=Model.Title %></h2>
         <%if (LogbookItems.Any())
          { %>
                  <ul class="small-block-grid-1 medium-block-grid-3 large-block-grid-4">
                 <%foreach (TxtAv.TDS.CodeGeneration.Models.sitecore.templates.TxtAv.Logbook.BaseLogbookEntry item in LogbookItems)
                  {
                      string inlineStyle = !string.IsNullOrEmpty(item.Image.Src) ?
                        string.Format("background-image: url('{0}');", item.Image.Src) :
                        string.Empty;
                       %>
                             <li class="logbook-item">                
                        <a style="<%= inlineStyle %>" href="<%= item.Url %>" target="_blank">
                            <%= RenderImage(item, x => x.Icon) %>
                            <label><%= item.Title %><br><span><%= item.LinkText %> <i class="fa fa-angle-right"></i></span></label>                       
                        </a>
                             </li>
                <% } %>
                  </ul>
        <%} %>
       </div>

</div>

Foreach vs Select

LogbookItems = results.Hits
                    .Select(item => item.Document.GetItem().GlassCast<BaseLogbookEntry>())
                    .Where(item => item != null).ToList();

 VS

 foreach (var hit in results.Hits)
 {
      BaseLogbookEntry entry = hit.Document.GetItem().GlassCast<BaseLogbookEntry>();
      if (entry != null)
      {
           LogbookItems.Add(entry);
      }

 }

Thursday, September 10, 2015

Glass Casting


To cast a list of Guilds (Treelist or Multilist field value):

if (Model.LogbookEntries != null && Model.LogbookEntries.Any())
{
     List<Guid> manuallySelectedEntires = Model.LogbookEntries.ToList();
     LogbookItems = manuallySelectedEntires.Select(x => SitecoreContext.GetItem<BaseLogbookEntry>(x)).ToList();

}
--------------------------------------------------------------------------------------------------------

To cast a SC item:

Item tracksFolder = Sitecore.Context.Database.GetItem("{A248A5F4-87CD-4BDD-9A6E-AA82986F7E2C}");


var glassItem = tracksFolder.GlassCast<IGlassBase>(false, true);

-------------------------------------------------------------------------------



To cast children of a SC Item:

using Glass.Mapper.Sc;



List<LogbookTrack> Tracks = tracksFolder.GetChildren().Select(item => item.GlassCast<LogbookTrack>()).ToList();

-------------------------------------------------------------------------------


To cast results of a SC content search:

ISearchIndex index = ContentSearchManager.GetIndex(SearchUtil.Settings.IndexName);
             using (var context = index.CreateSearchContext())
             {
                 List<ID> templatesIdsToFind = new List<ID>
                    {
                        ILogbookArticleEntryConstants.TemplateId,
                        ILogbookPhotoEntryConstants.TemplateId,
                        ILogbookVideoEntryConstants.TemplateId
                    };

                 // Build an "or" predicate for each type
                 var typePredicate = PredicateBuilder.True<LogbookSearchResultItem>();
                 typePredicate = templatesIdsToFind.Aggregate(typePredicate, (current, id) => current.Or(l => l.TemplateId == id));


                 var results = context.GetQueryable<LogbookSearchResultItem>()
                     .Where(typePredicate)
                     .Where(item => item.Language == Sitecore.Context.Language.Name);
                     //.Where(item => item.Content.Contains(searchTerm));

                 int count = results.Count();

                 foreach (var hit in results)
                 {
                     BaseLogbookEntry entry = hit.GetItem().GlassCast<BaseLogbookEntry>();
                     if (entry != null)
                     {
                         LogbookItems.Add(entry);
                     }
                 }

GlassUserControl


User control to inherti from GlassUserControl (Glass.Mapper.Sc.dll) of either custom type (template) or IGlassBase to get:

GetRenderingParameters,
RenderLink,
RenderImage,
GetModel(),
Editable,
InferType, etc

public partial class LogbookNav : GlassUserControl<IGlassBase>

==================





Monday, June 22, 2015

Editable


The Editable method doesn't always work. Have to specifically tell it which type it is.


Tuesday, June 16, 2015

Glass








If Glass suddenly stops mapping correctly and the field you expect is null do this: