Thursday, November 14, 2013

Common Issues with Rad Grid : telerik Unable to get property 'documentElement' of undefined or null reference

Hi all,

When developing ASP.Net applications using Telerik Controls, you may have come across this error saying "telerik Unable to get property 'documentElement' of undefined or null reference" which will ask you to debug using the javascript debugger. 

I came across this error when working with Telerik Controls in IE 10. When the browser mode is changed to IE 9, the issue fixed.  But this is not good for your Client.

If you are using a Telerik version which is outdated you will face this problem. One thing you can do is to upgrade your Telerik version.

Next you can fix this issue by adding the following lines in your web page. 

<head runat="server">
    <!-- Mimic Internet Explorer 9 -->
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
</head>

Another fix that is discussed in various posts in web is to edit the web.config file as follows. (This fix didn’t work for me and I have also seen others who have not been able to fix by editing the web.config file.) Anyway following is the way you can do that.

<system.webServer>

    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=9"/>
      </customHeaders>
    </httpProtocol>
   
</system.webServer>



Start Developing ASP.Net Applications Using Telerik Controls

Hi all,

Today I’m going to show you how to setup the environment to work with Telerik controls in ASP.Net web applications. In a previous tutorial I showed you how to develop a simple grid using Telerik RadGrid. When developing the grid, we have to add the references and edit the web.config file to avoid the errors that come on our way.

First you have to add the reference to “Telerik.Web.UI.dll”.





















Next the web.config should be edited as following. (Note: I have done this to support a basic rad grid and this may change according to your application)
 <configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
   
    <httpHandlers>
      <add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI"/>
      </controls>
    </pages>
   
  </system.web>

  <system.webServer>
    <handlers>
      <add name="Telerik_Web_UI_WebResource_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource"/>
    </handlers>
  </system.webServer>

  <location path="Telerik.Web.UI.WebResource.axd">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
 
</configuration>

Finally you have to add the  “Telerik.Web.UI.dll” to the bin folder of your project.

Now you can start developing ASP.Net applications using Telerik.


Hope this helps J

Friday, November 8, 2013

Common Issues with Rad Grid : Input string was not in a correct format.

If you get this error "Error: Sys.WebForms.PageRequestManagerServerErrorException: Input string was not in a correct format." when u click on the edit button of your radgrid data item, what you have to do is first check whether the data-format-strings are correct in your grid. I got this error because I have incorrectly configured the data-format-string for the given object's fields.

Hope this helps, thanks :-)

Wednesday, October 30, 2013

How to Truncate a String in a Telerik Grid (RadGrid) Column

Hi all, this small blog post is to show how you can truncate a string in a telerik grid when the string is too long to be shown inside the column. Truncation should be done at the ItemDataBound event of telerik grid.

Following is the column template :

<telerik:GridBoundColumn UniqueName="Column1" Visible="true" ShowSortIcon="true">
<ItemStyle Wrap="true" />                   

</telerik:GridBoundColumn>

The ItemDataBound Column will look like this. 

protected void Grid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{

if (e.Item is GridDataItem)
{
GridDataItem dataBoundItem = e.Item as GridDataItem;
if (dataBoundItem["Column1"].Text.Length > 10)
       {
        dataBoundItem["Column1"].Text = dataBoundItem["Column1"].Text.Substring(0, 10) + "...";
       }
}

}



Hope this helps J
Thank You J

Monday, October 28, 2013

How to Develop a Simple RadGrid Easily

Hi all, in this tutorial I am going to show you how to develop a very simple grid using Telerik. 

First create the structure of the RadGrid using the markups.

<telerik:radscriptmanager id="RadScriptManager1" runat="server"EnablePageMethods="true"/>
<asp:Panel ID="PnlGrid" runat="server">
        <telerik:radgrid runat="server"id="Grid"autogeneratecolumns="false"allowpaging="true" enableviewstate="true"
OnItemCreated ="Grid_ItemCreated"
OnNeedDataSource ="Grid_NeedDataSource">
        <MasterTableViewCommandItemDisplay="None" InsertItemPageIndexAction="ShowItemOnCurrentPage" EditMode="InPlace">
            <Columns>
                <telerik:GridBoundColumn UniqueName="Column1"Visible="true">
                    <ItemStyleWrap="true"/>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Column2"Visible="true">
                    <ItemStyleWrap="true"/>
                </telerik:GridBoundColumn>
            </Columns>
           
            <NoRecordsTemplate>
                <asp:Label ID="lblNoRecords"runat="server"/>
            </NoRecordsTemplate>
        </MasterTableView>
        <PagerStyle Mode="NextPrevAndNumeric"/>
        <ClientSettings EnablePostBackOnRowClick="false">
            <Selecting AllowRowSelect="true"/>
        </ClientSettings>
        <SelectedItemStyleBorderStyle="None"BorderWidth="0px"/>
    </telerik:radgrid>
  
</asp:Panel>

Between the ‘Columns’ tags, you can specify the columns you need using telerik:GridBoundColumn. Here I have used telerik:GridBoundColumn but we can use different other column types. As this is going to be a simple grid, I have only included the telerik:GridBoundColumn.
In this grid, I have specified some events. Let me explain them very briefly.
OnNeedDataSource : When this event fires, the grid will be bound to a given data source. It can be either a SQL data source or a list of objects.
OnItemCreated : I thought of showing you this method, because this method can be really helpful, when you are trying to dynamically change the items in the grid. Inside this method, you can do so many functions, for setting grid headers, data types for columns, data format strings, button names etc.
Then I have included the <NoRecordsTemplate> ,which will used for displaying the grid, when there are no records to be shown in the data source.

Then I have added pager style for the grid. This is a really cool feature in Telerik Grid, because it creates an amazing pagination for the grid.

In the <ClientSettings> allowed the row selection and avoided autopostback on row click. You can do server side functions by enabling this autopostback.

Then I have given a simple style for the selected row.
OK, now we are good with the structure of the RadGrid.  Then let’s see how we can bind the data to the grid and display it. For this example I have used a sample Student list to populate the grid.

Here’s the student class.

public class Student
    {
        public int StudentID { get; set; }
        public stringStudentName { get; set; }

        public Student()
        {
        }

        public Student(intid, string name)
        {
            this.StudentID = id;
            this.StudentName = name;
        }
    }

The code behind of the web page will look like this.

protected void Page_Load(object sender, EventArgse)
{
}

protected voidGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
this.SetDataFieldsForGridColumns();
       this.Grid.DataSource = this.GetStudentsList();
}

protected voidGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item isGridHeaderItem)
{
              GridHeaderItemheader = (GridHeaderItem)e.Item;
              header["Column1"].Text = "Student ID";
              header["Column2"].Text = "Student Name";
}

       if (e.Item is GridNoRecordsItem)
       {
              GridNoRecordsItemnoRecordsItem = e.Item as GridNoRecordsItem;
System.Web.UI.WebControls.LabellblNoRecords = (System.Web.UI.WebControls.Label)noRecordsItem.FindControl("lblNoRecords");
                lblNoRecords.Text = "Sorry, No Records are available for viewing";
       }
 }
private voidSetDataFieldsForGridColumns()
{
GridBoundColumn column1 = this.Grid.MasterTableView.GetColumnSafe("Column1") as GridBoundColumn;
GridBoundColumn column2 = this.Grid.MasterTableView.GetColumnSafe("Column2") as GridBoundColumn;

column1.DataField = "StudentID";
column2.DataField = "StudentName";
}

private List<Student> GetStudentsList()
{
List<Student> students = new List<Student>();
for (inti = 0; i < 20; i++)
       {
       students.Add(new Student(i, string.Format("Std{0}",i)));
       }

       return students;
}


Final Output for the grid will look like this.



In this tutorial, I have explained how to develop a simple static radgrid with populated with a list of data.  


Thanks. J

Monday, October 21, 2013

Telerik RadGrid : Add Sorting to RadGrids EASILY !!!

Hi all, This tutorial will explain how to add sorting for a RadGrid easily. Once you have added the grid to your page, you'll have to add the following codes according to your grid.

First in the aspx or ascx page or controller,

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
    <script type="text/javascript">
   
        function SortColumn(ColumnName)
        {
         var masterTable = $find("<%= Grid1.ClientID %>").get_masterTableView();
          masterTable.sort(ColumnName);
        }
   
    </script>

</telerik:RadCodeBlock>

Then in the code behind, add the following code. 

protected void Grid1_PreRender(object sender, EventArgse)
        {           

            foreach (GridColumncol in Grid1.MasterTableView.RenderColumns)
            {
                foreach (GridHeaderItemheader in Grid1.MasterTableView.GetItems(GridItemType.Header))
                {
                    header[col.UniqueName].Attributes.Add("OnClick", "return SortColumn('" + col.UniqueName + "');");
                }
            }
        }



Hope this will help someone... Thanks :-)





Sunday, October 20, 2013

How to Remove an Assembly from GAC using gacutil in Windows Server 2008 r2 (Without using .net sdk)

Hi all, I happened to remove some unwanted dlls from the GAC in a production server. In this server I didn't have windows SDK installed and therefore I had to use some other method to use gacutil.

The first thing I did was to copy the gacutil and it's configuration file from my local machine. It's located in C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bin\.  Copy the gacutil Application and gacutil.exe CONFIG file from there and paste it to a folder in your Server. 

When you want to install  an assembly to GAC, copy the above files to your assembly location and open the cmd as an Administrator. Then run the command "gacutil -i <assembly_name>" to install the assembly.

To uninstall an assembly from GAC you have to use "gacutil -u" command. As gacutil is now in a sepereate folder in your server, redirect to that location from the cmd and use the above command. Here you have to use the fully qualified name of the assembly in the GAC. Following is an example. 

gacutil -u "hello,Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789ABCDEF"

When you uninstall the assembly, you'll get an error message including this line. 

"Unable to uninstall: assembly is required by one or more applications"

To solve this follow the instructions as follow. 


  1. cd %systemroot%\assembly\
  2. cd gac_msil (Fom here you may have more that one "gac" directory, so you will have to search within each to find your component.  For me, it is within the "gac_MSIL" directory.)
  3. cd <assembly DLL name>
  4. cd <assembly version number>__<public key token>                                                            
    1. For example: 1.0.23.456__10dbd0fba6984148
  5. erase *.*
  6. Say "y" to are you sure.
  7. cd ..
  8. rd <assembly version number>__<public key token>
  9. cd ..
  10. rd <assembly DLL name>

Tuesday, October 8, 2013

RadGrid Tutorials - How to Change the Header Text of a RadGrid Column, When Gird is in EditMode

When you want to change the header text of a particular column in a Telerik Grid (RadGrd) you can do that easily from the code behind using the ItemCreated event in the grid.

protected void Grid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
            //Set Grid Column Headers
            if (e.Item is GridHeaderItem)
            {
                GridHeaderItem header = (GridHeaderItem)e.Item;
                header["ColumnUniquName"].Text = "Header Titile"; 
            }
}


There may be some requirements from your client, "This column name should be changed when you are inserting an item to the grid".... So how do you do that... simple as this. 

protected void Grid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
            //Set Grid Column Headers
            if (e.Item is GridHeaderItem)
            {
                GridHeaderItem header = (GridHeaderItem)e.Item;
              if (this.Grid.MasterTableView.IsItemInserted)
              {
                 header["ColumnUniquName"].Text = "Header Titile Changed";
              }
              else
              {
                  header["ColumnUniquName"].Text = "Header Titile";
              } 
             }
}

Hope this helps.....

Tuesday, May 21, 2013

How to use a List Definition for Sharepoint 2010 in VS 2010

When creating a list definition you have to create and edit two main files. They are the Elements.xml and Schema.xml. In the Elements.xml you have to add the <Fields> and <Content Type> elements. Then in the Schema.xml you have to refer them.

When creating the GUIDs for the Fields and Content types, you have to be careful because they have to be inherited. Then those GUIDs can be created using Tools-> Create GUID-> New-> 4th Option

This is the MSDN reference for creating a List Definition.
List Instances are the objects that can be used for creating instances of the list definition.

Update:

You can only change the schema.xml to create the List Definition. There first you have to add the <Content Type> then the <Fields> and <FiledRef>s. After that, in the <ViewFields> you can add the <FieldRefs> to determine, which <Fileds> should be viewed.
When creating the GUID for the content type ID you have to be careful. There you have to add the correct Item ID (You can find them in  C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\ctypes\ctypes.xml).

To create the ID for the Content Type, first add the ItemID (Eg: 0x01 for ContentTypes) then add the GUID without the hyphens. For FieldRef IDs also there are default IDs for fields like Title. They can be found in the wss xmls in the 14\TEMPLATE\FEATURES folder. As an example, field ID for the title field is fa564e0f-0c70-4ab9-b863-0177e6ddd247.

Update:

Filed Type IDs are here:


C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\fields\fieldswss3.xml

Issues and Solutions for Sharepoint 2010 - Enable Session State Issue

This issue arises due to missing or removing session element. For that just verify whether the "enableSessionstate" is set to "true" and add the following line in the httpmodules in web.config file.

1) <pages enableSessionState="true" enableViewState="true" enableViewStateMac="true"/>
2) <add name="Session" type="System.Web.SessionState.SessionStateModule" />

If this doesn't work check whether "Session" is removed somewhere like this,
<remove name="Session" />.

If so add the 2nd line again after that. 
For a detailed article visit this blog. 

Monday, May 20, 2013

Sending an Email using Sharepoint Web Part


For sending a mail using SPUtility I referred to this article. This code is just a demo.

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;
using System.Data;
using System.Collections;
using Microsoft.SharePoint.Utilities;

namespace CustomPeoplePickerOne.PeoplePicker_swp_1
{
    [ToolboxItemAttribute(false)]
    public class PeoplePicker_swp_1 : WebPart
    {
        PeopleEditor pe = null;
        SPWeb web = null;
        protected override void CreateChildControls()
        {
            web = SPContext.Current.Web;

            pe = new PeopleEditor();
            pe.ValidatorEnabled = true;
            this.Controls.Add(pe);

            Button viewPeople = new Button();
            viewPeople.Text = "View";
            viewPeople.Click += new EventHandler(viewPeople_Click);
            this.Controls.Add(viewPeople);

            Button sendMailButton = new Button();
            sendMailButton.Text = "Send Mail";
            sendMailButton.Click += new EventHandler(sendMailButton_Click);
            this.Controls.Add(sendMailButton);
               
        }

        void sendMailButton_Click(object sender, EventArgs e)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                if (SendMail("kinathr@navantis.com"))
                {
                    this.Controls.Add(new LiteralControl("<br/>"));
                    this.Controls.Add(new LiteralControl("<b>Email Successfully sent to Kinath</b>"));
                }
                else
                {
                    this.Controls.Add(new LiteralControl("<br/>"));
                    this.Controls.Add(new LiteralControl("<b>Sending Failed to Kinath</b>"));
                }
             
            });


        }

        void viewPeople_Click(object sender, EventArgs e)
        {
            viewPeopleOption4();
        }

        void viewPeopleOption()
        {
            foreach (var loginName in pe.CommaSeparatedAccounts.Split(';', ','))
            {
                SPUser user = SPContext.Current.Web.EnsureUser(loginName);
                TextBox tb = new TextBox();
                tb.Text = string.Format("Name : {0} Email : {1}", user.Name, user.Email);
                this.Controls.Add(tb);

                //SPUtility.SendEmail(
            }
        }

        void viewPeopleOption2()
        {
            //Create the data table and add data to it
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn(" Name ", typeof(String)));
            dt.Columns.Add(new DataColumn(" Email ", typeof(String)));

            //get data from the people editor
            for (int i = 0; i < pe.ResolvedEntities.Count; i++)
            {
                string accName = "";
                string email = "";
                PickerEntity pickerEntity = (PickerEntity)pe.ResolvedEntities[i];
                Hashtable hsEntityData = pickerEntity.EntityData;
                if (hsEntityData.ContainsKey("Account Name"))
                {
                    accName = Convert.ToString(hsEntityData["Account Name"]);
                }
                else
                {
                    accName = "Not available";
                }
                if (hsEntityData.ContainsKey("Email"))
                {
                    email = Convert.ToString(hsEntityData["Email"]);
                }
                else
                {
                    email = "Not available";
                }


                TextBox tb = new TextBox();
                tb.Text = string.Format("Name : {0} Email : {1}", accName, email);
                this.Controls.Add(tb);

            }
        }

        void viewPeopleOption3()
        {
            var accountName = pe.Accounts[0];
            SPUser user = web.EnsureUser((string)accountName);

            Label userLable = new Label();
            userLable.Text = string.Format("User : {0} Email : {1}",user.Name,user.Email);
            this.Controls.Add(userLable);

        }

        void viewPeopleOption4()
        {
            if (pe.IsValid)
            {
                for (int i = 0; i < pe.ResolvedEntities.Count; i++)
                {
                    PickerEntity picker = (PickerEntity)pe.ResolvedEntities[i];
                    Hashtable hstEntityData = picker.EntityData;
                    string[] name = picker.DisplayText.Split(' ');
                    string Email = Convert.ToString(hstEntityData["Email"]);
                    //string FName = name[0].ToString();
                    //string SName = (name[1].ToString() != null) ? name[1].ToString() : "";
                    Label userLable = new Label();
                    userLable.Text = Email;
                    this.Controls.Add(userLable);

                }
            }
        }

        bool SendMail(string userMail)
        {
            bool success = false;
            /*
             * public static bool SendEmail(
                       SPWeb web,
                       bool fAppendHtmlTag,
                       bool fHtmlEncode,
                       string to,
                       string subject,
                       string htmlBody,
                       bool appendFooter
                        )
             * */

            SPWeb web = SPContext.Current.Web;
            bool fAppendHtmlTag = false;
            bool fHtmlEncode = false;
            string toEmail = userMail;
            string subject = "Test Email";
            string htmlBody = "Test Email Body";
            bool appendFooter = false;

            //first check whehter the SMTP settings are established
            if (SPUtility.IsEmailServerSet(web))
            {
                success = SPUtility.SendEmail(web, fAppendHtmlTag, fHtmlEncode, toEmail, subject, htmlBody, appendFooter);
            }
            else
            {
                this.Controls.Add(new LiteralControl("<br/>"));
                this.Controls.Add(new LiteralControl("<b>SMTP settings not set</b>"));
            }
            return success;
        }
    }
}