中国平安陆金所邀您来投资

How to Pass Parameters to Success method in executeQueryAsync SharePoint

Summary :P assing Parameters to Success method in executeQueryAsync SharePoint, Passing Parameters and Returning Values from Success method in executeQueryAsync + Client Object Model + SharePoint 2010\SharePoint 2013,How to Pass Parameters and Retrieve Values from Success method in executeQueryAsync() SharePoint

This is quick tip about how to Pass Parameters and Retrieve Values from Success method in executeQueryAsync()

To Pass a Parameter in Success method use the following Syntax –

Before passing Parameters:

context.executeQueryAsync(Function.createDelegate(this,this.success)),

Function.createDelegate(this, this.failed));

After passing Parameters:

context.executeQueryAsync(

Function.createDelegate(this,function(){success(_parameter);}),

Function.createDelegate(this, this.failed));

function success(_parameter)
{
alert("In Success Method! " + _parameter);
}

To Retrieve Values from Success method use the following Syntax –

context.executeQueryAsync(

Function.createDelegate(this, function(){ _returnParam = success(_parameter);}),

Function.createDelegate (this, this.failed));

alert(_returnParam);





How to Batch Update List Items in SharePoint 2013 based on a CAML query (using Web Services + AJAX + JQuery)

Example of Batch Updating List Items in SharePoint 2013 based on a query using Client Object Model and Jquery.

In this example we will look at a Script where we make an Ajax call to GetlistItems web service and pass a CAML query to retrieve all Items with "Project Cost" greater than $1000 (as seen in the Before Projects list screen below). Once the Items are Retrieved (based on a "Project Cost" CAML query), we Create a Update Batch of these Items and pass it to the UpdateItems method.The UpdateItems method finally updates the required Items in the Projects List with the appropriate Status (see the After Image below).

Final Result – After running the Batch update script, all the Items with "Project Cost" > $1000 will have an updated Status of "Transferred" in the Custom Project List that we have Created.

Before :

1

After :

2

To begin,

1. Download the Script  and add it to Script Editor or Content Editor WebPart on your Lists Page. 2. Edit the listname, Column names and Value for the CAML query and update batch (in AddTobatch() method). 3. Once done Save and Click the link "Update Status for Items with Project Cost >$1000″ to update the Items that are retrieved from the CAML query. 4. Once updated a Confirmation message – "Update Complete" is displayed.

3





Folders and unsupported file types can’t be uploaded in SharePoint 2013

This is a quick tip about adding Folders or Items to a document Library using the new Drag and Drop feature.

If you are trying to Drag-n-Drop folders into a documnet library, you might run into the following error -

"Folders and Unsupported file types can't be uploaded"

1

The error simply occurs because with the new Drag and Drop feature you cannot add or Upload Folders,Items and Document sets into the library.This is a major limitation for Companies who love to add folders instead of individual Files in the library.

If this what your requirement is, there are few alternatives available for you.

1. Use the conventional Windows Explorer View - To Open Windows Explorer click on Upload Document button as shown in picture below

2

Next in the Add Documents popup click on "Upload Files using windows Explorer Instead" to Open the Windows explorer view where you can Drag and Drop folders.

3

2. Map the Document Library as Network Drive – You can Map any document library as a network drive and then drag and drop folders to it.

4

When you Map a document Library as a Network drive, you might see an error because of the missing "Desktop Experience" feature in Windows Server 2012. Take a look at this post where we resolve this issue and Map Master Page gallery as a Network drive.

 

3. Using SYNC Option - In SharePoint 2013, you can make any Document Library SYNC to your Local Folder (Including the SkyDrive PRO Library) to work with documents Offline. Once the Library is SYNCed users can Open, Edit and Add Files and Folders to the SYNCed Library Folder that gets created on your Local. These additions can be Synced back to the Library either everytime when you connect to SharePoint or On-Demand with "Sync now". Take a Look at the steps at Work with Documents Offline in SharePoint 2013





How to: SharePoint 2010 User Name Displaying Incorrectly in Option Menu

  I found an interesting bug that can occur when SharePoint 2010 syncs with AD and the user name is entered incorrectly in AD then fixed later. The profile sync will fix the name in most places except one of the most important and highly visible locations, the Option Menu. The Option Menu in SharePoint 2010 is the top right of every SharePoint 2010 page on a SharePoint site, it displays your user name, and this bug makes it so it's incorrect until you manually update it.

This isn't a very common problem but it occurs when a user it put into AD incorrectly, then SharePoint does its AD sync and the name is stored in the User Profile database with the wrong spelling. Later the name is updated in AD and SharePoint will sync the correct name. The problem is that for some reason the Option Menu display won't update to the correct spelling. That is unless you force it to, the following steps explain how to force the update and correct the issue.

1. Open the SharePoint 2010 server that hosts Central Admin

2. Click Start

3. Click All Programs

4. Click SharePoint 2010 Products

5. Click SharePoint 2010 Management Shell (run as administrator)

6. Type Set-SPUser -Identity 'Domain\UserName' -Web http://SharePointServer -SyncFromAD

7. Hit Enter (the script will run and once complete will prompt you that it completed)

Once the command completes you should be able to go back to any SharePoint page and the user name should now display properly. If it doesn't this could be a simple browser cache issue, so depending on your browser of choice clear cookies and cache and re-open SharePoint. The issue should now be resolved.

Well hopefully this fixed your issue with the SharePoint 2010 user name displaying incorrectly in the option menu. I know this can be a frustrating issue for users; they of course want their name displayer properly.

If you are unable to use the Exchange AD synch option described earlier, sign into SharePoint as as a different user and delete the wrong username. Open the option menu next to the username in the SharePoint page and choose "Sign in as a Different User" and sign in with a different user credential. Go back to the options menu and choose the "My Settings" option; the wrong user name should still be displayed on the sharepoint site. When the settings page open, click the "Edit Item" option. Within the edit window, choose the option to delete the username with the wrong information. Logout of the sharepoint page and then log back in with the right user credentials. This process should update to the correct user data on the sharepoint page.
 
 
 




Lync State display in a custom webpart for SharePoint 2010

I recently spent a while trying to integrate the Lync state into a custom web part and found it a little tricky so wanted to share my learning's. With SharePoint 2010's new social capabilities, I see this integration as being a must-have for any webpart or other custom interface that refers to people.

How does SharePoint do it?

Whenever a person's name is mentioned in the standard SharePoint UI, if the user has Office Communicator installed, the name will be shown with the Office Communicator 'pawn'. The pawn shows the user's status and gives them access to the pop-up menu to see more details.

Depending on which version of Office the user has installed, the experience will vary, however it will be the same experience as seen in Outlook. In Office 2010 it is a square icon with a richer drop-menu, in 2007 it is round.

SPPresencePawn

In addition to the pawn, the user's name will be a hyperlink to their profile page. This will vary depending on whether the user is in the main 'User Profile Service Application' (or 'profile database' for old-school terminology) or not. If the user does have a profile then the hyperlink will redirect to the user's main profile page under My Site. If the user does not have a profile, the hyperlink will redirect to the SharePoint Foundation 'User Information' page. All users in a site have a 'User Information' page, if they also have a User Profile the settings from the profile are synchronised down to the User Information page on a scheduled basis (by a timer job).

The key piece of information to make the presence work is the user's SIP Address which is basically their IM address (This is not always the same as email address). When a users is either added to a site in SharePoint or has their profile imported, the SIP Address will be drawn from Active Directory which is where OCS stores it and placed into the SIP address field in either the user's profile which will in turn synchronise down to the site's local 'User Information' page.

How does the pawn work in terms of HTML?

The pawn is basically an IMG element which has "IMNRC('[user's SIP Address]')" for the onload function. This will user client-side script that is part of Office to load the presence pawn on the page.

The hyperlink on the user's name is just a simple A element which redirects to "/_layouts/userdisp.aspx?ID=[User's local user information list item ID]". This userdisp.aspx page will then redirect to the user's main profile page if they have a profile, otherwise it will display the basic information that the user information list item stores.

How to get the SIP Address?

Hopefully you'll have spotted by now that the presence pawn relies on the user's SIP Address. To get the SIP address you need to get the user's User Information list item from the local site's (SPWeb to be precise) SiteUserInfoList which is basically a hidden SPList that is in every web.

There is a handy property to get you to this list called 'SPWeb.SiteUserInfoList'. This will give you an SPList object which represents the User Information list. From here you just need to find the item that represents the user you wish to display. The best way to do this is via their ID (the ID of the list item) by calling SPWeb.SiteUserInfoList.GetItemById([int User's ID]), however you can also use a variety of other methods which use SPQuery or match a specific field to a value.

In most scenarios, you may be getting the user information from a SPFieldUserValueCollection which is basically the field type that is used for 'Person' fields. If this is the case you can use SPFieldUserValue.LookupId to get the ID of the user's User Information list item.

Putting it all together

This code sample is a method that accepts an SPFieldUserValueCollection and SPSite as inputs and returns back the HTML for displaying each entry in the SPFieldUserValueCollection with the presence pawn and link to their profile. This will be presented exactly as SharePoint presents it by default. This could be extended to use ALT tags in the IMG and A elements.

I then simply add the HTML to an HtmlWriter or in my case a TableCell.Text property to display it on screen.

I've take a few extra steps here by adding ID and alt tags and trying to make the code readable, but I'm sure you get the idea:

public string GetPresenceHTMLFromUVC(SPSite thisSite, SPFieldUserValueCollection uvc)
{
StringBuilder html = new StringBuilder("");
using (SPWeb thisWeb = thisSite.RootWeb)
{
foreach (SPFieldUserValue uv in uvc)
{
string sipAddress = "";
//Get the sip address if it exists
SPListItem user = thisWeb.SiteUserInfoList.GetItemById(uv.LookupId);
if (user["SipAddress"] != null)
{
sipAddress = user["SipAddress"].ToString();
}
//construct the html for this user and add to overall html
html.Append(String.Concat(
"<div id\"PresenceLink"
, sipAddress
, "\">"
, "<img border=\"0\" height=\"12\" src=\"/_layouts/images/imnhdr.gif\" onload=\"IMNRC('"
, sipAddress
, "')\" ShowOfflinePawn=\"1\" style=\"padding-right: 3px;\" id=\"PresencePawn"
, sipAddress
, "\" alt=\"presence pawn for "
, sipAddress
, "\"/>"
, "<a href=\""
, thisWeb.Url
, "/_layouts/userdisp.aspx?ID="
, uv.LookupId
, "\" id=\"ProfileLink"
, sipAddress
, "\">"
, uv.User.Name
, "</a></div>"
));
}
}
return html.ToString();
}






Sort Folders (Custom Order) in SharePoint Document Library

Sort Folders (Custom Order) in SharePoint Document Library

One of my friend recently asked me this question about sorting the folders (not in alphabetical order) in a document library. The sort order has to be custom and user should be able to specify the order in which folders should appear. Example sort order

 

Top

Middle

Bottom

 

 

In order to implement this you can create a new folder content type and add an order column to this content type. You do need to have the appropriate rights to do so.

 

The steps would be as follows.

·         Go to Site Actions

·         Go to Site Settings

·         Go to Site Content Types

·         Click Create New

·         Give it a name such as Folder Order

·         Select Parent Content Type from as of Folder Content Types

·         Select Folder as the Parent Content Type

·         You can create a new group or leave it in custom content types

·         Click OK

·         At the content type settings click Add from new site column

·         Create a site column called Item Order or something similar, select the type as Number

·         Click OK

·         Go to the list where you want the folders to be ordered

·         Go to the list settings

·         Go to Advanced Settings

·         Select allow management of content types

·         Select No for display new folder command on the new menu

·         Click OK

·         You should now see an area called content types, leave the document as is

·         Click Add from existing site content types

·         Select the Folder Order (or whatever you named it)

·         Click OK







Create a Custom Action Specific to a List for SharePoint 2013/SharePoint 2010

You can create a custom action that is based on the list type by editing the elements.xml file that is associated with the custom feature. However, you can also create a custom action that is specific to a list rather than a list type. To do this, create a custom feature for the content type and then make a minor modification in the elements.xml file. The following steps demonstrate how to do this.

Create a custom content type

  1. Create a custom content type by inheriting from any one of the standard Windows SharePoint Services content types.

  2. Ensure that the identifier (ID) of your custom content type has the ID of the base content type (from which it inherits) as its ID prefix.

    The following example XML code shows the elements.xml file for a custom content type that was inherited from the standard Windows SharePoint Services content type, in this case, the List content type.
    <?xml version="1.0" encoding="utf-8" ?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <ContentType ID="0x01AB"
         Name="MyCustomContentType"
         Group="MyCustomContentTypeGroup"
         Description="Customized Content Type"
         Version="0">
       <FieldRefs>
        <FieldRef ID="{8c06beca-0777-48f7-91c7-6da68bc07b69}"
         Name="Created"
         DisplayName="Field1" />
        <FieldRef ID="{1df5e554-ec7e-46a6-901d-d85a3881cb18}"
         Name="Author"
         DisplayName="Field2" />
       </FieldRefs>
      </ContentType>
    </Elements>

    Create your custom action

    • In the Elements.xml file, create your custom action, as illustrated in the example following.
      <?xml version="1.0" encoding="utf-8" ?>
      <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <!-- Document Library Toolbar New Menu Dropdown -->
         <CustomAction Id="UserInterfaceLightUp.DocLibNewToolbar"
          RegistrationType="ContentType"
          RegistrationId="0x01AB"
          Rights="ManagePermissions"
          Location="EditControlBlock"
          Sequence="1000"
          Title="MY DOCLIB NEW MENU TOOLBAR BUTTON">
         <UrlAction Url="/_layouts/LightupHello.aspx?NewMenu"/>
        </CustomAction>
      </Elements>

      Create the list

      1. Create the list where you want to render the custom action.

      2. Change the default content type of the new list to the custom content type that you created above.

      3. Delete the Item content type from the list. At this point, the custom action will be rendered in the Edit Control Block menu of the specified list.





Enable The SharePoint Learning Kit Feature On All Sites In A Site Collection

Sometimes you want to be able to assign work from anywhere within your site collection. For the E-Learning Actions custom action to be added to a document library you need to enable the SharePoint Learning Kit feature on that site, so to enable it everywhere you need to enable the feature on all sites.

To do this in SharePoint 2010 all you need is a simple PowerShell script which iterates through all the sites and then enables the feature if it is not already enabled. The following script will do that for you. You will need to change the url value to reference your site collection, save in a .ps1 file and then run from the SharePoint 2010 Management Shell.

$url = "http://urlOfSiteCollection"  $site = Get-SPSite $url  $featureId = "00057002-c978-11da-ba52-00042350e42e"  $featureName = "SharePointLearningKit"  $site.Urlforeach ($web in $site.AllWebs)  {      # Output the site url for debugging purposes      $web.Url      # Only enable if not already enabled      if (!$web.Features[$featureId])      {          # Output debugging message          "Enabling..."          Enable-SPFeature $featureName -Url $web.Url      }  }

You can also use this for other features, just by replacing the feature id and name with the appropriate values. To find these look in

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES

The feature name is the name of the folder in here and the id is in the feature.xml file in that folder.



Using PowerShell to Bulk Upload Files to SharePoint 2013/SharePoint 2010

While building a school's Learning Gateway I needed to bulk upload all their student images into a picture library so that the My Children web part could display them. Since there were several hundred of them I wrote a little PowerShell script to perform this.

$siteUrl = "http://sharepoint/schools/test" $listName = "Students Picture Library"  [system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint") $site = New-Object Microsoft.SharePoint.SPSite($siteUrl) $web = $site.OpenWeb()$list = $web.Lists[$listName] $fileCollection = $list.RootFolder.Files  $files = get-childItem -Exclude *.ps1  foreach ($file in $files) {     $stream = $file.OpenRead()     $uploaded = $fileCollection.Add($file.Name, $stream, $TRUE)     "Uploaded " + $file.Name      if ($stream) {$stream.Dispose()} }  if ($web) {$web.Dispose()} if ($site) {$site.Dispose()}

In order to use this:

  1. Save as as .ps1 file in the same folder as the files to upload.
  2. Change the site url and name of the list at the beginning of the script to your values
  3. Make sure that only the files to upload and the ps1 file is in the folder
  4. Open PowerShell using Run As Administrator
  5. Navigate to the folder
  6. Run the .ps1 file

The script will then iterate through all files in the current folder and upload them to the given list, overwriting them if they already exist.