Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, April 16, 2015

How to create XML Sitemap for Sitecore website programmatically

There are time when you are going to deploy your website on production and client want Sitemap file of website. Sitemap file is used to improve SEO results.

Sometimes client have some weird requirement that create XML sitemap dynamically for Sitecore website.

For this type of requirement, always keep one field "Show Sitemap" in all the page content.

Here is a code to generate sitemap dynamically. Remember you need a permission to update Sitemap.xml file on server.

public bool GenerateXml(List<Tuple<string, string, string>> lstTuples)  //generateXml
{
    bool result = false;
    string xmlFile = HttpContext.Current.Server.MapPath("/Sitemap.xml");

    XmlTextWriter writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
    writer.Formatting = Formatting.Indented;
    writer.WriteStartDocument();
    {
        writer.WriteStartElement("urlset");
        writer.WriteAttributeString("xmlns:xhtml", "http://www.w3.org/1999/xhtml");
        writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

        string url = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];

        foreach (var value in lstTuples)
        {
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", System.Web.HttpUtility.HtmlEncode(url + value.Item2));
            writer.WriteElementString("lastmod", value.Item3);
            writer.WriteElementString("changefreq", "weekly");
            writer.WriteElementString("priority", "0.5");
            writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();

        result = true;
    }

    return result;

}

Pass the Tuple collection which contains URL and last modified date of content items.
This code should create file with below data

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://test/</loc>
    <lastmod>2015-04-06</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://test/Main Menu/Page1</loc>
    <lastmod>2015-03-23</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>


Please leave your comments or share this code if it’s useful for you.

Monday, April 13, 2015

How to do versioning of JS and CSS files in ASP.NET

Whenever user access any website - images, JS and CSS are cached by browser. But if JS and CSS are updated on server still client browser refer the old JS and CSS. That’s very bad. It’s always good practice to provide the latest copy of CSS and JS to client browser.

But how to do it in ASP.NET to make sure browser is getting the updated files.

To solve this, we can use query string with JS and CSS.

For CSS, take one literal in <Head> section of aspx page as below

<head runat="server">
<asp:Literal ID="ltStyleCss" runat="server" Text="" ></asp:Literal>
</head>

Write below code

public string CurrentVersion = "";

protected void Page_Load(object sender, EventArgs e)
{
CurrentVersion = DateTime.Today.ToString("MMddyyyy") + "_" + DateTime.Now.Hour.ToString();

ltStyleCss.Text = string.Format("<link href=\"/ css/style.css?ver={0}\" rel=\"stylesheet\" />", CurrentVersion) + System.Environment.NewLine;


Here we are declaring version for each hour of the day.

You can do it for each request by specifyin current datetime, but problem with that approach is that it affects network bandwidth. So per hour solution is better.

It’s very easy to specify it for JS by directly passing the version variable as query string  

<script src="/Presentation/scripts/jquery.js?ver=<%=CurrentVersion%>"></script>

Pretty simple for JS but you can’t achieve the same way for CSS. Let me know if you can do it for CSS as well.


Please leave your comments or share this tip if it’s useful for you.

Sunday, April 12, 2015

How to implement Facebook Tag API script or Facebook Analytic tracking script

Facebook analytic is great way to track your website access by analyzing custom audience source. Facebook called it as Facebook Tag API.

To work with this you need Facebook tracking ID. I represented it as “NNNNN”. In project store it either in web.config or database. Below is script that you need to place it before the end of </body> section of webpage.

    <script>(function () {
    var _fbq = window._fbq || (window._fbq = []);
    if (!_fbq.loaded) {
        var fbds = document.createElement('script');
        fbds.async = true;
        fbds.src = '//connect.facebook.net/en_US/fbds.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(fbds, s);
        _fbq.loaded = true;
    }
    _fbq.push(['addPixelId', 'NNNNN']);
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'PixelInitialized', {}]);
    </script>
    <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?id=NNNNN&amp;ev=PixelInitialized" /></noscript>

This much of information is enough to implement it in any web application like ASP.NET etc. Though programmer don’t like much theoretical reading however you can read more from https://developers.facebook.com/docs/ads-for-websites/tag-api

Please leave your comments or share this script if it’s useful for you.

Friday, April 10, 2015

How to break or put Sitecore config file data into other config files

I am damn sure that you must sometimes face this problem during reading, finding or modifying any entry in Sitecore web.config file.

The config file that I have contains 3950 lines. WTF how to work with such a large file. Is there any way to break it?

Fortunetly YES. Here is the trick.

·         Cut all data lines after </appSettings> and before <log4net> from web.config i.e. cut "<sitecore " section only

</appSettings>
  <sitecore database="SqlServer">
  </sitecore>
<log4net>             

·         Create "sitecore.config" in "App_Config" folder and put all the data into it as
<?xml version="1.0" encoding="utf-8" ?>
 <sitecore database="SqlServer">

          -----
</sitecore>

 At runtime Sitecore merge all these config files and treat them as a single file and work smartly.

Please leave your comments or share this trick if it’s useful for you.

Sunday, March 29, 2015

How to specify location of images in aspx page for Sitecore

I was clueless while displaying search image in all the aspx pages and ascx web control of Sitecore. As on some pages I was getting my image but while on some pages I was not missing the image.

I tried different path as below but all was wrong

<img src="../images/search.png" alt="search image" />
<img src="~/images/search.png" alt="search image" />
<img src="images/search.png" alt="search image" />

Correct one is to use path that starts with “/” as it automatically resolve its path as below

<img src="/images/search.png" alt="search image" />

Final note is - Never specify "../" for any image as for any web request IIS resolve it accordingly. So always write root path as "/" + physical image path.

Hope it helps someone in anyway.


Please leave your comments or share this tip if it’s useful for you.

Saturday, March 28, 2015

How to repeat particular string or char into certain number of times

I was writing a program for showing a tree structure in textbox. I was trying to concatenate tabs and spaces in string. Soon I realize that it’s a very tedious way to achieve the result. I thought that .NET is the Ocean and there must be some way to repeat the particular string or character certain number of times. For example if I have character ‘0’ and I want to display it 5 times on screen. 

How to do it?

FOR and FOR EACH Loops are common, but I need some more smart way do it.
Here are some ways that I found

int count = 5;
string str = "PEACE ";
char c = '0';

Console.WriteLine(String.Empty.PadLeft(count, c));     //Output- 00000

string result = new String(c, count);
Console.WriteLine(result); //Output- 00000

Console.WriteLine(new StringBuilder().Insert(0, str, count).ToString());   //Output- PEACE PEACE PEACE PEACE PEACE

First two only repeat characters while last way is to repeat string. Hope this help someone.

Please leave your comments or share this code if it’s useful for you.

Friday, March 27, 2015

How to include or put or embed curly braces in string.Format in C#

I was writing a HTML style within my repeater from code behind page as below

string s = string.Format("<style>.splashImg{0} { background-image:url({1}  );}</style>", 3, " myimage.jpg");

So that my final output should be like

<style>.splashImg3{ background-image:url(myimage.jpg);} </style>

And OMG I received error “Unrecognized escape sequence”. My first reaction was WTF what’s wrong with this code line. After careful look I come to know that it’s a problem of curly braces “{ }“.

As we are specifying curly braces for placeholder like {0} {1}, compiler is confused with other braces like “splashImg3{“.

So simplest solution is just write double braces for non-placeholder braces like “{{“ as shown in yellow color. So final code looks like

string s = string.Format("<style>.splashImg{0} {{ background-image:url( {1}  );}}</style>", 2, "myimage.jpg");


Please leave your comments or share this code if it’s useful for you.