December 17, 2015

System.Web.MVC version conflict Error

If you are getting below excetion about System.Web.MVC version conflict. "Assembly 'Sitecore.Mvc, Version=1.0.0.0, Culture=neut...

If you are getting below excetion about System.Web.MVC version conflict.

"Assembly 'Sitecore.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'"

You can try one solution for this .
Just run below statement on Visual Basic Nuget console

Install-Package Microsoft.AspNet.Mvc -Version 5.1.1

December 9, 2015

Get sitecore field details section wise

Dictionary<string, string> FieldsDetailsWithInSection = GetFieldDetailsWithInSection(<ItemID>, <SectionName>); public Di...

Dictionary<string, string> FieldsDetailsWithInSection = GetFieldDetailsWithInSection(<ItemID>, <SectionName>);


public Dictionary<string, string> GetFieldDetailsWithInSection(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).OrderBy(x => x.Sortorder).ToDictionary(field => field.Name, field => field.Value);
                }
            }
            return FieldsWithInSection;
        }

That's It.
Enjoy Learning

December 3, 2015

OnItemSaved Event in Sitecore

namespace SitecoreEvents {     public class ItemSavedHandler     {         public void OnItemSaved( object sender, EventArgs ...

namespace SitecoreEvents
{
   
public class ItemSavedHandler
    {
       
public void OnItemSaved(object sender, EventArgs args)
        {
           
Item SavedItem = Event.ExtractParameter(args, 0) as Item;
           
if (SavedItem != null && SavedItem.Database.Name.ToLower() == "master")
            {
               
if (SavedItem.TemplateID == ID.Parse("<TemplateID>"))
                {
                   
using (new SecurityDisabler())
                    {
                        // Do your action here
                    }
                }
            }
        }
    }
}

In web.config add below line.

<event name="item:saved">
   <
handler type="SitecoreEvents.ItemSavedHandler, SitecoreEvents" method="OnItemSaved" />
</
event>

December 2, 2015

ASP.Net Error Cannot have multiple items selected in a DropDownList

If you are getting exception like "Cannot have multiple items selected in a DropDownList", its most probable cause is you are usin...

If you are getting exception like "Cannot have multiple items selected in a DropDownList", its most probable cause is you are using below line in your application

ddlItems.FindByValue("data").Selected = true;

To handle this error, you need to clear the previous selection of your drop down as following:

ddlItems.ClearSelection();
ddlItems.FindByValue("data").Selected = true;

Thanks
Enjoy Learning.

December 1, 2015

How to obtain the URL to an item in Sitecore

We use LinkManager to get item Url in Sitecore. Lets see below one example. Item item = Sitecore.Context.Database.GetItem("/sitec...

We use LinkManager to get item Url in Sitecore.
Lets see below one example.

Item item = Sitecore.Context.Database.GetItem("/sitecore/Content/Home/Page1");
string link = LinkManager.GetItemUrl(item);

That's it.
Enjoy Learning.

November 30, 2015

How to get latest N children of Sitecore Item

Item ParentItem = Sitecore.Context.Database.GetItem(<ParentItemPath>); var ChildrenList = ParentItem.Children.ToList().OrderBy(x =...

Item ParentItem = Sitecore.Context.Database.GetItem(<ParentItemPath>);
var ChildrenList = ParentItem.Children.ToList().OrderBy(x => x.Statistics.Created).Reverse().Take(N);

Where N = 1,2,3 ...n

That's It
Enjoy Learning

November 29, 2015

ToList extension method not showing

If you are trying to use "ToList" extension method and if it is not showing in code file, it means you are missing "System.Li...

If you are trying to use "ToList" extension method and if it is not showing in code file, it means you are missing "System.Linq" namespace inclusion in file.
Once you will include "System.Linq" namespace, "ToList" extension method will be visible for you.

That's It.
Enjoy Learning

November 28, 2015

OnItemCreated Event in Sitecore

namespace SitecoreEvents {     public class ItemCreatedHandler     {         public void OnItemCreated( object sender, EventAr...

namespace SitecoreEvents
{
   
public class ItemCreatedHandler
    {
       
public void OnItemCreated(object sender, EventArgs args)
        {
           
var createdArgs = Event.ExtractParameter(args, 0) as ItemCreatedEventArgs;
            Sitecore.Diagnostics.
Assert.IsNotNull(createdArgs, "args");
           
if (createdArgs != null)
            {
                Sitecore.Diagnostics.
Assert.IsNotNull(createdArgs.Item, "item");
               
if (createdArgs.Item != null)
                {
                   
var addedItem = createdArgs.Item;
                   
if (addedItem != null && addedItem.Database.Name.ToLower() == "master")
                    {
                        // Do your action here.
                    }
                }
            }
        }
    }
}

Add below line in web.config file
<event name="item:created">
       <handler type="SitecoreEvents.ItemCreatedHandler, SitecoreEvents" method="OnItemCreated" />
</event>

That's it.
Enjoy Learning.

November 27, 2015

How to pass multi parameter in RestSharp body

private RestClient clientV; _clientVideo = new RestClient("<Rest API url>"); RestRequest request = new RestRequest(Met...

private RestClient clientV;
_clientVideo = new RestClient("<Rest API url>");

RestRequest request = new RestRequest(Method.POST)
{
Resource = "<Make your resource url>",
RequestFormat = DataFormat.Json,
};

request.AddBody(new
{
   Item1 = Value1,
   Item2 = Value2,
   Item3 = Value3

});
var response = clientV.Execute(request) as RestResponse;

That's it.
Enjoy Learning.

October 31, 2015

How to write a gentle reminder email

You can write gentle reminder email as below Hi  <Name>, This is just a gentle reminder that We’re waiting for <Activity...

You can write gentle reminder email as below

Hi  <Name>,

This is just a gentle reminder that We’re waiting for <Activity>.

Thanks!

Write multiline statement in C#

Sample String result; result = result + "<br>F1: " + Item.Fields["F1"].Value + "<br>" +   ...

Sample

String result;
result = result + "<br>F1: " + Item.Fields["F1"].Value + "<br>" +
                         "<br>F2: " + Item.Fields["F2"].Value + "<br>" +
                         "<br>F3: " + Item.Fields["F3"].Value + "<br>" +
                          "<br>F4: " + Item.Fields["F4"].Value + "<br>" +
                           "<br>F5: " + Item.Fields["F5"].Value + "<br>";



That's It.
Enjoy Learning

 

October 30, 2015

How to perform a null check on a dynamic object

If you want to check dynamic variable's value you can use " ReferenceEquals" in C#. if (ReferenceEquals(null, <Dynamic ...

If you want to check dynamic variable's value you can use "ReferenceEquals" in C#.

if (ReferenceEquals(null, <Dynamic Variable>)
{
   // To do something
}

October 29, 2015

Add context menu in Sitecore

Objective of this post is to know how we can add context menu in sitecore. At first instance, it looks very difficult process but it is no...

Objective of this post is to know how we can add context menu in sitecore.
At first instance, it looks very difficult process but it is not.

What you need to do if you want to add a conetext menu in sitecore instance.
Just traverse to this location "/sitecore/content/Applications/Content Editor/Context Menues/Default" in core database
and add your item here as in below picture.

October 28, 2015

Generate Brightcove API access token

I have written one method here to generate access token for Brightcove API. Once you have Brightcove API access token, you can work on API...

I have written one method here to generate access token for Brightcove API.
Once you have Brightcove API access token, you can work on API.

private string CLIENT_ID = "<Put here client ID>";
private string CLIENT_SECRET = "<Put here client secret>";
private string ACCESS_TOKEN = String.Empty;
private RestClient _client;

protected void Page_Load(object sender, EventArgs e)
    {
        ACCESS_TOKEN = GetAccessToken();
    }

private string GetAccessToken()
    {
        _client = new RestClient("https://oauth.brightcove.com");

        string authInfo = CLIENT_ID + ":" + CLIENT_SECRET;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

        RestRequest request = new RestRequest(Method.POST)
        {
            Resource = "/v3/access_token",
            RequestFormat = DataFormat.Json,

        };
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddHeader("Authorization", "Basic " + authInfo);
        request.AddParameter("grant_type", "client_credentials");

        var response = _client.Execute(request) as RestResponse;
        JObject joResponse = JObject.Parse(response.Content.ToString());
        return (string)joResponse["access_token"];   
    }

That's It.
Enjoy Learning

October 22, 2015

JSON editor online

If you have JSON output as string and you want to format it; you can do it online. This is nice tool to work with JSON output. Use below url...

If you have JSON output as string and you want to format it; you can do it online. This is nice tool to work with JSON output.
Use below url to format JSON string.

http://www.jsoneditoronline.org/

Just paste your JSON string in text box and click on run button you will see formatted JSON output.

That’s It.
Enjoy Learning

October 14, 2015

Upload Video to Sitecore Instance

public static void UploadToSitecore( Stream stream, string filename, string filepath)       {           Sitecore.Resources.Media. Medi...

public static void UploadToSitecore(Stream stream,string filename,string filepath)      
{      
    Sitecore.Resources.Media.
MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions
();      
    options.Database = Sitecore.Configuration.
Factory.GetDatabase("master"
);      
    options.Language = Sitecore.Globalization.
Language.Parse(Sitecore.Configuration.Settings
.DefaultLanguage);          
    options.Versioned = Sitecore.Configuration.
Settings.Media
.UploadAsVersionableByDefault;      
    options.Destination = filepath;      
    options.FileBased = Sitecore.Configuration.
Settings.Media
.UploadAsFiles;      
    Sitecore.Resources.Media.
MediaCreator creator = new Sitecore.Resources.Media.MediaCreator
();      
    Sitecore.Data.Items.
MediaItem
sample = creator.CreateFromStream(stream, filename, options);      
}

That’s It
Enjoy Learning

October 13, 2015

Get Dictionary Item value in Sitecore

Sitecore Dictionary item is very helpful  to maintain key-value pair information in Sitecore instance.Below function to get dictionary item ...

Sitecore Dictionary item is very helpful  to maintain key-value pair information in Sitecore instance.Below function to get dictionary item value by item name. You just need to pass dictionary path and item name

public string GetDictionaryItem(<Pass here dictionary item name>)      
{      
    Sitecore.Data.
Database database = Sitecore.Configuration.Factory.GetDatabase(“master”);      
   
Item currentItem = database1.GetItem(String.Concat(<dictionary path>, (<Pass here dictionary item name>));      
   
string val = String.Empty;      
   
if (currentItem != null)      
    {      
        val = currentItem[
“Phrase”];      
       
return val;      
    }      
   
return
val;      
}

That’s It.
Enjoy Learning.

October 10, 2015

Sitecore package generation hanging

Recently I was trying to create a package in one of my Sitecore instance. I was able to add items but after adding items when clicking on “G...

Recently I was trying to create a package in one of my Sitecore instance. I was able to add items but after adding items when clicking on “Generate Zip”, it was only showing me “Generating …” message on my window.

If you are facing this issue, you can try following solutions to resolve this issue.

1. Provide IIS_IUSRS permission on Data folder.

2. Check package folder availability in Data folder. It is available or not.

3. Compare all dlls of bin folder with fresh sitecore installed instance.

Important thing is it worked for me.

October 9, 2015

Convert JSON output to C# class

You can easily generate JSON response into C# classes. Just simply paste JSON response or URL here you will get all required classes structu...

You can easily generate JSON response into C# classes. Just simply paste JSON response or URL here you will get all required classes structure.

http://json2csharp.com/

Nice tool.

October 8, 2015

Generate Google API refresh token

You can generate Google API refresh token manually in browser. Once you get the refresh token, you start using Google API services. Foll...

You can generate Google API refresh token manually in browser. Once you get the refresh token, you start using Google API services.

Follow below steps to generate refresh token

Step 1: Login into Google account in chrome browser

Step 2: Just change your input in below URL and paste it in browser.

https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=SCOPE1%20SCOPE2&response_type=code&access_type=offline

Step 3: Once you press Go/Enter you will get Authorization code.

Step 4: If you have not curl utility, just download it.  Go to command window hit below URL after replacement of your values.

Curl https://accounts.google.com/o/oauth2/token -d "code=AUTHCODE&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code"

AUTHCODE = value you got in previous step.

You will get refresh token as response. Now you can use refresh token in your service.

RestSharp Http Client Tool

If you want to consume REST services from .Net application you can use RestSharp Http Client tool. You can download RestSharp dll and manua...

If you want to consume REST services from .Net application you can use RestSharp Http Client tool.

You can download RestSharp dll and manual from below URL.

http://restsharp.org/

RestSharp is a powerful http client tool.

October 7, 2015

Get Sitecore Item by path

You can get sitecore item by using sitecore item path. Once you have item object you can get all details of this item. public Item GetIt...

You can get sitecore item by using sitecore item path. Once you have item object you can get all details of this item.

public Item GetItemByPath(string path)
        {
            return Sitecore.Context.Database.GetItem(path);
        }


Just pass item’s path in above method.

 

October 6, 2015

Get Sitecore Item by Item ID

You can get sitecore item by using sitecore item ID. Once you have item object you can get all details of this item. public static Item Ge...

You can get sitecore item by using sitecore item ID. Once you have item object you can get all details of this item.
public static Item GetItemByID(string id)
        {
            return Sitecore.Context.Database.GetItem(new Sitecore.Data.ID(id));
        }

Just pass item’s id in above method.

 

October 5, 2015

Get YouTube Video Name by Video ID

public string GetVideoName( string VideoID)         {             RestRequest request = new RestRequest(Method.GET)             {  ...

public string GetVideoName(string VideoID)
        {
            RestRequest request = new RestRequest(Method.GET)
            {
                Resource = "youtube/v3/videos?id=" + VideoID + "&key="+ API_KEY + "&part=snippet,recordingDetails",
                RequestFormat = DataFormat.Json
            };

            var response = _client.Execute(request) as RestResponse;

            JObject joResponse = JObject.Parse(response.Content.ToString());
            string VideoName = (string)joResponse["items"][0]["snippet"]["title"];

            return VideoName;
        }

Just pass Video ID in above method you will get Video Name as response.

October 4, 2015

Get Category of Video by Video ID

public Category GetCategoryOfVideo( string VideoID)         {             RestRequest request = new RestRequest(Method.GET)          ...

public Category GetCategoryOfVideo(string VideoID)
        {
            RestRequest request = new RestRequest(Method.GET)
            {
                Resource = "youtube/v3/videos?id=" + VideoID + "&key="+API_KEY + "&part=snippet,recordingDetails",
                RequestFormat = DataFormat.Json
            };

            var response = _client.Execute(request) as RestResponse;

            JObject joResponse = JObject.Parse(response.Content.ToString());
            string CategoryID = (string)joResponse["items"][0]["snippet"]["categoryId"];

            Category result = GetVideoCategories().Find(x => x.ID == CategoryID);

            return result;
        }

    public class Category
    {
        private string CategoryID;
        private string CategoryTitle;

        public Category(string _ID, string _Title)
        {
            CategoryID = _ID;
            CategoryTitle = _Title;
        }

        public string ID
        {
            get { return CategoryID; }
            set { CategoryID = value; }
        }

        public string Title
        {
            get { return CategoryTitle; }
            set { CategoryTitle = value; }
        }
    }


Just pass Video ID in above method you will get Category details of video.

October 3, 2015

Get All YouTube Categories List

  public List <Category> GetVideoCategories()         {             List <Category> VideoCategoryList = new List <Categ...

  public List<Category> GetVideoCategories()
        {
            List<Category> VideoCategoryList = new List<Category>();

            VideoCategoryListResponse objCategories = null;

            VideoCategoriesResource.ListRequest objRequest = new VideoCategoriesResource.ListRequest(youtube, "id,snippet");
            objRequest.Hl = "en_US";
            objRequest.RegionCode = "US";
            objCategories = objRequest.Execute();

            foreach (VideoCategory obj in objCategories.Items)
            {
                VideoCategoryList.Add(new Category(obj.Id, obj.Snippet.Title));
            }

            return VideoCategoryList;
        }



public class Category
    {
        private string CategoryID;
        private string CategoryTitle;

        public Category(string _ID, string _Title)
        {
            CategoryID = _ID;
            CategoryTitle = _Title;
        }

        public string ID
        {
            get { return CategoryID; }
            set { CategoryID = value; }
        }

        public string Title
        {
            get { return CategoryTitle; }
            set { CategoryTitle = value; }
        }
    }

October 2, 2015

Upload Video Caption using Google YouTube API

public void UploadVideoCaption( string VideoID, string FilePath, string CaptionName)         {             Caption newCaption = new...

public void UploadVideoCaption(string VideoID,string FilePath,string CaptionName)
        {
            Caption newCaption = new Caption();
            newCaption.Snippet = new CaptionSnippet();
            newCaption.Snippet.Name = CaptionName;
            newCaption.Snippet.Language = "en";
            newCaption.Snippet.VideoId = VideoID;
            using (var fileStream = new FileStream(FilePath, FileMode.Open))
            {
                CaptionsResource.InsertMediaUpload captionInsertRequest = youtube.Captions.Insert(newCaption, "snippet", fileStream, "*/*");
                captionInsertRequest.Sync = true;
                IUploadProgress result = captionInsertRequest.Upload();
             }

        }


 

October 1, 2015

Upload Video using Google YouTube API

public void UploadVideo( String UploadVideoPath, String title, String categoryid) {     const int KB = 0x400;     var minimumChu...

public void UploadVideo(String UploadVideoPath, String title, String categoryid)
{
    const int KB = 0x400;
    var minimumChunkSize = 256 * KB;

    var video = new Video();
    video.Snippet = new VideoSnippet();
    video.Snippet.Title = title;
    video.Snippet.CategoryId = categoryid;
    video.Status = new VideoStatus();
    video.Status.PrivacyStatus = "unlisted";

    using (var fileStream = new FileStream(UploadVideoPath, FileMode.Open))
    {
        var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*");
              
        videosInsertRequest.ProgressChanged += insertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += insertRequest_ResponseReceived;
        videosInsertRequest.ChunkSize = minimumChunkSize * 4;
        videosInsertRequest.Upload();
             
    }
}



private void insertRequest_ResponseReceived(Video video)
{
    UploadedVideoId = video.Id;
}

private void insertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
    switch (progress.Status)
    {
        case UploadStatus.Failed:
            UploadedVideoId = "FAILED";
            break;

        case UploadStatus.Completed:
            break;

        default:
            break;
    }
}

 

Just pass Video path, video title & category id of video in above method.