Friday, September 12, 2014

Creating A Sitecore Page With ORM Tool ( Glass Mapper)

Glass Mapper is an object mapping framework (ORM tool) for mapping Sitecore items directly onto an object model allowing you to model your entire Sitecore solution as a data model. The framework handles converting data to and from fields and pulling data from related items. It also helps in making Sitecore code unit testable.

Below example uses CastleWindsor dependency injection framework.


Step 1: Install Glass.Mapper.Sc.CastleWindsor from NuGet packages


Step 2: Create two base templates “Page Title” and “Page Description” 











Step 3: Create a page inheriting from two templates














Step 4: Insert standard values by selecting “Builder” tab of data template and clicking on “Options” in the main menu.

















Step 5: Create a layout and put necessary place holders.



















In DemoLayout.aspx

<div id="MainPanel">

      <sc:placeholder key="main" runat="server" />

   </div>

Placeholder is an area of the page to support the user adding controls. Placeholders can be placed on layouts, sublayouts and view renderings.

Step 6: Create a sub layout


Step 7: Create a Model based on the data template

using System;
using System.Web;
using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Models.Demo
{

    public class DemoPage
    {

        [SitecoreField("Page Title")]
        public virtual string PageTitle { get; set; }
        [SitecoreField("Page Description")]
        public virtual string PageDescription { get; set; }

    }

}

Step 8: Load model of the current item using SitecoreContext

using Glass.Mapper.Sc;
using Glass.Mapper.Models.Demo;

public partial class layouts_PageData : System.Web.UI.UserControl
{

    public DemoPage Model { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {

        var context = new SitecoreContext();
        Model = context.GetCurrentItem<DemoPage>();

    }

}

Step 9: Render data from model on to the ascx page.

<h1><%= Model.PageTitle%></h1><br />
<%= Model.PageDescription %>

Step 10: Create a place holder setting item and allow above sublayout. Placeholder settings provide all of the details for the placeholder to Page Editor including the controls that can be added.



















Step 11: Assign layout, sub layout and placeholder settings to the template.

To set layout, go to standard values, click on edit and set the layout













Click on controls and set the sub layout


























Set the placeholder setting



























Step 12: Set Insert Options for the home item template to “Page” template.


















Create a page based on the template.



Thursday, September 11, 2014

Basic Sitecore Page Creation

Step 1: Create two base templates “Page Title” and “Page Description”
 Step 2: Create a page inheriting from two templates













Step 3: Insert standard values by selecting “Builder” tab of data template and clicking on “Options” in the main menu.
















Step 4: Create a layout and put necessary place holders.


















In DemoLayout.aspx

<div id="MainPanel">

      <sc:placeholder key="main" runat="server" />

   </div>

Placeholder is an area of the page to support the user adding controls. Placeholders can be placed on layouts, sublayouts and view renderings.

Step 5: Create a sub layout
 In PageData.ascx, put two literal controls

<asp:Literal ID="ltPageTitle" runat="server"></asp:Literal><br />
<asp:Literal ID="ltPageDescription" runat="server"></asp:Literal>

In PageData.ascx.cs

Item i = Sitecore.Context.Item;
if(i != null)
{
            ltPageTitle.Text = i.Fields["Page Title"].Value;
            ltPageDescription.Text = i.Fields["Page Description"].Value;
 }

Step 6: Create a place holder setting item and allow above sublayout. Placeholder settings provide all of the details for the placeholder to Page Editor including the controls that can be added.


















Step 7: Assign layout, sub layout and placeholder settings to the template.
To set layout, go to standard values, click on edit and set the layout












Click on controls and set the sub layout


























Set the placeholder setting



























Step 8: Set Insert Options for the home item template to “Page” template.


















Step 9: Create a page based on the template.

Wednesday, September 10, 2014

Working With Sitecore Developer Types Fields

ICON: The Icon field type associates a themed icon with each item.  "/~/icon/" should be prefixed to render the icon.

Sitecore.Data.Fields.Field iconField = current.Fields ["Icon Field"];
Image1.ImageUrl = "/~/icon/" + iconField.Value;

IFRAME: The IFRAME field type display a web page within a field. The source property of the field specifies the URL to display.

Tristate: The Tristate field type allows the user to select one of the three options: Default, Yes and No. If the user selects Default, the value of the field would be empty string. If the user selects Yes, the value would be number 1. If the user selects No, the value would be number 0.

Sitecore.Data.Fields.ValueLookupField tristateField = current.Fields ["Tristate Field"];

ltPageData.Text = tristateField.Value;

Tuesday, September 9, 2014

Working With Sitecore List Fields

Working with Single list item

     Sitecore.Data.Fields.ReferenceField refDroplinkField = current.Fields ["Drop Link Field"];
            Sitecore.Data.Fields.ReferenceField refDroplistField = current.Fields["Drop List Field"];
            Sitecore.Data.Fields.ReferenceField refGroupedDroplinkField = current.Fields ["Grouped Droplink Field"];
            Sitecore.Data.Fields.ReferenceField refGroupedDroplistField = current.Fields ["Grouped Droplist Field"];
            Sitecore.Data.Fields.ReferenceField refDroptreeField = current.Fields ["Drop Tree Field"];
            if (refDroptreeField != null && refDroptreeField.TargetItem != null)
            {
                //ltPageData.Text = refDroplinkField.TargetItem.Fields["Category Name"].Value;
                //ltPageData.Text = refDroplistField.Path;
                //ltPageData.Text = refGroupedDroplinkField.TargetItem.Fields["Category Name"].Value;
                // ltPageData.Text = refGroupedDroplistField.Path;
                ltPageData.Text = refDroptreeField.TargetItem.Fields["Category Name"].Value;
            }

Note: Droplist data type only stores the string value of the item that was chosen by the content editor, not the GUID that would allow us to get back to the item and gets its other fields. So aside from doing string matching on the name of the item, there’s no way to get back to the actual item that was chosen.

Working with Multi list item

        Sitecore.Data.Fields.MultilistField refMultilistField = current.Fields["Multi List Field"];
            if (refMultilistField != null)
            {
                Item[] items = refMultilistField.GetItems();
                List<Item> check = items.Where(x => x.Fields["Category Name"].Value == "Liquor").ToList();
            }

Treelist / TreelistEx:

The value of Treelist/ TreelistEx fields are very similar to the value of the Checklist and Multilist field in that it is a pipe-separated list of IDs of the selected items.

For performance, you should use the TreelistEx field type in your data templates instead of the Treelist field type. With a Treelist, the client renders the selection tree and the list of selected items whenever the user selects an item that contains the field. With a TreelistEx, the client renders only the list of selected items, and does not render the selection tree until the user clicks the Edit command above the field.

Source Parameters

DataSource: The root item the field points to. Must be a path.
Datasource=/sitecore/common/categories

ExcludeTemplatesForSelection: This is a comma separated list of template names that should NOT be allowed for selection. These items may need to appear in the treelist to show sub-items, but these cannot actually be selected. For example folders.
DataSource=/sitecore/common/categories&ExcludeTemplatesForSelection=Folder

IncludeTemplatesForSelection: This is a comma separated list of template names that should be allowed for selection. If this is defined, only items of templates defined in this list can be selected.
DataSource=/sitecore/common/categories&IncludeTemplatesForSelection=Category

ExcludeTemplatesForDisplay: This is a comma separated list of templates that should not be displayed in the treelist. Any sub-items of these templates will also not display because they are hidden.
DataSource=/sitecore/common/categories&ExcludeTemplatesForDisplay=Categoty

IncludeTemplatesForDisplay: This is a coma separated list of template names that should be displayed in the treelist. If this is defined, only items of templates defined in this list can be displayed. An important thing to note here is that for any templates in this list, the parent items must at least be displayed in the treelist in order for these to show up.
DataSource=/sitecore/common/categories&IncludeTemplatesForDisplay=Categoty

IncludeItemsForDisplay: This is a comma separated list of GUIDs that should be displayed.
DataSource=/sitecore/common/categories&IncludeItemsForDisplay= {93FBD42C-458A-4C9C-A999-1EE2B651C6E1}, {3ABCX2C-458A-4C9C-A999-1EE2B651C6E1}

ExcludeItemsForDisplay: This is a comma separated list of GUIDs that should NOT be displayed.
DataSource=/sitecore/common/categories&ExcludeItemsForDisplay= {93FBD42C-458A-4C9C-A999-1EE2B651C6E1}, {3ABCX2C-458A-4C9C-A999-1EE2B651C6E1}

AllowMultipleSelection: This defines whether or not an editor can select the same item more than once. It takes a word yes.
DataSource=/sitecore/common/categories&AllowMultipleSelection=yes

DatabaseName: Changes the database name being referenced. Useful if using an external data provider.

Working with Name Value List Field:

The Name Value List field type allows the user to enter values for zero or more arbitrary keys. Sitecore stores the values entered as a list of key=value pairs separated by ampersands “&”.

Option 1:

  Sitecore.Data.Fields.NameValueListField refNameValuelistField = current.Fields["Name Value List Field"];
        if (refNameValuelistField != null )
        {
            NameValueCollection nameValueCollection = refNameValuelistField.NameValues;
            foreach (var nv in nameValueCollection)
            {
                ltPageData.Text += nameValueCollection[nv.ToString()] + "<br/>";
            }
        }

Option 2:

        Sitecore.Data.Fields.MultilistField refMultilistField = current.Fields ["Name Value List Field"];
        if (refMultilistField != null && refMultilistField.List != null)
        {
            string _urlParamsToParse = refMultilistField.List.ToString ();
            NameValueCollection nameValueCollection = Sitecore.Web.WebUtil.ParseUrlParameters(_urlParamsToParse);
            foreach (var nv in nameValueCollection)
            {
                ltPageData.Text += nameValueCollection[nv.ToString()] + "<br/>";
            }
        }

Working with Name Lookup Value List Field:


Name Lookup Value field takes a data source parameter which is used to pick values for entered keys.









        Sitecore.Data.Fields.MultilistField refMultilistField = current.Fields["Name Lookup Value List Field"];
        if (refMultilistField != null && refMultilistField.List != null)
        {
            string _urlParamsToParse = refMultilistField.List.ToString();
            NameValueCollection nameValueCollection = Sitecore.Web.WebUtil.ParseUrlParameters(_urlParamsToParse);
            foreach(var nv in nameValueCollection)
            {
                Item i = master.GetItem(nameValueCollection[nv.ToString()]);
                ltPageData.Text += i.Fields["Category Name"] + "<br/>";
            }
        }

Note: Name Lookup Value List field stores Item Id for each key











Monday, September 8, 2014

Querying Items from Sitecore

Sitecore data can be retrieved using following approaches
  •          Sitecore Query
  •          Fast Query
  •          Lucene

Sitecore Query: Sitecore Query is most flexible in terms of filtering items right in the query using XPath functions. However, the more complex your query is, the longer it will take to run. This should be used when we try to query less than 100 items.

Fast Query: Sitecore fast query is designed for retrieving and filtering items from the Sitecore database. Sitecore Fast Query uses the database engine to execute queries. Sitecore Fast Query has the following benefits compared to the standard Sitecore Query
Improved performance – queries are executed by the SQL engine and as a result the scalability and performance of the SQL engine is not limited by .NET or by Sitecore.
 Consumes less memory – Sitecore Query loads every item that it touches into memory (cache) and this can fill the cache with unnecessary information. Sitecore Fast Query only loads the items from the result set and this minimizes the pressure on the cache.
Sitecore Fast Query is similar to XPath and Sitecore Query statements in many ways. The most notable difference in using Fast Query is that you use the fast: keyword. Sitecore fast query should be used when we try to query more between 100 to 1000 items.

Lucene: Lucene uses search indexes to query content and filter. This requires additional configuration upfront and maintenance of search index.

General syntax for Sitecore Query

Symbol
Meaning
/
The root of the content tree or parent-child relationship
//
Selects items from descendants of the specified item
..
Selects parent of the specified item
*
Wildcard, match items of any name
[ ]
Search criteria related to fields and XML element attributes
@
A field defined in the item’s base template
@@
An XML element attribute. All Sitecore items contain following attributes
·         name : The item’s name
·         key : The item’s name in all lower-case characters
·         id : The item’s GUID
·         tid : The item’s base template’s GUID
·         mid : The branch template used to create item, if any
·         sortorder: The item’s sort order
·         templatename : The item’s base template’s name
·         parented : The item’s parent’s GUID

To work with Sitecore queries create following structure based on two templates Category & MobileCategory having 3 fields.


/sitecore/content/Common/Categories/*
Grabs all children under Categories item

/sitecore/content/Common/Categories/*[@@templatename='Category']
Grabs all children of template Category under Categories item

/sitecore/content/Common/*/*[@@templatename='Category']
Checks all subfolders under folder Common and grabs all items of templatename Category

/sitecore/content/Common/Categories/*[@@templateid='{3B0461BF-9ABC-4AF1-B937-C8D225FC2313}']
/sitecore/content/Common/Categories/*[@@tid='{3B0461BF-9ABC-4AF1-B937-C8D225FC2313}']
Grabs all children of a specific template ID under Categories item
tid is the item's base template's GUID

/sitecore/content/Common/*/*[@@name='Electronics']
Grabs all items with name Electronics (exact match).

/sitecore/content/Common/*/*[@@key='electronics']
Grabs all items with name Electronics (items name in lower case characters)

/sitecore/content/Common/*/*[@@id='{E00B1D51-B118-480A-A10F-0CE4BF560B5B}']
Grabs an element with item id under Common item

fast:/sitecore/content/common/*/*[@@parentid='{A85663D5-B794-4B27-A4F9-B1A62241E8E1}']
Grabs all the descendants of the Common item whose parent item has the specified ID
@@parentid only works in fast query.

/sitecore/content/common//Electronics/..
Grabs the parent of the Electronics item that is stored under Common item

/sitecore/content/common/*/*[@Category Name='Electronics']
Grabs all items whose field "Category Name" has a value "Electronics"

/sitecore/content/common/*/*[@IsAvailable='1']
Grabs all items under Common item which have the IsAvailable check box set to true

/sitecore/content/common/*/*[@@templatename='Category' and @IsAvailable='1']
Grabs all items under Common item which template is Category and IsAvailable is set to true

fast:/sitecore/content/common/*/*[@Category Name='%Elec%']
Grabs all items under Common item whose Category Name contains string "Elec"

/sitecore/content/common/#Old-Categories#/*
"#" is used to escape special characters or special words like "and" "or".
Grabs all items under "Old-Categories" item

/sitecore/content/common/Categories/*[startswith(@Category Name,'E')]
fast:/sitecore/content/common/Categories/*[@Category Name = 'E%']
Grabs immediate sub items under Categories whose field "Category Name" starts with letter "E"
fast query doesnt support XPath functions

XPath functions
  •          position () Determine the numeric position of the node
  •         last () Determine the last node in the node set
  •          concat () Concatenate two strings together
  •          starts-with () Determine if a string begins with another string
  •          contains () Determine if a string contains another string
  •          not () Negate a Boolean value

/sitecore/content/common/Categories/*[position () > 2]
Grabs immediate sub items under Categories whose position is greater than 2

/sitecore/content/common/Categories/*[last ()]
Grabs the last node in Categories list

/sitecore/content/common/Categories/*[contains (@Category Name,'E')]
Grabs immediate sub items under Categories whose Category Name contains character ‘E’

/sitecore/content/common/Categories/*[not (startswith (@Category Name,'E'))]

Grabs immediate sub items under Categories whose field "Category Name" does not starts with letter "E"

AXES

ancestor
Returns all the ancestors of the specified item (same as XPath)
parent
(..) Returns the parent item of the  specified item
child
(/*) Returns all the children of the specified item
descendant
(//*) Returns all the descendants of the specified item

The axis component of a query determines the direction of the node selection in relation to the context node.
/sitecore/content//*[@Category Name='Electronics']/ancestor::*
Returns all the ancestors of specified item

/sitecore/content//*[@Category Name='Electronics']/parent::*
Returns the parent Item of the specified item. (..) Similar in XPath

/sitecore/content//*[@Category Name='Electronics']/child::*
Returns all the children of the specified item. (/*) similar in XPath

/sitecore/content//*[@Category Name='Electronics']/descendant::*
Returns all the descendants (child or child of a child) of the specified item. (//*) similar in XPath

Friday, September 5, 2014

Working with Sitecore Link Fields

General Link Field / General Link Search Field

Sitecore.Data.Fields.LinkField class is used to access the data template fields of type general link. 














                                                            

Access a link type field 

Sitecore.Data.Fields.LinkField lnkField = current.Fields ["General Link Field"];
        if (lnkField! = null)
        {
            if (lnkField.LinkType == "external" || lnkField.LinkType == "anchor" || lnkField.LinkType == "mailto" || lnkField.LinkType == "javascript")
            {
                HyperLink1.Text = lnkField.Text;
                HyperLink1.NavigateUrl = lnkField.Url;
            }
            if (lnkField.LinkType == "internal")
            {
                HyperLink1.Text = lnkField.Text;
                HyperLink1.NavigateUrl = Sitecore.Links.LinkManager.GetItemUrl (lnkField.TargetItem);
            }
            else if (lnkField.LinkType == "media")
            {
               Image1.ImageUrl = Sitecore.StringUtil.EnsurePrefix ('/',   Sitecore.Resources.Media.MediaManager.GetMediaUrl (lnkField.TargetItem));
          }
        }

Edit Link Field – External

using (new Sitecore.SecurityModel.SecurityDisabler ())
        {
            Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
            Sitecore.Data.Items.Item current = master.GetItem (Sitecore.Context.Item.ID);
            current.Editing.BeginEdit ();
            Sitecore.Data.Fields.LinkField lnkField = current.Fields["General Link Field"];
            if (lnkField != null)
            {
                lnkField.LinkType = "external";
                lnkField.Url = "http://sitecore.com";
            }
            current.Editing.EndEdit ();
        }

Edit Link Field – Internal

using (new Sitecore.SecurityModel.SecurityDisabler ())
        {
            Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
            Sitecore.Data.Items.Item current = master.GetItem (Sitecore.Context.Item.ID);
            Sitecore.Data.Items.Item editItem = master.GetItem ("/sitecore/content/Home/Page1");
            current.Editing.BeginEdit ();
            Sitecore.Data.Fields.LinkField lnkField = current.Fields ["General Link Field"];
            if (lnkField!= null)
            {
                lnkField.Clear ();
                lnkField.LinkType = "internal";
                Sitecore.Links.UrlOptions urlOptions = Sitecore.Links.LinkManager.GetDefaultUrlOptions ();
                urlOptions.AlwaysIncludeServerUrl = false;
                lnkField.Url = Sitecore.Links.LinkManager.GetItemUrl (editItem, urlOptions);
                lnkField.TargetID = editItem.ID;
            }
            current.Editing.EndEdit ();
        }


Edit Link Field – Media

using (new Sitecore.SecurityModel.SecurityDisabler ())
        {
            Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
            Sitecore.Data.Items.Item current = master.GetItem (Sitecore.Context.Item.ID);
            Sitecore.Data.Items.Item editItem = master.GetItem ("/sitecore/media library/Images/Translate");
            current.Editing.BeginEdit ();
            Sitecore.Data.Fields.LinkField lnkField = current.Fields ["General Link Field"];
            if (lnkField != null)
            {
                lnkField.Clear ();
                lnkField.LinkType = "media";
                lnkField.Url = editItem.Paths.MediaPath;
                lnkField.TargetID = editItem.ID;
            }
            current.Editing.EndEdit ();
        }



Monday, September 1, 2014

Working With Sitecore Simple Type Fields

Checkbox field:

Checkbox field stores the one character (“1”) when selected.

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase ("master"); Sitecore.Data.Items.Item home = master.GetItem ("/sitecore/content/home"); Sitecore.Data.Fields.CheckboxField checkboxField = home.Fields ["checkboxfield"]; 
if (checkboxField != null && checkboxField.Checked)
{ 
 //TODO
}

Date and Date time fields:

You can use the Sitecore.Data.Fields.DateField class to access data template fields of type Date and Datetime. The Sitecore.Data.Fields.DateField.Value property contains the date and time as a string in the ISO format used by Sitecore (yyyyMMddTHHmmss). You can convert a value in the ISO format to a System.DateTime structure using the Sitecore.DateUtil.IsoDateToDateTime() method. Alternatively, you can access the Sitecore.Data.Fields.DateField.DateTime property.

Sitecore.Data.Fields.DateField dateField = current.Fields ["Date Time"];
if(dateField != null)
{
    DateTime dt1 = Sitecore.DateUtil.IsoDateToDateTime(dateField.Value);
    DateTime dt2 = dateField.DateTime;
}

Image field:

Sitecore.Data.Fields.ImageField imgField = current.Fields ["Image"];
if (imgField != null)
{
     Image1.ImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl (imgField.MediaItem);
 }

File field:

Sitecore.Data.Fields.FileField fileField = current.Fields ["File"];
if (fileField! = null)
{
     Image1.ImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl (fileField.MediaItem);
 }

Word Document field:

Sitecore.Data.Fields.WordDocumentField class is used to access the value of the Word Document field. Sitecore.Data.Fields.WordDcocumentField.Html property is used to access the HTML representation of the field value. Sitecore.Data.Fields.WordDocumentField.PlainText property is used to access the plain text representation of the field value. Sitecore.Data.Fields.WordDocumentField.Styles property is used to access the cascading style sheet code associated with the HTML.

Sitecore.Data.Fields.WordDocumentField wordField = current.Fields ["Word Document"];
if (wordField! = null)
{
      // ltPageData.Text = wordField.Html;
         ltPageData.Text = wordField.PlainText;

 }