Bug Fix in Sitecore 8.2 IR Delete Media Item

Recently, I was working on requirement of external media storage enable in sitecore 8.2 IR. During the development, I have observed some abnormal behaviour when delete any media item, which is created from copy or duplicate command.

After dig this behaviour in details, I found that the media item created using Duplicate/Copy To operation, both items (actual item and copied item) share the same blob reference in blobs table. So while we perform Delete operation on new copied item, it will remove media item as well as blob from blob table and due to that existing media item returns 404 Error.

In sitecore, There are two option available to manage delete operation and it is manage by below config entry of sitecore.config file.

<setting name=”RecycleBinActive” value=”false”/>

Option 1:  RecycleBinActive setting is enabled in sitecore instance, then delete command work fine. Because the delete operation not remove blob entry from database.

Option 2: RecycleBinActive setting is disabled in sitecore instance, then the issue will be occur in delete operation, Because, while we perform Delete operation on new copied item, it will remove media item as well as blob from blob table and due to that existing media item returns 404 Error.

In our case, Sitecore Support provided us a patch (# 227925) that solved the problem.

Hope this helps you guys…!

Advertisements

Unit testing

Hi Guys, Unit testing is becoming more and more popular in software development and it’s good to have application with unit tested. There are numerous frameworks, tools, and development processes can be used to perform unit testing. Here in this post, I am going to provide basic introduction of unit testing.

What is unit testing?

Unit testing is the code through which units of source code (actual functionality code) are tested to verify. Performing unit tests is a way to ensure that all functionalities of an application are working as they should.

It is not mandatory to implement unit test for each and every method and functionality. But it should cover all the main functionality code.

Unit testing framework.

There are number of unit testing frameworks are available in market. Each has it’s own matrix and features. Based on your project requirement, you can select unit testing framework.

Two most popular unit testing frameworks in the .NET world is the open source NUnit and the commercial MsTest.

Benefits of Unit Testing.

One of the main benefits of unit testing is that, it makes the coding process more Agile and improve quality of the code.

Issues are found at an early stage, so unit testing helps reduce the cost of bug fixes.

Unit testing reduces defects in the newly developed features or reduces bugs when changing the existing functionality.

Unit testing helps simplify the debugging process. If a test fails, then only the latest changes made in the code need to be debugged.

In next post, we will cover basic sample example of unit test project and different tools which we can use in our unit test project for better result….

 

Sitecore Item Operations Tool

I am really very excited to write this post because this post related to my first tool that have contributed in Sitecore Market Place (https://marketplace.sitecore.net). Finally they have approved and published the “Item Operations Tool” module and it is available on Sitecore marketplace.

This tool is use for doing some basic operations on item. So have given name as “Item Operations Tool”. Mainly this tool use for comparison of item with live item, count sub items and expands all the dependents of item

Download installation package from below link.

https://marketplace.sitecore.net/Modules/I/Item_Operations_Tool.aspx

Installation

Step -1: Download installation package from above link.

Step -2: installed downloaded package into local Sitecore.

Step -3: add following entry into Commands.config

<command name="item:ItemComparer" type="CustomCommands.ItemComparer,CustomCommands"/>

<command name="item:countSubItems" type="CustomCommands.CountSubItems,CustomCommands" />

<command name="item:ExpandDescendants" type="CustomCommands.ExpandDescendants,CustomCommands" />

Step -4: Restart Sitecore instance.

When you open Sitecore instance you can see new menu item in side version –> Item in below image.

Sitecore Item Operation Tool

Item Operations

Item Comparer

I am going to provide a tool in Content Editor that will allow users to compare contents of master and web databases. (Sitecore Ribbon: Version -> Item -> Item Compare)

– This will show all fields of both databases to compare.

– The default selected item and language should be compared.

Once you click on Item Compare button.

Compare Item

This will show all fields of both databases to compare.

Note:

The differences are highlighted in blue and red.

Blue: Apply on field value to highlight difference of field value.

Red: Apply on field title to identify that the field value is different form live field value).

Count Subitems

You can Count the number of sub items (all descendant sub items) of particular item. To do so, please follow below steps:

  1. Navigate to particular item of which you want to get sub items count.

Click on “Count SubItems” from ribbon as shown in below image.

count subitem in sitecore

Expand subitems

You can expand all sub items (all descendant sub items) of particular item. To do so, please follow below steps:

  1. Navigate to particular item of which you want to expand SubItems.

Click on “Expand SubItems” from ribbon as shown in below image to expand sub items (all descendant sub items) of particular item.

Expand Subitem

Displaying Images in ASP.NET Using HttpHandlers

Now you know what HttpHandlers are and how to setup them, we will write our own httpHandler to read the images from a database. Remember, this article explains creating httpHandler using the generic handler (.ashx). Since the .ashx file extension is already mapped in the IIS to the ASP.NET ISAPI filter, you do not have to configure your web.config file.

Create a new website in Visual Studio. Right-click on the project in the solution explorer and select Add New Item. From the available templates, add the new file of type Generic Handler and name it ImageHandler.ashx

Visual Studio opens a new file with the following content.

<%@ WebHandler Language="C#" Class="getImage" %>
 using System;
 using System.Web;
 
 public class getImage : IHttpHandler {
     
     public void ProcessRequest (HttpContext context) {
         context.Response.ContentType = "text/plain";
         context.Response.Write("Hello World");
     }
 
     public bool IsReusable {
         get  {
             return false;
         }
    }
 }

By default, the IHttpHandler is implemented. We will modify the code in ProcessRequest to read images from database. We are going to use the DataTable to read the data from the database.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace UserManagement
{
/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
       string _imageId;
       if (context.Request.QueryString["id"] != null)
          _imageId = context.Request.QueryString["id"];
      else
      throw new ArgumentException("No parameter specified");


      SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.
      ConnectionStrings["master"].ConnectionString);
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = objcon;
      cmd.CommandText = "SELECT [Id],[Data] FROM [dbo].[ImageTable] where ID like '" + _imageId + "'";
      cmd.CommandType = System.Data.CommandType.Text;

      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataTable dt = new DataTable();
      da.Fill(dt);



      if (dt.Rows.Count > 0)
      {
         if (dt.Rows[0]["Data"] != DBNull.Value)
         {
             context.Response.ContentType = "image/jpeg";
             context.Response.BinaryWrite((byte[])dt.Rows[0]["Data"]);
         }
     }
   }
   public bool IsReusable
   {
      get { return false;}
   }
  }
}

now add image tage on Default.aspx page like.
<img alt=”test” src=”ImageHandler.ashx?id=9b27f3b5-9844-4ac9-8e60-7c6f1f0bb91f” />

Now run your application and the page (Default.aspx) displays the image served through HttpHandler.

C#.Net- How to Convert SQL to XML String and render output using XslCompiledTransform in Asp.net

Here I will explain how to convert datatable to xml string in asp.net using C#

Code for faching data from sql database

using (SqlConnection objcon = new SqlConnection(ConfigurationManager.ConnectionStrings[“TestDB”].ConnectionString))
{
objcon.Open();
SqlDataAdapter da = new SqlDataAdapter(“select * from Emp_Info”, objcon);
DataTable dt = new DataTable(“empInfo”);
da.Fill(dt);

using (TextWriter writer = new StringWriter())
{
dt.WriteXml(writer);
Response.Write(new XMLHelper().GetValue(@”C:\Tushar\SQLToXMLExample\XSLT\Demo.xslt”, writer.ToString()));
}
}
XMLHelper that generate Output string using XSLT file and XML String

public class XMLHelper
{
public XMLHelper()
{ }
public string GetValue(string templatePath, string xmlString)
{
XDocument xmlObj = XDocument.Parse(xmlString);
XDocument result = GetResultXml(templatePath, xmlObj);

return (result == null) ? string.Empty : result.Document.ToString();
}
public XDocument GetResultXml(string templatePath, XDocument xmlObj)
{
XDocument result = new XDocument();
using (XmlWriter writer = result.CreateWriter())
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(templatePath);
xslt.Transform(xmlObj.CreateReader(), writer);
}
return result;
}
}

XSLT File — Sample Demo

<?xml version=”1.0″ encoding=”utf-8″?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform&#8221;
xmlns:msxsl=”urn:schemas-microsoft-com:xslt” exclude-result-prefixes=”msxsl”
>
<xsl:output method=”html” omit-xml-declaration=”yes” indent=”yes”/>

<xsl:template match=”@* | node()”>
<html>
<body>
<table>
<tr>
<xsl:for-each select=”/*/node()”>
<xsl:if test=”position()=1″>
<xsl:for-each select=”*”>
<td>
<xsl:value-of select=”local-name()”/>
</td>
</xsl:for-each>
</xsl:if>
</xsl:for-each>
</tr>
<xsl:for-each select=”*”>
<tr>
<xsl:for-each select=”*”>
<td>
<xsl:value-of select=”.”/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Inherit Textbox control -c#

how to create a class which inherits textBox control in c# . the new class contains a new property like “Windowtype” and more.

[CustomAttributes(Browsable = true)]
public class Textbox_tushar : System.Web.UI.WebControls.TextBox
{

        public enum Size
        {
            Maximize,
            Minimize,
            Center
        }

        [CustomAttributes(Browsable = true)]
        public override string ID
        {
            get
            {
                return base.ID;
            }
            set
            {
                base.ID = value;
            }
        } 

        private Size _size;
        public Size WindowType
        {
            get { return _size; }
            set { _size = value; }
        }  

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);  
        }

}

C# Partial

Partial classes span multiple files. How can you use the partial modifier on a C# class declaration? With partial, you can physically separate a class into multiple files. This is often done by code generators.

Keywords

Example

With normal C# classes, you cannot declare a class in two separate files in the same project. But with the partial modifier, you can. This is useful if one file is commonly edited and the other is machine-generated or rarely edited.

Program that uses partial class: C#

class Program
{
    static void Main()
    {
	A.A1();
	A.A2();
    }
}

Contents of file A1.cs: C#

using System;

partial class A
{
    public static void A1()
    {
	Console.WriteLine("A1");
    }
}

Contents of file A2.cs: C#

using System;

partial class A
{
    public static void A2()
    {
	Console.WriteLine("A2");
    }
}

Output

A1
A2

Partial is required here. If you remove the partial modifier, you will get an error containing this text: [The namespace ‘<global namespace>’ already contains a definition for ‘A’].

Namespace

Tip: To fix this, you can either use the partial keyword, or change one of the class names.

Compilation

 

How does the C# compiler deal with partial classes? If you disassemble the above program, you will see that the files A1.cs and A2.cs are eliminated. You will find that the class A is present.

IL Disassembler

So: Class A will contain the methods A1 and A2 in the same code block. The two classes were merged into one.

Class

Tip: Partial classes are precisely equivalent to a single class with all the members.

Compiled result of A1.cs and A2.cs: C#

internal class A
{
    // Methods
    public static void A1()
    {
	Console.WriteLine("A1");
    }

    public static void A2()
    {
	Console.WriteLine("A2");
    }
}