Tuesday 27 May 2014

Difference between direct casting, IS and AS operator in C#

Leave a Comment
In this blog I am going to explain difference between direct casting (normal typecasting), IS and AS operator in C#. In C#, we can type cast data from one data type to another data type using below methods:
  1. Using IS operator
  2. Using AS operator
  3. Direct casting or normal typecasting
1. Using IS operator: IS operator returns true if an object can be cast to a specific type otherwise false.  Since the evaluation result is always a Boolean value so IS operator will never throw an exception.
    class Program
    {
        static void Main(string[] args)
        {
            object number = 6.3;

            //Check if number can be cast to int
            if (number is int) 
            {
                Console.WriteLine("Number can be cast to int");
            }
            else
            {
                Console.WriteLine("Number cannot be cast to int");
            }
        }
    }
Above code will print "Number cannot be cast to int" as number = 6.3 is a float value.

2. Using AS operator: AS operator tries to cast an object to a specific type. It returns null on conversion failure instead of raising an exception.
class Program
    {
        static void Main(string[] args)
        {
            object obj = new object();
            obj = 16;
            string str = obj as string; // str == null

            if (str != null)
            {
                Console.WriteLine("Value is " + str);
            }
            else
            {
                Console.WriteLine("Value is null");
            }           
        }
    }
Above code will print "Value is null".

3. Direct casting or normal typecasting: Direct casting or normal typecasting is most common way of casting one object to another data type. However it throws InvalidCastException exception if casting can’t be done.
class Program
    {
        static void Main(string[] args)
        {
            object obj = new object();
            obj = 16;
            string str = (string)obj; // throws InvalidCastException exception

            if (str != null)
            {
                Console.WriteLine("Value is " + str);
            }
            else
            {
                Console.WriteLine("Value is null");
            }
        }          
    }   
Above code will throw InvalidCastException exception at run time.

Comments and suggestions are most welcome. Happy coding!
Read More...

Sunday 25 May 2014

Deserialize a content item programmatically in Sitecore

Leave a Comment
In my previous blog; I’ve explained how to serialize a content item using Sitecore API. In this blog I’ll show how to deserialize or restore content item programmatically in Sitecore. Below function RestoreItem(string itemPath) takes item path as input parameter and restore the item in content tree.
 public void RestoreItem(string itemPath)
        {
            Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
            Sitecore.Data.Serialization.ItemReference itemReference = new Sitecore.Data.Serialization.ItemReference(masterDB.Name, itemPath);
            string path = Sitecore.Data.Serialization.PathUtils.GetFilePath(itemReference.ToString());

            Sitecore.Data.Serialization.LoadOptions options = new Sitecore.Data.Serialization.LoadOptions(masterDB);
            options.ForceUpdate = true;

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                Sitecore.Data.Serialization.Manager.LoadItem(path, options);               
            }
        }
Sitecore.Data.Serialization.Manager class is having all Serialization related operations. LoadItem(path, options) function restores only given item path in content tree. If you want to restore entire sub content tree from given item path then you have to use LoadTree(path, options) function.

Execution Steps:
  1. Serialize Sitecore content item. For example: Serialize /sitecore/content/Home/Demo News Article/item1 content item.
  2. Change any field value of that Sitecore content item. 
  3. Call function RestoreItem(string itemPath) with item path. For example:
    string path = "/sitecore/content/Home/Demo News Article/item1";
    RestoreItem(path);
  4. Content item will restore in Sitecore content tree. All changes made in step 2 will be reverted.
Comments and suggestions are most welcome. Happy coding!
Read More...

Saturday 24 May 2014

Serialize a content item programmatically in Sitecore

Leave a Comment
Below function SerializeItem(string itemId) will serialize a content item programmatically in Sitecore. This function takes item id as input parameter and will create a .item file in the default serialization directory.
public void SerializeItem(string itemId)
        {
            if (Sitecore.Data.ID.IsID(itemId))
            {
                Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
                Item item = masterDB.GetItem(Sitecore.Data.ID.Parse(itemId));
                if (item != null)
                {
                    Sitecore.Data.Serialization.Manager.DumpItem(item);
                }
            }
        }
Sitecore.Data.Serialization.Manager class is having all Serialization related operations. DumpItem(item) function serializes only given item in default serialization directory. If you want to serialize entire content tree then you can use DumpTree(item) function.

DumpItem() and DumpTree() both these functions are overloaded functions. If you want to serialize item in any specific serialization directory instead of default serialization directory then you can pass directory path as input parameter along with Sitecore item to these functions.
Example:
Sitecore.Data.Serialization.Manager.DumpItem(@"E:\Inetpub\wwwroot\netsitecore", item);
Make sure that appropriate write access has been given to serialization directory else you will get access denied error.
Comments and suggestions are most welcome. Happy coding!
Read More...

Friday 23 May 2014

How to get collection of fields that exists within a section of Sitecore item

2 comments
In this blog post I am going to explain how to retrieve collection of fields that exists within a section of Sitecore item. For example: I am having a template named as Article. In Article template I am having two sections: News Text and News Image. Every section is having few specific fields associated with it. I’ve created a Sitecore item based on Article template. I want to access specific fields of given section name in this Sitecore item.
Figure: Article Template
Below function GetFieldsWithInSection(string itemId, string sectionName) takes Sitecore item id and section name and returns dictionary collection. Field name is set as Dictionary Key and Field value is set as Dictionary Value.
public Dictionary<string,string> GetFieldsWithInSection(string itemId, string sectionName)
        {
            Dictionary<string, string> FieldsWithInSection = new Dictionary<string, string>();
            if (Sitecore.Data.ID.IsID(itemId))
            {
                Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));
                if (item != null)
                {
                  FieldsWithInSection = item.Fields.Where(name => name.Section == sectionName).ToDictionary(field => field.Name, field => field.Value);
                }
            }
            return FieldsWithInSection;
        }
Example:
string itemId={560CFE39-D932-4FB7-A39F-0E335375439E};
string sectionName = "News Text";

Dictionary<string, string> FieldsWithInSection  = GetFieldsWithInSection(itemId,sectionName );
Comments and suggestions are most welcome. Happy coding!
Read More...