Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, June 5, 2013

Calculate distance between two points on Earth

        public static Double CalculateDistance(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
            double theta = longitude1 - longitude2;
            double dist = Math.Sin(deg2rad(latitude1)) * Math.Sin(deg2rad(latitude2)) + Math.Cos(deg2rad(latitude1)) * Math.Cos(deg2rad(latitude2)) * Math.Cos(deg2rad(theta));
            dist = Math.Acos(dist);
            dist = rad2deg(dist);
            dist = dist * 60 * 1.1515;
            dist = dist * 1.609344;
            return (dist);
        }

        private static Double deg2rad(Double deg) {
            return (deg * Math.PI / 180.0);
        }

        private static Double rad2deg(Double rad) {
            return (rad / Math.PI * 180.0);

        }

Serialize object to XML

        /// <summary>
        /// Serialize object to XML
        /// </summary>
        /// <param name="instance">Object Instance to be serialized</param>
        /// <returns>Respective XML for specific instace</returns>
        public static string SerializeToXml(object instance) {
            string serializedXml = string.Empty;

            if (instance != null) {
                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter();
                XmlSerializer serializer = new XmlSerializer(instance.GetType(), "");
                serializer.Serialize(sw, instance);
                serializedXml = sw.ToString();
            }

            return serializedXml;

        }

Generates Json for specific object instance

Generates Json for specific object instance

/// <summary>
        /// Generates Json for specific object instance
        /// </summary>
        /// <param name="instance">Instance to be converted to Json </param>
        /// <param name="recursionDepth">Recursion depth optional paramter</param>
        /// <returns>Json for specific object instance</returns>
        public static string ToJson(this object instance, int recursionDepth = 100) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(instance);

        }

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.

Image Gallery in Sitecore

Assign Placeholder in Template Standard value and set its properties – width, height, presentation, media folder [set parent folder so that all folder images will be fall under it.]
Remember that Image Gallery accepts images of the type .JPG, all others will at the moment just result in a grey screen. If you want to include all types of images then change below lines in “ImageGalleryXMLConfiguration.xslt” file


  <!--<xsl:if test="./item[@template='jpeg']">-->
  <xsl:if test="./item">
    <album title="{@name}"
           description="{sc:fld('description',.)}"
           image="{sc:fld('image',.,'src')}">
      <!--<xsl:for-each select="item[@template='jpeg']">-->
      <xsl:for-each select="item">

Create and fill table in SQL server from XML file

<?xml version="1.0" encoding="UTF-8" ?>
<Dealers>
  <Dealer id='77'>
    <Dealer_Address>
      <Name>Action Kia</Name>
      <Address>Cnr Bruce Highway And Oak St</Address>
      <Suburb>Gympie</Suburb>
      <State>QLD</State>
      <Postcode>4570</Postcode>
      <WorkPhone>(07) 5482 2759</WorkPhone>
      <Opening_Hour>Mon-Fri: 8:00 AM-6:00 PM-br-Sat: 8:00 AM-12:00 PM-br-Sun: Closed</Opening_Hour>
      <Fax>(07) 5482 2389</Fax>
      <Url>www.actionautogroup.com.au</Url>
      <Email></Email>
      <Longitude>152.650454</Longitude>
      <Latitude>-26.179577</Latitude>
    </Dealer_Address>
    <Service_Address>
      <Name>Action Kia</Name>
      <Address>Cnr Bruce Highway And Oak St</Address>
      <Suburb>Gympie</Suburb>
      <State>QLD</State>
      <Postcode>4570</Postcode>
      <WorkPhone>(07) 5482 2759</WorkPhone>
      <Opening_Hour>Mon-Fri: 8:00 AM-6:00 PM-br-Sat: 8:00 AM-12:00 PM-br-Sun: Closed</Opening_Hour>
    </Service_Address>
  </Dealer>
  <Dealer id='7'>
    <Dealer_Address>
      <Name>Adtrans Kia</Name>
      <Address>1178 - 1184 South Road</Address>
      <Suburb>Clovelly Park</Suburb>
      <State>SA</State>
      <Postcode>5042</Postcode>
      <WorkPhone>(08) 8374 2744</WorkPhone>
      <Opening_Hour></Opening_Hour>
      <Fax>(08) 8374 2755</Fax>
      <Url>www.adtranskia.com.au</Url>
      <Email></Email>
      <Longitude>138.574837</Longitude>
      <Latitude>-34.997404</Latitude>
    </Dealer_Address>
    <Service_Address>
      <Name>Adtrans Kia</Name>
      <Address>1178 - 1184 South Road</Address>
      <Suburb>Clovelly Park</Suburb>
      <State>SA</State>
      <Postcode>5042</Postcode>
      <WorkPhone>(08) 8374 2744</WorkPhone>
      <Opening_Hour></Opening_Hour>
    </Service_Address>
  </Dealer>
</Dealers>

SELECT
      product.value('../@id', 'int') as id,
      replace(X.product.query('Name').value('.', 'VARCHAR(300)'), 'And', '&') as Name,
      X.product.query('Address').value('.', 'VARCHAR(300)')as Address,
      X.product.query('Suburb').value('.', 'VARCHAR(300)')as Suburb,
      X.product.query('State').value('.', 'VARCHAR(300)') as State,
      X.product.query('Postcode').value('.', 'VARCHAR(30)') as Postcode,
      X.product.query('WorkPhone').value('.', 'VARCHAR(20)') as WorkPhone,
      replace(X.product.query('Opening_Hour').value('.', 'VARCHAR(300)'), '-br','<br>') as Opening_Hour
INTO Service_Address
FROM
(
      SELECT CAST(x AS XML) FROM OPENROWSET(BULK 'D:\dealers_2012125 - Copy.xml', SINGLE_BLOB) AS T(x)
) AS T(x)

CROSS APPLY x.nodes('Dealers/Dealer/Service_Address') AS X(product);

Photoshop useful commands

Select – Control + Mouse click
Copy – Control + shift + C
New - Control N
Save as image size – control + shift + alt + S
Enlarge - Control + space + mouse click

Deselect all items – Control + D

Add particular child to parent in content.

Select Parent template and click on “Assign” and choose the child template. Click on Ok

Add sitecore reference in web.config file so that we can get intelligence in aspx files

<pages validateRequest="false">
      <controls>
        <add tagPrefix="sc" namespace="Sitecore.Web.UI.WebControls" assembly="Sitecore.Kernel" />
</controls>

</pages>