Thursday, March 28, 2013

Add Multiple WebParts using PowerShell Script

Hi All,


Imagine a scenario where you need to create 100 web part pages with different templates. You would spend a lot of time creating those pages. One of the approaches can be having a PowerShell script which can create web part pages for templates that you want.

Here is a simple script that creates web part pages in a loop.

[xml]$xmlfile = Get-Content ConfigFile.xml 

foreach( $sitecoll in $xmlfile.Configuration.SiteCollection) 
{ $site = $sitecoll.name }

 $spSite= Get-SPSite $site 
$web = $spSite.OpenWeb() 
$layoutTemplate = 4 # Template code 
$web = $spSite.OpenWeb() 
$list = $web.GetList("/sites/SharePointSite/SitePages/")
 $i = 1
 while ($i -le 5)
 { Write-Host $pageTitle = "WebPartPage& + $i 

$xml = "<?xml version=""1.0"" encoding=""UTF-8""?&gt;

<Method ID=""0,NewWebPage""><SetList Scope=""Request"">" + $list.ID + "</SetList><SetVar Name=""Cmd"">NewWebPage</SetVar><SetVar Name=""ID"">New</SetVar><SetVar Name=""Type"">WebPartPage</SetVar><SetVar Name=""WebPartPageTemplate"">" + $layoutTemplate + "</SetVar><SetVar Name=""Overwrite"">true</SetVar><SetVar Name=""Title"">" + $pageTitle + "</SetVar></Method>"

 $result = $web.ProcessBatchData($xml)

 $i++ 

Write-Host -foregroundcolor Green $pageTitle 'created successfully' 

}

and when you run here is the output of the script and then final result



If you observe closely here we have specified layouttemplate, we have specified 4. This related to various templates like three column, four columns, headers the template that we select while creating web part page.

 Possible LayoutTemplate values are :

# 1 - Full Page, Vertical
# 2 - Header, Footer, 3 Columns
# 3 - Header, Left Column, Body
# 4 - Header, Right Column, Body
# 5 - Header, Footer, 2 Columns, 4 Rows
# 6 - Header, Footer, 4 Columns, Top Row
# 7 - Left Column, Header, Footer, Top Row, 3 Columns
# 8 - Right Column, Header, Footer, Top Row, 3 Columns


Saturday, February 23, 2013

WebPart Life Cycle in different PostBacks


On Page Load

  1. Constructor
  2. OnInit
  3. OnLoad
  4. ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  5. CreateChildControls
  6. OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  7. SaveViewState
  8. Render
  9. RenderChildren
  10. RenderContents

On 1st Postback
(PostBack click handler sets ViewState via public Property)

  1. Constructor
  2. OnInit
  3. CreateChildControls
  4. OnLoad
  5. PostBack click handling
  6. ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  7. OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  8. SaveViewState
  9. Render
  10. RenderChildren
  11. RenderContents

On 2nd Postback
(PostBack click handler sets ViewState via public Property)

  1. Constructor
  2. OnInit
  3. LoadViewState
  4. CreateChildControls
  5. OnLoad
  6. PostBack click handling
  7. ConnectionConsumer method is called if web part is connectable (sets the connection providers interface in the webpart)
  8. OnPreRender (if your web part is connectable you would typically call the connection provider here to retrieve data)
  9. SaveViewState
  10. Render
  11. RenderChildren
  12. RenderContents
Note that during the 2nd postback, LoadViewState, is called, since in the 1st postback the click handler sets the value of the ViewState backed public property.

Thursday, February 21, 2013

Where are Assemblies in Sandboxed Solutions Deployed?

Hi All,

Sometime back I started working on SandBox Solutions. I came across many issues and situation in terms of restrictions and Resource Point Utilization.

When I tried creating a Visual WebPart then I neede PowerTool VS extensions inorder to make it work.
Hence I realized that in sandbox solution, we are not dealing with file system. It its not that way then where my assemblies reside.

Then came across a msdn article which enlightened me with following facts.

The assemblies in the sandboxed solution are included in the solution pkg i.e. ".wsp" file, and the pkg is deployed to the site collection's solution gallery.
When a sandbox solution is accessed for the first time i.e. when a user access the webpart from sandbox solution, any assembly in the solution is extracted from the pkg in the gallary and copied to the file system of the server that is handling the sandboxed request. The location is
c:\ProgramData\Microsoft\SharePoint\UCCache

The executable of this service is SPUCHostService.exe. The server that handles the sandboxed request is not necessarily the front-end web server that is handling the initial HTTP request.
The Microsoft SharePoint Foundation Sandboxed Code Service can be run on back-end application servers in the farm instead. Because the sandboxed user process (SPUCWorkerProcess.exe) cannot copy anything to the file system, the copying is done by theMicrosoft SharePoint Foundation Sandboxed Code Service.

The assemblies of a sandboxed solution do not stay in the file cache perpetually. When the user session that accessed the solution ends, the assemblies stay in the cache for only a short time, and they may be reloaded from there if another user session accesses them. Eventually, if they are not accessed, they are removed in accordance with a proprietary algorithm that takes into account how busy the server is and how much time has gone by since the assemblies were last accessed. If the sandboxed solution is used after that time, the assemblies are extracted again and copied to the UCCache.


Saturday, January 19, 2013

How to create a Dynamic CAML Query

Hi All,

Many a times you might come into a situation when you have to deal with some complex query building and the scenario is like you have to pull the data from a SharePoint list and the records on which you need to fire the <Where> clause is not fixed.


So, you to need to write a dynamic query where the <OR> tags changes accordingly.
Here is the code:

// This lstPeers can be of any type like array or List Type or Collection.
List<String> lstPeers = new List<String>();

SPQuery peersQuery = new SPQuery();
string createquery = "";
peersQuery.Query = "<Where>" + CreateDynamicQuery(createquery, lstPeers) + "</Where>";


Here is your Dynamic Query :

protected String CreateDynamicQuery(String query, List<string> lstString)
        {
            bool firstIteration = true;
            if (query != "")
            {
                query = "<Or>" + query;
                firstIteration = false;
            }

            if (lstString.Count >= 2)
            {
                query += "<Or>";
                query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>" + lstString[0] + "</Value></Eq>";
                query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>" + lstString[1] + "</Value></Eq>";
                query += "</Or>";

                lstString.RemoveRange(1, 1);
                lstString.RemoveRange(0, 1);

                if (!firstIteration)
                    query += "</Or>";

                if (lstString.Count != 0)
                    query = CreateDynamicQuery(query, lstString);
            }
            else
            {
                if (lstString.Count != 0)
                {
                    query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>" + lstString[0] + "</Value></Eq>";
                    if (!firstIteration)
                        query += "</Or>";
                }
            }
            return query;
        }


As you can notice you are calling a recursive function and dynamically creating the <OR> tags.

I am sure this will help your case !!



Thursday, January 10, 2013

Error occurred in deployment step 'Recycle IIS Application Pool': The communication object, System.ServiceModel.InstanceContext, cannot be used for communication

Hi All,


When deploying a solution to SharePoint 2010, I suddenly got the error message:
Error occurred in deployment step ‘Recycle IIS Application Pool’: The communication object, System.ServiceModel.InstanceContext, cannot be used for communication because it has been Aborted.
Restarting Visual Studio did the trick. (IISreset did not help..)

Wednesday, January 9, 2013

SharePoint 2010 Web Part Error "The UserCodeToken is invalid"


Hi All,

The error says "Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: The UserCodeToken is invalid". While this error message is very descriptive, it wasn't very helpful in determining a solution. No events in the error
 Update: Sandboxed solutions not working, try restarting the service in powershell "Restart-Service SPUsercodeV4"

Monday, January 7, 2013

Populate Drop Down Lists in Client Object Model

Hi All,

SharePoint 2010 provided two major custom web part enhancements: Visual Web Parts and Client Side Object Model (COM) using JavaScript. We can populate a dropdown items from a sharepoint list.

First populate a list for example : InterviewerList

In visual webpart add following tag in .ascx file inside a DIV tag :

<select id="ddlInterviewerName">

</select>

Then jump to your .js file and write following code :



jQuery(document).ready(function () {

    ExecuteOrDelayUntilScriptLoaded(function () {
        obj = new ScheduleInterviewClass();
        obj.LoadObjects();
    }, "sp.js");
});


function ScheduleInterviewClass() {

    this.LoadObjects = LoadObjects;

    var siteObjects = {
        ctx: null,
        web: null,
        url: null,
        InterviewerList: null,
        InterviewerListItems: null
    };

    
    function LoadObjects() {
        siteObjects.ctx = SP.ClientContext.get_current();
        siteObjects.web = siteObjects.ctx.get_web();
        siteObjects.ctx.load(siteObjects.web);
        siteObjects.ctx.executeQueryAsync(Function.createDelegate(this, LoadObjectsOnSuccess), Function.createDelegate(this, LoadObjectsOnFailure));
    }

    function LoadObjectsOnSuccess() {

        siteObjects.InterviewerList = siteObjects.web.get_lists().getByTitle("InterviewerList");      
        var query = new SP.CamlQuery();
        query.set_viewXml();

        siteObjects.InterviewerListItems = siteObjects.InterviewerList.getItems(query);

        siteObjects.ctx.load(siteObjects.InterviewerListItems);
        siteObjects.ctx.executeQueryAsync(Function.createDelegate(null, RenderHtmlOnSuccess), Function.createDelegate(null, RenderHtmlOnFailure));
    }

    function LoadObjectsOnFailure() {
        alert("Objects Not Loaded Properly. Try again");
    }

    function RenderHtmlOnSuccess() {
        var ddlInterviewer = this.document.getElementById("ddlInterviewerName");
        ddlInterviewer.options.length = 0;
        var enumerator = siteObjects.InterviewerListItems.getEnumerator();

        while (enumerator.moveNext()) {
            var currentItem = enumerator.get_current();
            ddlInterviewer.options[ddlInterviewer.options.length] = new Option(currentItem.get_item("InterviewerName").get_lookupValue(), currentItem.get_item("ID"));                    
        }
    }


    function RenderHtmlOnFailure(sender, args) {
        alert(args.get_message());
        alert("Not able to render HTML");
    }



}