Friday, April 6, 2012

SharePoint 2010 : Use Resouce(resx) file in a Multilingual site.

Goal

Our site is created using variations in both English and Spanish. Create a Visual Web Part which can use the resource file(.resx) to show different texts for different language.

Steps to achieve goal

  • Create a SharePoint project with name "Sample".
  • Add a web part with name "SampleWebPart".
  • Add a "Mapped Folder" to "Resources". 2 files needs to be added.
    1. SampleWebPart.en-US.resx - English version resource file. Add some text to the resource.
    2. SampleWebPart.es-ES.resx - Spanish version resource file. Add some text to the resource.
  • At this point the project "Solution Explorer" will look like
  • For applying the resource, Open the Feature1 properties. And make the 2 changes shown in the below given image.
  • Use the HTML and C# Code below.
  • Once the above given steps are done, deploy the web part and They will display as below given image.


HTML - SampleWebPartUserControl.ascx

<h1><asp:Literal ID="ltrlTitle" runat="server" /></h1>
<hr />
<h3>
    <asp:Literal ID="ltrlDescription" runat="server" />
</h3>


C# - SampleWebPartUserControl.ascx.cs

#region System
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
#endregion

namespace Sample.SampleWebPart
{
    /// <summary>
    /// Simple example to use Resouce file with English/Spanish language.
    /// </summary>
    public partial class SampleWebPartUserControl : UserControl
    {
        #region Events

        /// <summary>
        /// Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            ltrlTitle.Text = LoadResource( ResourceName.Title );
            ltrlDescription.Text = LoadResource(ResourceName.Description);
        }

        #endregion

        #region Resource Reader

        /// <summary>
        /// Name for the Version to be considered.
        /// NOTE :- Use exactly same "Name" as used in Resource(resx) file.
        /// </summary>
        public enum ResourceName
        { 
            Title,
            Description
        }

        /// <summary>
        /// Gets the text on the basis of "Name" in Resource(resx).
        /// </summary>
        private string LoadResource(ResourceName _resName)
        {
            return Microsoft.SharePoint.Utilities.SPUtility.GetLocalizedString("$Resources:" + _resName.ToString(),
                "SampleWebPart"
            , (uint)System.Globalization.CultureInfo.CurrentUICulture.LCID); 
        }

        #endregion
    }
}


Happy Coding

Get all properties of Object using Javascript.

Goal

Assuming we are working on an a task. On a process we get an object. We don't know what exactly is there in the object or what properties the object is having. The javascript mentioned will print the list of properties of an object.

Solution

<script language="javascript" type="text/javascript">       
    var _jsonObject = {"Property1":1,"Property2":"Simple String","Property3":true};
    alert(_jsonObject);

    var _html = "";
    for (var key in _jsonObject) {
        _html = _html + key + " : " + _jsonObject[key] + "<br />" ;
    }
    document.writeln(_html);
</script>


Output

Saturday, March 3, 2012

SharePoint 2010 Error Solution : A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.

Introduction

An occours when a user tries to add a webpart on the page. The description of the error is "A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.".


Test Cases

Here, I am creating a small solution to show why I got this issue.
  1. Open Visual Studio 2010. Create a project with name "Sample".
  2. Add a WebPart to the project with name "SomeWebPart"(Note : Mind it WebPart not VisualWebPart).
  3. Add a class library to the solution with name "Helper".
  4. Add a "Helper.snk" to the project by Right Clicking "Helper" > Properties > Signing > Choose a strong name...
  5. Once that is done the structure will look like image given below
  6. Helper.Enums Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Helper
    {
        public class Enums
        {
            public enum SomeType
            {
                A = 0,
                B = 1,
                C = 2
            }
        }
    }
    
  7. SomeWebPart.cs Code
    using System;
    using System.ComponentModel;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    
    namespace Sample.SomeWebPart
    {
        [ToolboxItemAttribute(false)]
        public class SomeWebPart : WebPart
        {
            /// <summary>
            /// The enum which resides in enum
            /// </summary>
            public Helper.Enums.SomeType SomeTypeEnum { get; set; }
    
            /// <summary>
            /// Create child control
            /// </summary>
            protected override void CreateChildControls()
            {
    
            }       
            
        }
    }
  8. Deploy to the site. Try adding the WebPart and it will give the above mentioned error.


Problem

The problem is "Sample.dll" created for the WebPart gets added to the wsp and gets added to GAC automatically but the "Helper.dll" is not considered as a safe one and it stays out of GAC and so while adding the WebPart, it blows and the error shows on the alert window.

Solution

  1. Sample > Package > Open "Package.package"
  2. At the bottom you will find an option title "Advanced".
  3. As shown in the image select "Add Assembly from Project Output...".
  4. In the dialog select "Helper" will auto populate the Helper details.
  5. Safe Controls section add a new item.
  6. Fill the Namespace and Assembly with name "Helper".
  7. Click "OK" and exit the dialog. You can see the settings of Helper added on the Advanced screen.
  8. Deploy the WebPart and try adding it again. It should work.


Hope this helped!

SharePoint 2010 : Remove a WebPart from Page programmatically using C#.

Goal

To remove webparts from a page programmatically using C#.

Code

/// <summary>
/// This function will remove web parts with title passed
/// </summary>
/// <param name="_web">Web object</param>
/// <param name="_pageUrl">The url of the page on which the web part exists.</param>
/// <param name="_title">The title of the Web part</param>
private void RemoveWebPart(SPWeb _web, string _pageUrl, string _webPartTitle)
{
    //Remove the control once the page is copied
    Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager _webPartCollection = _web.GetLimitedWebPartManager(_pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

    //Retrive the webpart and remove
    IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
                                                                            where string.Compare( _wp.Title , _webPartTitle  , true ) == 0
                                                                            select _wp).ToList();

    //Check if there are any web parts found
    if (_listFormWebParts != null)
    {
        foreach (Microsoft.SharePoint.WebPartPages.WebPart _listFormWebPart in _listFormWebParts)
        {
            //Remove the webpart
            _webPartCollection.DeleteWebPart(_listFormWebPart);

            //Update
            _web.Update();
        }
    }
}


Tip

Suppose we dont want to remove the webpart using "Title" we want to remove the webpart with type.
//Retrive the webpart and remove
IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
                                                                        where _wp.GetType() == typeof(Microsoft.SharePoint.WebPartPages.ListFormWebPart)
                                                                        select _wp).ToList();

Monday, February 27, 2012

SQL Server : Sample for reading xml data

Goal

Simple SQL query to fetch data from an xml.
--//---------- Declare ----------//
DECLARE @xmlSample XML;

SET @xmlSample = '<GUIDs>
  <GUID Temp="a">1</GUID>
  <GUID Temp="a">2</GUID>
  <GUID Temp="a">3</GUID>
  <GUID Temp="b">4</GUID>
  <GUID Temp="b">5</GUID>
</GUIDs>';

--//---------- Set Query ----------//
SELECT * FROM 
(
    SELECT 
        d.value('.', 'INT') AS GUID , 
        d.value('@Temp', 'VARCHAR(36)') AS Temp
    FROM @xmlSample.nodes('/GUIDs/GUID') d(d) 
) AS A