Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, June 5, 2013

Get Latitude Longitude From Location

public static void GetLatitudeLongitudeFromLocation(string address, out double SelectedLatitude, out double SelectedLongitude) {

            SelectedLatitude = 0;
            SelectedLongitude = 0;

            string url = "http://maps.googleapis.com/maps/api/geocode/" + "xml?keyword=Hotels, + Australia&address=" + address + "&sensor=false&region=au";


            WebResponse response = null;

            try {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                response = request.GetResponse();

                if (response != null) {

                    XPathDocument document = new XPathDocument(response.GetResponseStream());
                    XPathNavigator navigator = document.CreateNavigator();

                    var resultXML = XDocument.Parse(navigator.InnerXml);

                    if (resultXML != null) {
                        var geocodeStatus = (from geocodeResponse in resultXML.Descendants("GeocodeResponse")
                                             select new {
                                                 Status = geocodeResponse.Element("status").Value,
                                             }).First();


                        if (geocodeStatus.Status.Equals("OK")) {
                            var geoLocation = (from Location in resultXML.Descendants("GeocodeResponse").Descendants("geometry").Descendants("location")
                                               select new {
                                                   Latitude = Location.Element("lat").Value,
                                                   Longitude = Location.Element("lng").Value,
                                               }).First();

                            if (geoLocation != null) {
                                SelectedLatitude = Convert.ToDouble(geoLocation.Latitude);
                                SelectedLongitude = Convert.ToDouble(geoLocation.Longitude);

                            }
                        }
                    }
                }
            } catch (Exception ex) {
                string error = ex.Message;
            } finally {
                if (response != null) {
                    response.Close();
                    response = null;
                }
            }

            Console.ReadLine();

        }

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);

        }