Monday, December 24, 2012

Unable to display this web part. Error while executing web part: System.StackOverflowException: Operation caused a stack overflow in SharePoint 2010

In this post, I will explain an error user frequently see on their screen.
Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.
Correlation ID: XXXX
.

After analyzing the log file in 14 hive I got the below error
Error while executing web part: System.StackOverflowException: Operation caused a stack overflow.
After doing R & D I found that in August 2011 Cumulative update for SharePoint 2010, there is a timeout put on the XSLT transforms.
And after running the following commands at the PowerShell prompt.
 $farm = Get-SPFarm
$farm.XsltTransformTimeOut = 5
$farm.Update()
The page now appears correctly.

Sunday, October 14, 2012

Creating a List in SharePoint using ECMA Script

In this post, I will explain how to create a list in SharePoint using ECMA script. Use the ListCreationInformation object to define list properties and then pass this object to add (listCreationinformation object).
<script type="text/ecmascript">
function createSPList()
{
  var clientContext = new SP.ClientContext.get_current();
  var oWeb=clientContext.get_web();
  var listCreation = new SP.ListCreationInformation();
  listCreation.set_title('My Custom List');
  listCreation.set_templateType(SP.ListTemplateType.genericList);
  listCreation.set_description('List created using ECMA Script');

  this.oList = oWeb.get_lists().add(listCreation);
  clientContext.load(oList);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,this.OnFailure));
  }

function OnSuccess()
{
 alert(oList.get_title() + ' created.');
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  }
 </script>

Refer the below link for list template type

Deleting a List Item in SharePoint list using ECMA Script

In this post, I will explain how to delete list item in SharePoint list using ECMA script. To delete list item, firstly use getItemById (ID) function to fetch item to be deleted and then call deleteObject () to delete list item.
<script type="text/ecmascript">
function DisplayListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  this.oListItem = oList.getItemById(3);
  oListItem.deleteObject();  
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this, this.OnFailure));
  }
function OnSuccess()
{
 alert('Item deleted successfully');  
 }
function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +  args.get_stackTrace());
  }

</script>

Sunday, October 7, 2012

Updating a list item in SharePoint list using ECMA Script

In this post I will explain how to update list item in SharePoint list using ECMA script. To update list items, firstly use getItemById (ID) function to fetch item to be updated and then set value for that item. Finally call update () function to update list.

Add the below code in content editor web part and see the result

<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(UpdateListItems, "sp.js");

function UpdateListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  this.oListItem = oList.getItemById(2);
       
    oListItem.set_item('Title', 'Somnath');
    oListItem.set_item('LastName', 'Matere');
    oListItem.set_item('WorkingUnit', 'IT');
       
    oListItem.update();

    clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate
(this,this.OnSuccess), Function.createDelegate(this,       this.OnFailure));
  }

function OnSuccess()
{
 alert('Item Updated successfully');
  
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Adding a list item in SharePoint list using ECMA Script

In this post I will explain how to create/add list item in SharePoint list using ECMA script. To create list items, firstly create a ListItemCreationInformation object, set its properties and pass it as parameter to the addItem(parameter) function of the list object. Then set the properties on the list item and finally call update() function to update list.

Add the below code in content editor web part and see the result
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(AddListItems, "sp.js");

function AddListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  var listItemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(listItemCreateInfo);
       
    oListItem.set_item('Title', 'Somnath');
    oListItem.set_item('LastName', 'Matere');
    oListItem.set_item('WorkingUnit', 'IT');
       
    oListItem.update();

    clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{
 alert('Item Added successfully');
  
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Retrieve SharePoint List Items Using ECMA Script Part 2

As explained in previous post I will show how to retrieve list items using getItems (query). Here we will use the same SharePoint list specified in previous post. We will replace ECMA Script code specified in the Content Editor Web part.
getItems (query) function enables us to define CAML query that specifies which items to return or we can use the set_viewXml function to define query and return items that meet specific criteria.
Approach 1:
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  var CAMLquery = SP.CamlQuery.createAllItemsQuery();
  this.oAllListItem = oList.getItems(CAMLquery);
  //clientContext.load(this.oAllListItem);
clientContext.load(this.oAllListItem,'Include(Id,Title, LastName,WorkingUnit)');
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{

    var Html ='';
    var ListEnumerator = this.oAllListItem.getEnumerator();
Html='<table cellspacing="3" cellpadding="3" border="0"><tr><td>ID</td><td> First Name</td><td> Last Name</td><td> Department</td></tr>';
    while(ListEnumerator.moveNext())
    {
                var oItem = ListEnumerator.get_current();
                var ID= oItem.get_id();
var title=oItem.get_item('Title');
var lastName=oItem.get_item('LastName');
var dept=oItem.get_item('WorkingUnit');
   
   Html += '<tr><td>'+ID+'</td><td>'+title+'</td><td>'+lastName+'</td><td>'+
                    dept+'</td></tr></table>';
  
   }

   document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Approach 2:
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  var camlQuery = new SP.CamlQuery();
  camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>2</Value></Geq></Where></Query><RowLimit>2</RowLimit></View>');
 
  this.oAllListItem = oList.getItems(camlQuery);
  clientContext.load(this.oAllListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{

    var Html ='';

    var ListEnumerator = this.oAllListItem.getEnumerator();
Html='<table cellspacing="3" cellpadding="3" border="0"><tr><td>ID</td><td> First Name</td><td> Last Name</td><td> Department</td></tr>';
    while(ListEnumerator.moveNext())
    {
                var oItem = ListEnumerator.get_current();
                var ID= oItem.get_id();
                var title=oItem.get_item('Title');
                var lastName=oItem.get_item('LastName');
                var dept=oItem.get_item('WorkingUnit');
   
   Html += '<tr><td>'+ID+'</td><td>'+title+'</td><td>'+lastName+'</td><td>'+
                    dept+'</td></tr></table>';

  
   }

   document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Retrieve SharePoint List Items Using ECMA Script Part 1

In this post I will explain how to retrieve SharePoint list items using Client OM. To get items from a list using ECMA Script we can use below two functions
1.       getItemsById (id) - return a single item.
2.       getItems(query)- return multiple items
In this post we will retrieve list items using getItemsById () function.
Step 1: Create a custom list and name it as Employees.
Step 2: Rename Title column as FirstName, Add LastName, and WorkingUnit columns.
Step 3: Add content editor web part and add the below code
<script type="text/ecmascript">
ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  this.oListItem = oList.getItemById(1);
  clientContext.load(this.oListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,       this.OnFailure));
  }

function OnSuccess()
{
    var listItemInfo ='';
    var Html ='';

   Html += '<table cellspacing="'+3+'" cellpadding="'+3+'" border="'+0+'"><tr><td>ID</td><td>First Name</td><td>Last Name</td><td>Department</td></tr>'+
                    '<tr><td>'+oListItem.get_id()+'</td><td>'+oListItem.get_item('Title')+'</td><td>'+oListItem.get_item('LastName')+'</td><td>'+
                    oListItem.get_item('WorkingUnit')+'</td></tr></table>';
   
 document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Step 4: Add HTML Form web part and add below code
<table cellspacing="3" cellpadding="3" border="2">
<tbody><tr><td style="background-color:#f9f9f9"><div>
<div id="ECMADiv"></div>
</div></td>
</tr>
</tbody></table>
 In next post I will explain how to retrieve list items using getItems().

Tuesday, October 2, 2012

Get query string value using ECMA script

In this post, I will explain how to get query string value using ECMA script

<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(GetValue, "sp.js");

function GetValue()
  {
   var qs = getQueryStringValue();
   var myParam= qs["ID"];
   alert(myParam);  
  }

 function getQueryStringValue()
  {
      var associate  = {};
      var decodevalue = function (s)
      {
        return decodeURIComponent(s.replace(/\+/g, " "));
       };
      var queryString = location.search.substring(1);    
      var keyValues = queryString.split('&');
      for(var sm in keyValues)
      {  
       var key = keyValues[sm].split('=');    
       if (key.length > 1)
        { 
          associate[decodevalue(key[0])] = decodevalue(key[1]); 
         } 
      }   
     return associate; 
   } 
  
</script>

Get all subsites under SharePoint site using ECMA script

In this post, I will explain how to get all subsites under SharePoint site using ECMA script

<script type="text/ecmascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(GetSites, "sp.js");
function GetSites()
{
currentcontext = new SP.ClientContext.get_current();
if(currentcontext!=null && currentcontext!=undefined ){
currentweb = currentcontext.get_web();
this.subsites = currentweb.get_webs();
currentcontext.load(this.subsites);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess),
Function.createDelegate(this, this.OnFailure));
}
}
function OnSuccess(sender, args) {
var subsite = '';
var Listsubsite= this.subsites.getEnumerator();
while (Listsubsite.moveNext())
{
var Site = Listsubsite.get_current();
subsite += '\nID: ' + Site.get_id() + '\nTitle: ' + Site.get_title()+'\n Created date:'+ Site.get_created();
}
alert(subsite);
}
function OnFailure(sender, args) {
alert('Error');
}
</script>

Get Top site collection using ECMA script

In this post, I will explain how to get top site collection using ECMA script

 <script type="text/ecmascript">
var currentcontext = null;
var currentsitecol = null;
ExecuteOrDelayUntilScriptLoaded(GetTopLevelSiteCollection, "sp.js");
function GetTopLevelSiteCollection()
{
currentcontext = new SP.ClientContext.get_current();
if(currentcontext!=null && currentcontext!=undefined ){
currentsitecol= currentcontext.get_site().get_rootWeb();
currentcontext.load(currentsitecol);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess),
Function.createDelegate(this, this.OnFailure));
}
}
function OnSuccess(sender, args) {
var sitecol='';
sitecol+= '\nID: ' + currentsitecol.get_id() + '\nTitle: ' + currentsitecol.get_title()+'\n Created date:'+ currentsitecol.get_created();
alert(sitecol);
}
function OnFailure(sender, args) {
alert('Error');
}
</script>

Saturday, August 25, 2012

SharePoint: Copy document from one document library to file system programmatically

In this post I will explained how we can programmatically copy documents from one document library to file system.
Create a User interface as shown below and add the code snippet
protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SPSite oSite = SPContext.Current.Site;
                SPWeb oWeb = oSite.RootWeb;
                   
                CopyDocToFileSystem(oWeb, txtSourceLib.Text, txtLocation.Text);
                lblMsg.Text = " sucessfully copied";
                     
            }
            catch (Exception ex)
            { }
           
        }


        public void CopyDocToFileSystem(SPWeb oWeb, string sourceDocLib, string destFilePath)
        {
            SPFolder oSourceDocLibraryFolder = oWeb.GetFolder(sourceDocLib);

            SPFileCollection oFileCol = oSourceDocLibraryFolder.Files;
            foreach (SPFile oFile in oFileCol)
            {
                byte[] b = oFile.OpenBinary();
                FileStream oFileStream = new FileStream(destFilePath + "\\" + oFile.Name, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter oBinaryWriter = new BinaryWriter(oFileStream);
                oBinaryWriter.Write(b);
                oBinaryWriter.Close();
            }
        }



SharePoint: Copy document from one document library to another programmatically

In this post I will explained how we can programmatically copy documents from one document library to another.
Firstly create two document library.Then create a Visual studio solution with User Interface as shown below
Add the below code snippet
protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
              SPSite oSite = SPContext.Current.Site;
              SPWeb oWeb = oSite.RootWeb;
                   
              SPFileCollection oFileCol = oWeb.GetFolder(txtSourceLib.Text).Files;

              foreach (SPFile oFile in oFileCol)
              {
                oFile.CopyTo(txtTargetLib.Text + "/" + oFile.Name, true);
                }
lblMsg.Text = "sucessfully copied";
            }
            catch (Exception ex)
            { }
           
        }

Wednesday, August 15, 2012

Add webpart using Toolpaneview

In this post I will explain how we can add web part from toolpaneview.
Create a webpart page and append ?ToolPaneView=2 to the page URL. The result page is as shown in below screenshot

Sunday, July 29, 2012

Dynamically Apply/change SharePoint 2010 Header Image

In this post I will explained how we can dynamically apply/change SharePoint 2010 site Header Image. Create Image library, add image named “SiteHeaderImg.png” and below code in master page
<script type="text/javascript">
  
    function ChangeImage() {
        try {
     var URL_str = L_Menu_BaseUrl + '/ImageLibrary/SiteHeaderImg.png';
            
                document.getElementById("s4-titlerow").style.background = "background-image: url('" + URL_str + "') no-repeat";
                /* (Works in Firefox) */
  document.getElementById("s4-titlerow").style.background = "url('../ImageLibrary/SiteHeaderImg.png') no-repeat";
      
        }
        catch (e) {
            alert(e);
        }
    }
    _spBodyOnLoadFunctionNames.push("ChangeImage()");
 
</script>

Hosting SharePoint 2010 InfoPath form in web part

In this article I will explained how to add InfoPath form in SharePoint 2010 InfoPath form web part. Firstly we will create an  EmployeeDetails list
with following fields
 Now we will customize the InfoPath form as shown below
Now we will create SharePoint page and edit that page to insert InfoPath form web part on it

Saturday, May 19, 2012

What we can do with InfoPath 2010


Special thanks to my friend who inspired me to write series of article on InfoPath. In this first article I will talk features of InfoPath 2010 and SharePoint 2010. Following are the new features of InfoPath 2010
1.    Quickly design electronic forms with easy to use tools for developers and advance business users.
2.    New controls added in InfoPath 2010 designer.
3.    Easily adding rules and formatting.
4.    Quickly publishing forms in designer.
5.    Creating forms for SharePoint lists.
6.    Hosting InfoPath form in web parts.
7.    Integration of InfoPath with web services.
8.    Building InfoPath form with codes.

Nice blog to read