Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, June 5, 2013

DeSerailizes Json string to specific object

DeSerailizes Json string to specific object

/// <summary>
        /// DeSerailizes Json string to specific object
        /// </summary>
        /// <typeparam name="T">Type of Object</typeparam>
        /// <param name="jsonObject">Json String to be converted to Collection</param>
        /// <param name="recursionDepth">Recursion depth optional paramter</param>
        /// <returns>Collection of Object from Json Response</returns>
        public static T ToObject<T>(this string jsonObject, int recursionDepth = 100) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Deserialize<T>(jsonObject);

        }

Fetches Associated Sitecore Image from Site core Item

Fetches Associated Sitecore Image from Site core Item


/// <summary>
        /// Fetches Associated Sitecore Image from Site core Item
        /// </summary>
        /// <param name="item">Site core Item containg Image Field</param>
        /// <param name="fieldName">Name of the Image Field</param>
        /// <returns>Associated Sitecore Image from Site core Item</returns>
        public static string GetItemImageURL(Sitecore.Data.Items.Item item, string fieldName) {
            string imageTag = string.Empty;
            Sitecore.Data.Fields.ImageField imageField = item.Fields[fieldName];

            if (imageField != null && imageField.MediaItem != null) {
                MediaItem image = new MediaItem(imageField.MediaItem);
                string src = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));

                if (!string.IsNullOrEmpty(src)) {
                    imageTag = src;                
                   }
            }

            return imageTag;

        }

Send email with image in Sitecore and C#

Send email with image

public static bool SendEmailWithImage(string mailTo, string mailFrom, string subject, string mailBody, bool isHtml) {
            bool response = false;
            string emailStatus = string.Empty;
            //string from = Convert.ToString(ConfigurationManager.AppSettings["EmailReminder.FromAddress"]);
            string to = mailTo;
            try {
                using (MailMessage mail = new MailMessage()) {
                    #region Mail setting
                    mail.From = new MailAddress(mailFrom, mailFrom);
                    mail.To.Add(new MailAddress(mailTo, mailTo));
                    mail.IsBodyHtml = isHtml;
                    mail.Subject = subject;
                    mail.Body = mailBody;
                    #endregion

                    EmbedCompanyLogo(mail);

                    Sitecore.MainUtil.SendMail(mail);
                }

                response = true;
            } catch (Exception ex) {
                Sitecore.Diagnostics.Log.Error(ex.Message + " : ", ex);
                response = false;
            }
            return response;

        }


        /// <summary> 
        /// Embeds the company logo into the given mail message 
        /// </summary> 
        /// <param name="message">Message in which the logo should be embedded</param> 
        public static void EmbedCompanyLogo(MailMessage message) {
            AlternateView av1 = AlternateView.CreateAlternateViewFromString(message.Body, null, System.Net.Mime.MediaTypeNames.Text.Html);
            string strImageUrl = System.Web.HttpContext.Current.Server.MapPath("~/Images/dealer/logo_menu.jpg");
            LinkedResource logo = new LinkedResource(strImageUrl, System.Net.Mime.MediaTypeNames.Image.Jpeg);
            logo.ContentId = "logo_menu";
            //To refer to this image in the html body, use <img src="cid:companylogo"/> 
            av1.LinkedResources.Add(logo);
            message.AlternateViews.Add(av1);

        }

Get URL of Sitecore item

var directionItem = Sitecore.Context.Database.SelectSingleItem(Sitecore.Context.Site.StartPath + "//*[@@templatename='Hotel Directions']");

string directionURL = directionItem != null ? LinkManager.GetItemUrl(directionItem) : "";

Glass Library Implementation in Sitecore Project

1.    Install Package Managar in Visual Studio
a.    Go to Tools->Extension Manager-> click Online Gallery -> NuGet Package Manager. Download & install it
2.    Install Glass library
a.    Go to Tools-> Library Package Manager->Package Manager Console
Type command PM>"Install-Package Glass.Sitecore.Mapper" & press enter
3.    Create folder "Model" in your visual Studio project.
4.    Add cs file like "SitecoreHome.cs" in Model folder which map to content/template fields of sitecore


5.    Add following code in “Global.asax

public void Application_Start() {

var loader = new Glass.Sitecore.Mapper.Configuration.Attributes.AttributeConfigurationLoader(
            "WebApplicationRND.Model, WebApplicationRND");

Glass.Sitecore.Mapper.Context context = new Glass.Sitecore.Mapper.Context(loader);

  }

6.    Try to access it from web page code behind file as

Glass.Sitecore.Mapper.ISitecoreContext context = new Glass.Sitecore.Mapper.SitecoreContext();
var home = context.GetCurrentItem<WebApplicationRND.Model.SitecoreHome>();

Label4.Text = "<br> This is ---" + home.PageTitle + "----" + home.Created.ToString() + "---" + home.CreatedBy ;

Use LINQ with Glass

Create NotFound page for 404 error in Sitecore

Create template, layout and content for Notfound page.
Changes in web.config file
<setting name="ItemNotFoundUrl" value="/Notfound.aspx"/>
<setting name="LayoutNotFoundUrl" value="/Notfound.aspx"/>
<setting name="LinkItemNotFoundUrl" value="/Notfound.aspx"/>
<setting name="NoLicenseUrl" value="/Notfound.aspx"/>


In Notfound.aspx page write below code
protected void Page_Load(object sender, EventArgs e)
{
Response.Status = "404 Not Found";
Response.StatusCode = 404;
}

XslHelper - XSL extension methods in XSLT for Sitecore

Download “XslHelper.cs” from http://svn.sitecore.net/XslHelper/ and add it to project.
Open web.config file and find, comment and add below entry in <xslExtensions> tag
<xslExtensions>
      <extension mode="on" type="Sitecore.Sharedsource.Xml.Xsl.XslHelper, WebApplicationRND" namespace="http://www.sitecore.net/sc" singleInstance="true" />
      <!--<extension mode="on" type="Sitecore.Xml.Xsl.XslHelper, Sitecore.Kernel" namespace="http://www.sitecore.net/sc" singleInstance="true" />-->


Where WebApplicationRND is project assembly name.