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");
    }



}


Sunday, January 6, 2013

How To Add Custom Web Part Properties To Visual Web Part In SharePoint 2010


Hey Folks,
Let’s see how we can add custom web part properties to a visual web part in SharePoint 2010.
Open Visual Studio 2010 -> File -> New -> Project -> Visual C# -> SharePoint -> 2010 and select Visual Web Part project template as below:
In SharePoint Customization Wizard, validate the SharePoint 2010 site URL as below:
Once Visual Studio 2010 open ups, it will look like below:
Open VisualWebPart1.cs file and add below code:

namespace AddCustomProperty.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @”~/_CONTROLTEMPLATES/AddCustomProperty/VisualWebPart1/VisualWebPart1UserControl.ascx”;
private string _Name;
[WebBrowsable(true), WebDisplayName("Name"), WebDescription("My Name"),
Personalizable(PersonalizationScope.Shared), Category("Custom Property"),
System.ComponentModel.DefaultValue("")]
public string Name
{
get { return _Name; }
set { _Name = value; }
}
protected override void CreateChildControls()
{
VisualWebPart1UserControl control = (VisualWebPart1UserControl)Page.LoadControl(_ascxPath);
control.Name = Name;
Controls.Add(control);
}
}
}

It should look like below:
Open VisualWebPart1UserControl.ascx file and add below code:
It should look like below:
Open VisualWebPart1UserControl.ascx.cs file and add below code:
namespace AddCustomProperty.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
public string Name { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
NameLiteral.Text = "Your Name is : " + this.Name;
}
}
}
It should look like below:
Deploy The Project:
Final Look:
Thanks & Have Fun!! :)

What is an App in SharePoint 2013


App is similar to a web part. One main key difference is everything is at the client side and not on the server side when you write a code developing an app which is called client web part.

In SharePoint 2013 Lists and Libraries are now termed as apps.

SharePoint now has its own app store where we get some free apps and some paid apps which can be installed and then can be used inside SharePoint.

There are three hosting options when you create app for SharePoint.

1) SharePoint hosted - On Premises.
2) Externally hosted
3) SharePoint Online - Sandbox solutions can be created. (deprecated now in SharePoint 2013) or new apps web part (client web part) can be used.

Certain important points about an app are :
  •       App cannot have any server side code.
  •      Apps  get created in a special “app web” on a special URL which is isolated from the original SharePoint web. Each app is a part of dedicated site collection.
  •      App does not have permission to talk to the parent site or site collection
  •     App cannot talk to the host site. ( a site in which app is displayed)
  •       Apps can be created using Visual Studio 2012     or using "Napa" Office 365 Development Tools
So SharePoint 2013 apps do not live in SharePoint rather they execute within the browser client or in a non-SharePoint server such as IIS or Windows Azure.

Apps can only be added by users with Full Control permission to the site. As mentioned earlier Apps can be installed from the centralized app store from on premises SharePoint or from public app store.

Apps can also be opened as a full browser screen or can also be a part of page. When we want app as a part of page we can use app part just like a web part to display that app in the app part. App part will display content of that app part in Iframe html element.

Regardless of how you authenticate your app with SharePoint, you need to have user consent to perform actions. You declare the required permissions in the app manifest file while developing, and the user is asked to grant or deny those permissions to the app during installation.

You can connect your app with just about any internal or public web services, take advantage of the new OAuth 2.0 support in SharePoint, and use the Representational State Transfer (REST) and client APIs (JavaScript and .NET) to integrate and connect your app with SharePoint.

There is a list of available apps that can be downloaded (some free / some paid versions) from Microsoft market place for SharePoint 2013.