Friday, August 29, 2014

Working With Sitecore Fields

We have 4 different ways to work with sitecore fields

  •   Simple Text Value: Excluding the Attachment system field type used to store binary data for media items, Sitecore stores all field values as text. You can access any field as a simple text value.

Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
Sitecore.Data.Items.Item current = master.GetItem (Sitecore.Context.Item.ID);
              lblData.Text =  current["Page Title"] ;
  •  Fields property: You can access any field as an instance of the Sitecore.Data.Fields.Field class using the Sitecore.Data.Items.Item.Fields property.

Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
Sitecore.Data.Items.Item current = master.GetItem (Sitecore.Context.Item.ID);
Sitecore.Data.Fields.Field titleField = current. Fields [“Page Title”];
If (titleField! = null)
lblData.Text = titleField. Value;

  • Using FieldRender Render Method: In presentation components we can use the Field Renderer Render method to output field values.

          lblData.Text = Sitecore.Web.UI.WebControls.FieldRenderer.Render (current, "Page Title"); 
      
  • Using FieldRender web control:

           Add a FieldRenderer web control to a layout or sublayout

           <sc:FieldRenderer runat="server" ID="fieldControl" />

            In the code behind for the layout or sublayout, set properties of the control.

            fieldControl.DataSource = current.Paths.FullPath;     

            fieldControl.FieldName = "title";

Wednesday, August 27, 2014

Working With Sitecore Media Items

To create media items, sitecore provides two templates for each type of media item, a versionable template and unversionable template. In general, versioning of media should only be implemented when versioning is expressly required and implications such as increased database storage space over time are understood.

Media items can be stored in two ways

Database Media Storage: Media items are stored in database as blob.


Advantages:
  •          Media can be published like any other resource.
  •          CMS services such as locking, security, versioning and workflow are supported for media.
  •          Images can be dynamically manipulated, for instance shrinking or stretching.
  •          Changes to the media library do not need to be synchronized with the file system.

Disadvantages:
  •          Very large media can result in performance issues.
  •          URLs for media items are altered, for instance ending in the .ashx extension which invokes ASP.NET processing rather than original file extensions.
  •          Can result in increased database and file system requirements as media are both stored in two databases (master and web) as well as being cached on disk.

Configuration:
  •          Set Media.UploadAsFiles to false in web.config

 File System Media Storage: Media items are stored on file system. Path of the uploaded file would be stored in “File Path” field in sitecore.

Advantages
  •          Media can be manipulated on the file system, for instance copying the media folder to another system.

Disadvantages
  •          For multi-server environments, media must be propagated from the CMS server to the content delivery servers(s) using the Sitecore Staging module.
  •          CMS services such as locking, security, versioning and workflow can be applied to the metadata only. Every change of the file itself will required a new copy of the file in the file system.

Configuration
  •          Set Media.UploadAsFiles to true in web.config 
           <setting name=”Media.UploadAsFiles” value=”true”>

  •          Specify the MediaFolder path in web.config

           <sc.variable name=”mediaFolder” value=”/upload”>

  •          Specify the Media.FileFolder path. Uploaded files will be stored in this folder

           <setting name=”Media.FileFolder” value=”/App_Data/MediaFiles”>

Programmatically create a media item

        string filePath=@"C:\Images\Translate.png";
        string filenamefull = Path.GetFileName (filePath);
        string noextensionname = Path.GetFileNameWithoutExtension (filePath);
        Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
        Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions ();
        options.FileBased = false; //stores the file in database, not as file
        options.AlternateText = noextensionname;
        options.Destination = "/sitecore/media library/images/" + noextensionname;
        options.Database = master;
        options.Versioned = false; // Do not make a versioned template
        options.KeepExisting = false; // Overwrite any existing file with the same name
        Sitecore.Data.Items.MediaItem mediaitem = new Sitecore.Resources.Media.MediaCreator ().CreateFromFile (filePath, options);


Retrieve a media item: You can use the Sitecore.Data.Items.MediaItem class to access media items.

        Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
        Item item = master.GetItem ("/sitecore/media library/Images/Translate");
        If (item! = null)
        {
            MediaItem mediaItem = new MediaItem (item);
            img.ImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl (mediaItem);
        }


If the Sitecore Item you are linking to is a Media Item, you cannot use the LinkManager as this will return the URL to the Sitecore item, not the actual media. Instead use the MediaManager.

Wednesday, August 20, 2014

Working with Sitecore Items

You can use the Sitecore.Data.Items.Itemclass to access any item. Sitecore provides specialized classes to represent specific types as items, such as Sitecore.Data.Items.TemplateItemto represent a data template and Sitecore.Data.Items.MediaItemto represent a media item.

1) Retrieve items

Retrieve item from context
Item current = Sitecore.Context.Item

Retrieve item from master database using item path
Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);
Item current =master.GetItem (“/sitecore/content/Home/Page1”);

Retrieve item from master database using item id
Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);
Item current =master.GetItem (“{BC5E60E8-25A0-4E04-BD60-D919F5E9121F}”);

Retrieve item from master database using fast query

Basics of 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 can be used:
  •  In the Content Editor as a source for List Types fields.
  •  In the Developer Center, in the XPath Builder tab.
  •  In custom .NET code by using the SelectSingleItem () method and the SelectItems () methods of the Sitecore.Data.Database class.
In Content Editor Sitecore Query is used for the items that contain a Source field.
  • Path to the root item:
/sitecore/content/Home/Shapes
This expression returns all the items that are children of the Shapes item.
  • Sitecore Query:

query: /sitecore/content/Home/Shapes
This expression uses Sitecore Query to return the Shapes item.

query: /sitecore/content/Home/Shapes/*
This expression uses the Sitecore Query to return all the items that are children of the Shapes item.
  •          Sitecore Fast Query

Query: fast: /sitecore/content/Home/Shapes
This expression uses Sitecore Fast Query to return the Shapes item.

Query: fast: /sitecore/content/Home/Shapes/*
This expression uses Sitecore Fast Query to return all the items that are children of the Shapes item.

Using API in custom .NET code

Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);
Item [] items = master.SelectItems (“fast: /sitecore/content/Home/*[@@templatename=’Page’]”);


If (items! = null && items. Length > 0)
{
                foreach (Item current in items)
{
                // do work
}
}

2) Create an item
Sitecore.Data.Items.Item.Add () method can be used to create an item. The parent item and the data template for the new item must exist before you create the item.
Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);
Item parentItem = master.GetItem (“/sitecore/content/Home”);
Template templateItem = master.GetTemplate (“User Defined/Page”);
parentItem.Add (“Page2”,templateItem);

3)Publish an item
Sitecore.Publishing.PublishManager.PublishItemcan be used to publish an item.
Database master = Sitecore.configuration.Factory.GetDatabase (“master”);
Database target = Sitecore.configuration.Factory.GetDatabase (“web”);
Database [] targetDatabases = {target};
Item current = master.GetItem (“/sitecore/content/Home”);
Sitecore.Globalization.Language [] languages = master.Languages;
bool deep = true;
bool compareRevisions = true;
Sitecore.Publishing.PublishManager.PublishItem (current, targetDatabases, languages, deep, compareRevisions);

deep = true publishes an item and all of its publishable descendants.
deep = false publishes only the current item.
compareRevisions = true does a smart publish. Sitecore compares the value of the Revision field in the versions of the item in the source and the target database during the publishing operation. If the values of the Revision fields are the same, the version is not published.
compareRevisions = falsedoes a full publish. Sitecore publishes items independently of the Revision field values.

By default sitecore context user would be Anonymous, so add / edit / delete / publish would throw an exception due to access rights. We have to use any one of the following way to give access rights
  •  Using Sitecore.Security.Accounts.UserSwitcher : An instance of the UserSwitcher class executes the block of code in the context of a specific user. The user can be an Administrator and can do everything or we can create a “service user” with only specific permissions like giving only add or edit access.

Using (new Sitecore.Security.Accounts.UserSwitcher (Sitecore.Security.Accounts.user.FromName (@”sitecore\admin”,false)))
{
                //do work
}

  •       Using Sitecore.SecurityModel.SecurityDisabler:Sitecore will not do any permission checks when SecurityDisabler is used. In fact, the result will be the same as if you use the UserSwitcher () with an administrator, but using this will not give us any control on the context.

In case of publishing, we can set Publishing.CheckSecurity setting in the Web.config file to false to disable security checks while publishing.

4) Edit an item
Sitecore APIs that update items may throw exceptions if the item is not in editing mode. You can place an item in editing mode using methods of the Sitecore.Data.Items.Item.Editing property, or by using the Sitecore.Data.Items.EditContext class.

  •         Editing property

                 Item current = master.GetItem (“/sitecore/content/Home/Page2”);
                 try
                 {
                              current.Editing.BeginEdit ();
                              //do work
                             current.Editing.EndEdit ();// commits changes
                   }
                 catch (Exception ex)
                  {
                             Current.Editing.CancelEdit (); // does not commit changes
                  }

        When using Editing property, EndEdit () would commit the changes and CancelEdit () does not commit the changes.

  •          EditContext class

                 Item current = master.GetItem (“/sitecore/content/Home/Page2”);
                 using (new Sitecore.Data.Items.EditContext (current))
                 {
                               //do work
                 }

The closure of the using statement invokes the Sitecore.Data.Items.EditContext.Dispose () method, which commits any changes made within that segment of code.

5)Delete an item
                Database master = Sitecore.Configuration.Factory.getDatabase (“master”);
Item current = master.GetItem (“/sitecore/content/Home/Page2”);

                Current.Delete ();

Monday, August 18, 2014

Sitecore Databases

Sitecore data is stored in multiple databases. We have to use Sitecore.Data.Database class to access sitecore databases. Default sitecore configuration includes three databases.

·         Master – Contains the data being edited in the Content Manager.
·         Web – Contains published versions of Master database used to display the web site.
·         Core – Contains data controlling the Content Manager.

When the code executes on the web site (that is a layout or an XSL extension), the context database will be web. When the code is executing within the Content Manager, the context database will be core.

1) Access data base by name
To obtain a reference to a database, use the Factory class.
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);

2) Access context database
Whenever the user code is invoked by Sitecore, a context database is automatically assigned which can be assessed using the Context class.
Sitecore.Data.Database current = Sitecore.Context.Database;

3) Access content database
Content Editor interact with the content database. The default content database is the Master database. User interfaces such as the Sitecore Desktop allow the user to change the content database to another database.

To access currently active content database we use ContentDatabase property.

Sitecore.Data.Database content = Sitecore.Context.ContentDatabase;

The ContentDatabase property will be empty when executing in the web site context. Only content editors (such as the Content Manager) will normally support this property.

4) Publish a database
Publishing copies an item from master database to the web database.

The 3 ways to publish items are

1.       Republish: This method will publish every item, even items that have not changed. If you are publishing on a large website this method of publishing can take a long time. It is intended to be used when you are publishing to a new web database, if you are restoring a backup of the master database or similar situations.

2.       Smart publish: This method compares each item in the master database with the item in the web database. In Sitecore each item has an internal revision identifier and it is this identifier that is compared. If they are different, that is, the item has been changed since it was last published, the item will be published. Even though this method is still comparing each item, it is much faster than doing a republish.

3.       Incremental publish: Every time an item is changes, it is added to the publishing queue. This applies both to changes made through the Sitecore user interface and changes made programmatically. Doing an incremental publish will only publish the items in the publishing queue.Therefore only items that has been changed will be published and sitecore does not have to do any comparisons to figure out which items has been changed. This way of publishing is therefore by far the fastest. Republish and smart publish do not use the publishing queue.

To publish the Master database incrementally in every language to the Web database
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase (“master”);
Sitecore.Data.Database target = Sitecore.Configuration.Factory.GetDatabase (“web”);
Sitecore.Data.Database[] targetDatabases ={target};
Sitecore.Globalization.Language[] languages = master. Languages;
Sitecore.Publishing.PublishingManager.PublishIncremental (master, targetDatabases, languages);

PublishSmart () is used for smart publishing.
Republish () is used for all complete publishing of the website.

Note: If you set updateStatistics property to false while creating an item programmatically and want to use PublishSmart (), you should manually set the Revision field to a new Guid. 

Friday, August 15, 2014

Understanding Sitecore Presentation Objects

·         Layouts – A Sitecore layout defines the overall appearance of a generated web page. Layouts are based on .NET Web Forms (aspx files) and support all functionality associated with .NET web forms.

·         Placeholders –Placeholders determine which presentation objects to include in a specific area of a layout depending on which item in the content tree has been requested by a site visitor.

·         XSLT Renderings - A Sitecore XSLT Rendering transforms content from Sitecore’s content tree into appropriate presentation language.

·         Sublayouts – A Sitecore sublayout defines the appearance of a portion of a generated web page. Sublayouts are based on .NET User Controls (ascx files) and support all functionality associated with .NET User Controls.


·         Devices – Sitecore allows developers to define custom devices which automatically detect what hardware or software visitors are using when requesting a page. Developers then indicate which layout and other presentation objects Sitecore should use to generate the page targeted to that particular device.

Thursday, August 14, 2014

Introduction to sitecore

Sitecore is a content management system and a website development environment. Sitecore is built on top of the Microsoft.NET foundation and supports everything that the Microsoft.NET platform supports. Sitecore also leverages many standard technologies, such as XML, XSLT, XPATH and other technologies from W3C and others. Sitecore takes content stored in a data source and dynamically transforms it into web pages.

In Sitecore, developers create templates which are similar to relational database table schemas. A template defines the fields associated with a set of items. An item is like a relational database record and a field is like a relational database column.


However, the difference between Sitecore storage and relational databases is, Sitecore rather than storing items in tables, organizes items into a hierarchy called the content tree. The content tree is similar to the Windows file system. The main difference is that the Windows file system tree is made up of folders which may contain other folders and/or documents containing data; whereas the Sitecore content tree is made up of items which contain data but can also act like folders and have sub-items.