Friday, May 31, 2013

Get and Set User in Client People Picker using Javascript Client Object Model

Hi Readers,

There is a unique scenario where I have to pick user from a Custom People Picker on a Custom Form and then Push that User to a Client People Picker of a List Item using Javascript Client Object Model.

InOrder to achieve this functionality, I first tried to fetch the User from the Custom People Picker on the Form using JQuery,

 var displayName = $("span.ms-entity-resolved div:first-child").attr("displaytext");

Problem is I do not get the ID of this User normally. So inorder to get the 'Id' of this User I searched this User into UserInformation List and then picked the ID of this User.

 function AddItems(displayName) {

        var userInfoList = siteObjects.web.get_siteUserInfoList();
        var query = new SP.CamlQuery();
        query.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + displayName + "</Value></Eq></Where></Query></View>");
        siteObjects.UserCollListItem = userInfoList.getItems(query);
        siteObjects.ctx.load(siteObjects.UserCollListItem);
        siteObjects.ctx.executeQueryAsync(Function.createDelegate(null, AddItemsSuccess), Function.createDelegate(null, AddItemsFailure));
    }

Then I fetched the List Item ID :  userID = currentItem.get_item("ID");

Once I got the User ID , I can easily convert this String Type User into User Type using below code :

  var userFV = new SP.FieldUserValue();
  userFV.set_lookupId(userID);

and can easily set the People Picker List Item now

siteObjects.UserCourselistItem.set_item('UserName', userFV);

This is something very unique requirement and can be helpful for many.


How to Ensure User using JavaScript Client Object Model

Hi Readers,

In Server Object Model, web.EnsureUser(loginName) checks whether the user is there in the sharepoint site and if not present , it automatically adds that user into the site.

Similarly using Client Object Model, Microsoft has introduced in same fashion using ECMA Client Object Model we can achieve same functionality.

In microsoft link below you might get to see this approach but if you try to use the same exact way it might not turn fruitful to you.
http://msdn.microsoft.com/en-us/library/ff408786(v=office.14).aspx

The reason why it is not working for you is only because you need to 'esureuser' on correct 'web' context.
i.e.  Try to initiate separate context for this command and then asyc the load objects.

 function EnsureUser(loginName) {
        var context = SP.ClientContext.get_current();
        siteObjects.currentUser = context.get_web().ensureUser(loginName);
       
        context.load(siteObjects.currentUser);
        context.executeQueryAsync(Function.createDelegate(null, ensureUserSucess), Function.createDelegate(null, ensureUserFailure));
    }

I hope this will be helpful

How to get People Picker entry using JavaScript Client Object Model

Hi ,

To fetch People picker value from People Editor Control, JQuery comes to rescue when we talk in terms of Javascript Client Object Model.

Approach 1 :
var loginName = $("span.ms-entity-resolved").attr("title"); // Returns the Login Name eg. ind\ali.yasir
var displayName = $("span.ms-entity-resolved div:first-child").attr("displaytext"); Returns Display Name as 'Ali Yasir'

Approach 2:
var loginName = $("textarea[title='People Picker']").val();
var displayName = $("div[title='People Picker']").text();

Hope this will help !!

Sunday, May 26, 2013

What is OAuth ???

Hi All,

I came across a nice post on OAuth so couldn’t stop myself sharing this with you all.

Here is a long description which needs patience to read
J , Hope you will like this :

Before I go straight to the definition of OAUTH and its elaboration, let’s talk about few things we already know to set the context. Also, my discussion on OAuth below is very generic and is not specific to SharePoint now. Once we are clear of OAuth concepts, we will see on SharePoint OAuth implementation in another upcoming post.
Apps: We all know what Apps are by now. The word App is so common now a days that I hope to see the nursery books replacingA for Apple  with A for Apps ;-)  Well, at least for me A is for Apps.
Service: We all understand the idea of Service. A Service can be a Web Service or API that is consumed by client applications
Service consumer : Any application that consumes a service. Now tell me what’s is the most common breed of application now-a-days that consume the Services?….guess… APPs! Yes, Apps are the most common Service Consumers now-a-days.
Service Provider: It’s the one who hosts the service and where the service runs. The service generally requires authentication so that only trusted consumers can access the restricted functionality or data offered by the service.
Now,  imagine as a developer, you have developed an enterprise application that offer users to play some interesting games on their Mobile devices. For that, you created a Windows 8 or iOS App (or any App) whose main function is to entertain user via some puzzle games on his mobile device.
Now, a new requirement is to allow the user to share the score on his Facebook timeline via your App.
               How can you make your App share the information on Facebook on behalf of User?
Isn’t it a most common and necessary requirement now-a-days? It is.
You will need to access the Service provided by Facebook (Service Provider) and authenticate your App to post on behalf of the User. An obvious solution is to ask User to provide his Facebook credentials and store it securely with you (in your DB\config or whatever). Now, whenever the user wants to share his score, your App will use the stored credentials and post on the Facebook wall on behalf of user.
With this (bad) solution, below uncomfortable questions arise around Security, Maintenance, and User Experience.
1. Security: Is it good to ask User for his Facebook credentials and store them with your application?
Although a user may enjoy playing with your App but he will most likely hesitate to provide you what you are asking. Of course, he cannot simply trust you!
2. Maintenance: What if you want to provide the same functionality with other social platforms like Twitter, LinkedIn or Yammer? Also, it will be difficult to maintain the user credentials for all the platforms you have integrated and also keep them in sync in case the User updates his account at Facebook, Twitter, and Yammer etc.
3. User Experience: If your App makes a User feel insecure about his social accounts, he will simply abandon your App. How can you prevent it? One solution is that instead of storing credentials, you can also present a login page when he can supply credentials. However, if your App connects with many Service Providers (Facebook, Twitter, LinkedIn, Yammer and many more upcoming) and you keep on asking the credentials every time, the user will not feel your App is really integrated . Isn’t it?
The solution to all above questions is OAUTH - an open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.
OAUTH
OAuth is a standard way for Service providers and Consumers(Apps for example) to handle authentication. Also, the OAuth authorization framework enables a third-party application to obtain limited access to a service hosted by Service provider. By using OAuth, you can allow the user to access a service (Facebook wall for example) stored at one site(Service Provider) with another application without having to store or manage credentials at the Application side.
There are 3 main Actors in an OAuth transaction: the User, the Service Consumer ( which is generally an APP), and the Service Provider.  This gang of three are often said to form the OAuth Love Triangle.
  

Now, assuming that your Game APP implemented OAuth for FaceBook, it can initiate authentication using OAuth.
Below are the steps(and the technical conversation) that will occur at high level  among all parties:
1.  A user wants Service Consumer (App) to access his protected resource lying with Service Provider (Facebook) :
User: “Hey App, I enjoyed the game but now I would like you to be able to share my game score on my Facebook timeline.”
Game App: “No problem! Let me ask for permission from Facebook. ”
2.  The service consumer asks for request token from service provider.
Game App: “My user wants me to post to his wall. Please share a request token.”
Facebook: “Your request is answered. Take the token and associated secret.”
Using the secret,  the service provider is able to verify the future requests by consumer (if its coming from the valid Service Consumer).
3.  The user is redirected to the service provider where user approve the service consumer to act on his behalf.
Game App: “Hey user,  I’m redirecting you to Facebook so you can approve me for the actions you want. Take the token with you which I got  from Service Provider(Facebook).”
User: “Ok”
4.   The user sees a form presented by the Service provider which lists all the actions the Service Consumer can take on user’s behalf. If user thinks its all OK, he approves.
Facebook: “Welcome User, do you want to authorize the Game App for all the A, B, and C actions?”
 User: “Yes, I approve”
Facebook: “OK, the request token is approved for the Game App”
5.   The service consumer obtains an access token in lieu of request token from service provider
Game App: “Facebook, Can you provide an access token for this approved request token?”
Facebook: “Sure. Take the access token and secret.”
6.  The service consumer preserve the access token and secret information for later use.This information can be saved along with user account with service consumer.
Game App : Hey User, now you can share the score on your wall as long as you keep me authorized with Facebook.
User: Great! But please note I will revoke your permission on my account with Facebook anytime I wish.
7.   The service consumer accesses the protected resource (of user) on behalf of user.
 Game App: “My user wants to share score on his Facebook wall.  Here is the access token for the action”
 Facebook: “Your access token looks valid. Your request can be carried on!”

OAuth is adopted by many Service Providers like Facebook, Twitter,Google, Yahoo and all the Consumers that consume the service from them.
The initial version of OAuth is 1.0 which is  still being used by some software companies. The second and latest version , OAuth 2.0, is created to simplify development while still providing app authentication and specific authorization flows for web apps, desktop applications, and mobile devices. For OAuth history and deep details, you can go to oauth.net and Wikipedia .


Sunday, April 14, 2013

Setting Up Environment Configuration of Windows Phone 8 development

Hi Readers,

A very common and simple blog today.
"Setting Up Environment Configuration of Windows Phone 8 development"


Your first task when it comes to Windows Phone development is getting your development environment up and running. It’s a three step process:
Install Windows 8
  • Windows 8 Pro edition or greater is required
  • Your machine must have a processor that supports Second Level Address Translation (SLAT)
Install Visual Studio Express 2012 for Windows Phone
  1. Web Installer – this is a small initial download that will download the necessary components during the installation process. Download at http://bit.ly/YSPmrh.
  1. Disk Image (iso) – This is the full installer, no additional downloads are required. Download athttp://bit.ly/Tmb6rX.
Optional: Join the Windows Phone Dev Center

You can’t create Windows Phone apps on anything but a 64 bit version of Windows 8. There are two additional requirements for running the Windows Phone 8 emulator:
What this means is that you can’t run a Windows Phone 8 development inside of a virtual machine. This is due to the Hyper-V technology used in the Windows Phone emulator.
For installing Windows 8 you have several options. If you’re running a Windows 7 machine, you can either upgrade your existing install, create a separate partition for you Windows 8 install, or create a bootable vhd with Windows 8 (this is not the same as running inside of a virtual machine).

Download and install Visual Studio Express 2012 for Windows Phone from http://aka.ms/getvs12now. Visual Studio is the IDE, similar to Eclipse, that you’ll use for creating Windows Phone applications. Please note, there are a five Visual Studio Express products available. Make sure you download and install the one specifically for Windows Phone.
There are two options for installation, a web installer and a disk image. A description of each is below, choose the one that works best for you:
If you already have a different edition of Visual Studio Express installed on your machine don’t worry, Visual Studio Express 2012 for Windows Phone will install just fine with it.
After you install Visual Studio you can try it free for up 30 days. After 30 days you must register to obtain a free product key for ongoing use. Just remember, it’s free as long as you register. You can register athttp://bit.ly/URM0I8.

This step is not required to start developing Windows Phone applications. However, if you want to test your apps on Windows Phone hardware and submit your apps to the Windows Phone Store, you must register for a Windows Phone Dev Center account. You can learn more about the Windows Phone Dev Center and register at http://bit.ly/StpJhE.
That’s it! You’re good to go. In the next lesson you’ll learn how to create your first Windows Phone 8 App. 

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



}