Showing posts with label SharePoint2007. Show all posts
Showing posts with label SharePoint2007. Show all posts

Access WCF Service with jQuery in SharePoint2010


 I described how to develop a custom WCF service. Today I’ll cover how you can invoke the SharePoint WCF Service from jQuery. In my last post I described to develop a SOAP web service but for using WCF service from jQuery I’m going to use REST web service. For the list of service types and factories supported in SharePoint you can visit the link in MSDN. You can download source code from the link given at the end of the post.

Prepare the service to call from jQuery

Consider developing a service as described in Create Custom WCF Service in SharePoint2010 with the following changes:
  • For  using json I’ve used REST service factory ‘Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory’ as shown below. You can use SOAP factory but you then need to parse data in different way.
    <%@ ServiceHost Language="C#" Debug="true"
        Service="AccessSPServiceFromJQuery.MyService, $SharePoint.Project.AssemblyFullName$"  
        CodeBehind="MyService.svc.cs"
        Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, 
    Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0,     Culture=neutral, 
    PublicKeyToken=71e9bce111e9429c" %>
    
  • Next you need to specify the return type to json in the service interface as shown below. I’ve specified both request and response type to json in WebInvoke attribute:

    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)]
        List<Product> SearchProduct(string productName);
     
     
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)]    bool Save(Product product);
    }
One thing to notice here is that you can’t access the service in browser with mex endpoint. For example if you service is http://myserver/myservice.svc, then the url http://myserver/myservice.svc/mex will not work for service created with MultipleBaseAddressWebServiceHostFactory.

Call Service with jQuery

The next step is to call the service with jQuery. The url of the service to be used in jQuery will be service url and method name. For example if you service url is‘/_vti_bin/AccessSPServiceFromJQuery/MyService.svc’ and the method name you want to invoke is ‘Search’ then the full url will be ‘/_vti_bin/AccessSPServiceFromJQuery/MyService.svc/Search’. As shown in the code below, you can invoke the service Search by passing the parameter in data field of ajax call of jquery
function getProductFromService(searchText) {
    try {
        $.ajax({
            type: "GET",
            url: '/_vti_bin/AccessSPServiceFromJQuery/MyService.svc/SearchProduct',
            contentType: "application/json; charset=utf-8",
            data: { "productName": searchText },
            dataType: 'json',
            success: function (msg) {
                WCFServiceGetSucceeded(msg);
            },
            error: WCFServiceGetFailed
        });
    }
    catch (e) {

        alert('error invoking service.get()' + e);
    }
}
function WCFServiceGetSucceeded(result) {
    alert('success');
}
function WCFServiceGetFailed(error) {
    alert('Service Failed.');
}

Download and use code

I’ve uploaded the code for this post in my skydrive. You can download the code from the link below. To use the code please ensure you have internet connection as I’ve used jqery from Microsoft CDN. The search functionality get all products matching name. You can try to search just by typing a single character. You can debug and test the code. In save I’ve just shown you can pass value from browser to service using POST method.

How to Iterate through All the webs in the site of SharePoint


Sometimes we need to process all webs in a site collection, as you want to do some quick fixes in the web. Few weeks back my manager asked me to do some fixes in the list items exists in all the webs in the site collection. There were about 30,000 webs in the site collection and I was looking for some kind of script that will be efficient. The usual way of looping through all webs might be using some recursive way, as shown below.
//Starting point
public void ProcessAllWeb(SPSite site)
{
    using (var web = site.RootWeb)
    {
        ProcessWebRecursive(web);
    }

}

//Recursive method
private static void ProcessWebRecursive(SPWeb web)
{
    //do some processing
    //web.Lists["listName"].ItemCount

    foreach (SPWeb subWeb in web.Webs)
    {
        using (subWeb)
        {
            ProcessWebRecursive(subWeb);            
        }
    }

}
Code Snippet 1: Recursive way of processing all webs in the site collection (Not optimized)
In the recursive way of processing all webs, there will be more than one SPWeb instance alive in memory. In the above code snippet, when the method ProcessAllWeb is invoked it’ll call the recursive method ProcessWebRecursive. The recursive method will keep calling the subwebs while keeping the parent web alive.

While I was writing the code, I was wonder if there’s any way of processing only one web non-recursively. So my intention was to open only one web in memory at once. And then I found it. You can get all web Url(including all subwebs at all level) using SPSite.AllWebs.Names. The following code snippet shows the efficient way of processing all webs in the site collection:
public void ProcessAllWeb(SPSite site)
{
    string[] allWebUrls = site.AllWebs.Names;
    foreach (string webUrl in allWebUrls)
    {
        using (SPWeb web = site.OpenWeb(webUrl))
        {
            //process web
        }
    }
}
Code Snippet 2: Process all webs one by one (Optimized for large number of webs)
Using the code snippet shown in figure 2, you just open one web at a time in memory for processing. The trick here is ‘SPSite.AllWebs.Names’ which will return all the (I mean it!) subwebs (including children and their children and so on) as a result. If you have thousands of webs under a site collection (and if it’s production), you should care about performance issue.

Custom add/edit/display form for list in SharePoint


Sometimes we don’t want to use SharePoint’s custom add/edit/display form. We want our own custom form when user will try to view, edit or add an item. I’ll show you today how easily we can do so.
For this post I’ll consider I’ll have a list with three fields: Product Code, ProductName and ProductDescription. I’ll show how we can create a list with these two fields with custom add/edit/display form. The list’s fields are described in the table below:
Field nameField TypeComments
Product CodeTextTitle field will be used instead of creating a new one
Produce NameText
Product DescriptionText
Table 1: Custom list template/Content Type’s fields

The first step of this approach is to create a content type with required fields associated with the content type. The noticeable point here is that In the content type declaration, we can define custom forms for add/edit/display.

Step 1: Create a content type for your list

To create content type right click on your project and click ‘add new item’ and then select content type as shown below:
image
Figure 1: Add content type

Next you will be prompted for the base content type as shown below: If you want to create a custom list, you can select Item as shown below:
image
Figure 2: ‘Item’ is the base content type for custom/generic list

Then you will have provided the content xml file. You need to modify the content type xml file as shown below. Please modify the Inherits=”False” from the content types.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!--Defined fields-->
  <Field ID="{30C3D21A-A7C9-410E-A896-82875475F697}" Name="ProductName"
         DisplayName="Product Name" Type="Text" Required="FALSE" >
  </Field>
  <Field ID="{9621763e-3494-4a86-a3eb-fd2593f1a1f1}" Name="ProductDescription"
         DisplayName="Product Description" Type="Text" >
  </Field>
  <!-- Parent ContentType: Item (0x01) -->
  <ContentType ID="0x0100c5e54b7f62ad451a92f9235d43ec9082"
               Name="ProductContentType"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="false"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" 
                DisplayName="Product Code" Sealed="TRUE"/>
      <FieldRef ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" Name="LinkTitle" 
                DisplayName="Product Code" Sealed="TRUE"/>
      <FieldRef ID="{BC91A437-52E7-49E1-8C4E-4698904B2B6D}" Name="LinkTitleNoMenu" 
                DisplayName="Product Code" Sealed="TRUE" />
      <FieldRef ID="{30C3D21A-A7C9-410E-A896-82875475F697}" Name="ProductName" 
                DisplayName="Product Name" Required="False" />
      <FieldRef ID="{9621763e-3494-4a86-a3eb-fd2593f1a1f1}" Name="ProductDescription" 
                DisplayName="Product Description" Required="False" />
    </FieldRefs>
    <XmlDocuments>
      <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
        <FormUrls xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
          <Display>_layouts/blogtest/Product.aspx?mode=display</Display>
          <Edit>_layouts/blogtest/Product.aspx?mode=edit</Edit>
          <New >_layouts/blogtest/Product.aspx?mode=new</New>
        </FormUrls>
      </XmlDocument>
    </XmlDocuments>
  </ContentType>
</Elements>
Figure 3: Content Type xml file with fields and add/edit/display form declared

Now let’s explain what’s in the xml shown in figure 3.
  • Firstly I’ve modified Inherits to false in ConentType tag.
  • I’ve defined two fields inside the <Elements> tag that I’ve used later in content types
  • Then used those fields in <FieldRefs> of <ContentType> tags. These fields will be available in Content type. I’ve also used three existing fields (for Title) from base Content Type (Item).
  • Finally I’ve defined New, Edit and Display form for these content types in <XmlDocuments> section.


Step 2: Create a list Template based on Content type

Now you have defined content types with three fields. Next step is to define a list template based on the content type. To do so click add new item from visual studio context menu and select “List Definition From Content Type” as shown below:
image
Figure 4: Create list definition from content type in ‘Create new Item’ dialog.

Next you will be prompted for available  content types in the project as shown below. Remember to uncheck the button ‘Add a list instance for this list definition’ for this demo now.
image
Figure 5: Create list definition from Content Type

Now you will find two files Elements.xml and Schema.xml files are added. Our full focus will be now on Schema.xml.

Modify the content in <Fields> tag:
Ensure Title fields with display name ‘product code’ exists as shown below:
<Field ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" DisplayName="Product Code" Sealed="TRUE" Type="Text" />
image
Figure 6: Add title field in the list template (if not exists)

Then find two fields LinkTitle and LinkTitleNoMenu. Then change their display name to ‘Product Code’ as shown below. These two fields are link to edit menu.
image
Figure 7: Rename the displayName for linkTitle and LinkTitleNoMenu field

Modify the content in <Views> tag
Open the views tag and add the fields you want to display in default view under <View> with Default value is true as shown below.
image
Figure 8: Define the fields to be shown in default view

 

 

Step 3: Create Custom add/edit/display form

Next step is to develop a custom application page to use for add/edit/display. As sown in figure 3, you can three different pages for add, edit and view. However for brevity I want to use a single page for all these three operations. You need to create an application page in appropriate location (in my case this is _layouts/blogtest folder). Rather than using three different files for add/edit/display, you can use a single page for all these three tasks as shown below:
<XmlDocuments>
  <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
    <FormUrls xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
      <Display>_layouts/blogtest/Product.aspx?mode=display</Display>
      <Edit>_layouts/blogtest/Product.aspx?mode=edit</Edit>
      <New >_layouts/blogtest/Product.aspx?mode=new</New>
    </FormUrls>
  </XmlDocument>
</XmlDocuments>
By passing different parameter to a single page we can identity the page’s mode (add, edit or view). Also SharePoint by default add the list and item id at the end of the page. So your page’s url will look like for new item:
_layouts/blogtest/Product.aspx?mode=new&List=LISTGUID&ID=ITEMID
So from the page (Product.aspx) you can identity the list id and item id from querystring.
I’m not showing details of the product.aspx page here.
You can download the full source code from this skydrive link.

How to use the project attached with this post?

  1. Download the code from here.
  2. Deploy the solution to a SharePoint site.
  3. Create a new list with “ProductListDefinition” template. This template will be installed in the site as you deploy the SharePoint solution.
  4. Now try to add/edit/view items in the list. You will find the custom form product.aspx is used for add/edit/view.

How to set PeopleEditor value using javascript in SharePoint

While developing SharePoint application, you may want to use PeopleEditor control or your own custom control derived from EntityEditorWithPicker. If you come across the problem with setting its value using Javascript, below is the code sample that may help.

<script type="text/javascript">

function SetPickerValue(pickerid, key, dispval)
{
    var xml = '<Entities Append="False" Error="" Separator=";" MaxHeight="3">';
    xml = xml + PreparePickerEntityXml(key, dispval);
    xml = xml + '</Entities>';

    EntityEditorCallback(xml, pickerid, true);
}

function PreparePickerEntityXml(key, dispval)
{
    return '<Entity Key="' + key + '" DisplayText="' + dispval + '" IsResolved="True" Description="' + key + '"><MultipleMatches /></Entity>';
}

</script>


The easiest way to set PeopleEditor’s value is to use the EntityEditorCallbak function. This function is provided with built-in SharePoint javascript functions (both WSS 3.0 and MOSS 2007). It is the same function that is used by the control to set its own value. The first two parameters of the function are important – the first one is XML containing entities definition and the second one is a client identifier of the control which value should be set. (The client identifier is the same which is available in the ClientID property on the server side).
The above code sample presents the SetPickerValue function. The function covers XML generation from a given key and display text, and calling of EntityEditorCallback function.

Example of SetPickerValue call:

SetPickerValue('ctl00_PlaceHolderMain_pplEdit', 'domain\\m.kapusta','Marcin Kapusta');

Generated XML (for the given call) is the following:

<Entities Append="False" Error="" Separator=";" MaxHeight="3">
  <Entity Key="domain\m.kapusta" DisplayText="Marcin Kapusta" IsResolved="True" Description="domain\m.kapusta">
    <MultipleMatches />
  </Entity>
</Entities>


Be careful when providing domain account name. Javascript treats \ (backslash) character as a special character. If you want to have it in the string, you have to use \\ instead. That’s why I had to provide ‘domain\\m.kapusta’ as a parameter to get domain\m.kapusta value in the XML.

If you want to set PeopleEditor value to have multiple entities, you can modify SetPickerValue function to generate multiple <Entity />nodes in the XML.

You can set IsResolved attribute to False to have unresolved entity in the control. When the entity is unresolved you are able to provide some suggestions (accessible in the popup menu) adding child nodes to the <MultipleMatches /> node. I don’t want to go into details about the multiple matches as it is the topic for another post.

How to Set Up the SharePoint 2010 User Profile Service Application to Synch AD Users –Part II

Now that we have our connection to AD configured and the user profile service application is up and running, we're ready to do our first import of users from AD. 
1. In order to perform the synchronization, you'll need to verify you have the following permissions:

• You must be a member of the Farm Administrators group on the computer that is running the SharePoint Central Administration Web site 

• The Farm Administrator account must be a Service Administrator for the User Profile Service that you are configuring. For more information about how to set service permissions, see Assign administration of a User Profile service application (SharePoint Server 2010).

• The account that you use to synchronize profile information with Active Directory Domain Services (AD DS) must have Replicate Directory Changes permissions on the AD DS domains from which you want to import data. If the NETBIOS name is different from the domain name, the account that is used must also have Replicate Directory Changes permissions on the cn=configuration container. For more information about how to configure Replicate Directory Changes in AD DS, see How to grant the "Replicating Directory Changes" permission for the Microsoft Metadirectory Services ADMA service account (http://go.microsoft.com/fwlink/?LinkId=47854). Create All Child Objects permission is needed to export properties, such as profile pictures, from SharePoint Server to AD DS.

2. On the Central Administration Web site, in the Application Management section, click Manage service applications.

3. On the Manage Service Applications page, click in the Title column of the User Profile Service Application row to select it. 

4. In the Operations group of the ribbon, click Manage.

5. On the Manage Profile Service page, in the Synchronization section, click Start Profile Synchronization.

6. On the Start Profile Synchronization page, select Start Incremental Synchronization to synch only user and group profile data that has changed or select Start Full Synchronization to synchronize all user profile data.


The Start Full Synchronization option is time and resource intensive. We do not recommend it unless absolutely required to reset data that is stored in user profiles or to do an initial synchronization of user profiles.

When using AD DS, you must run full synchronization any time a new profile property mapping is created.

7. Click OK.

After the Profile Synchronization job is finished, you can search for a known profile or for accounts that begin with a known domain name from the Manage User Profiles page.

Because the import uses MIIS/FIM you can also open the miisclient.exe application from C:\Program Files\Microsoft Office Servers\14.0\Synchronization Service\UIShell\miisclient.exe to verify that the sync was successful:

How to Set Up the SharePoint 2010 User Profile Service Application to Synch AD Users - Part I

As part of our demo environment, I've been working on our configuration for the user profile service application to importusers from our AD so we can start using MySite's , Profile Pages, Social Tagging, etc… Here are the steps I followed from Microsoft plus some of my own comments: 


The Environment & Requirements


• SharePoint 2010 Enterprise Beta server acting as Web and App.


• SQL 2008 SP1 CU2 (separate from SP2010 server)


• AD (domain functional level 2003)


• The account you use to connect to AD must have at least Replicate Directory Changes permissions on the AD DS domain(s) from which you wish to import data and on the cn=configuration container are needed for SharePoint Server 2010. For more information about how to configure Replicate Directory Changes in AD DS, see How to grant the "Replicating Directory Changes" permission for the Microsoft Metadirectory Services ADMA service account (http://go.microsoft.com/fwlink/?LinkId=47854). Create All Child Objects permission is needed to export properties, such as profile pictures, from SharePoint Server to AD DS.

For my lab environment, I'm ignoring profile pictures....for now.

•The farm is running either the Standard or Enterprise version of SharePoint Server 2010 and you have run the farm configuration wizard. Profile Synchronization does not work on a stand-alone installation for SharePoint Server 2010 Beta.


• An instance of the User Profile Service application exists and is started. For more information, see Create, edit, or delete a User Profile service application (SharePoint Server 2010).


• If you are using Microsoft SQL Server 2008, Microsoft SQL Server 2008 with Service Pack 1 (SP1) with Cumulative Update 2 (CU2) (http://go.microsoft.com/fwlink/?LinkId=165962) is required.


• The WCF hotfix (KB976462) for Windows Server 2008 R2 is installed.


• You must be a member of the Farm Administrators group on the computer that is running the SharePoint Central Administration Web site.


• The Farm Administrator account, which is created during the SharePoint farm setup, must also be a Local Administrator on the server where the User Profile Synchronization service is deployed


• The Farm Administrator account must be a Service Administrator for the User Profile Service that you are configuring. For more information about how to set service permissions, see Assign administration of a User Profile service application (SharePoint Server 2010).


• The Service Administrator account can log on locally to the server where Profile Synchronization will be deployed.


• If you are using a Windows Server 2003 AD DS forest, the Service Administrator account must be a member of the Pre-Windows 2000 Compatible Access group for the domain with which you are synchronizing. For more information about adding accounts to the Pre-Windows 2000 Compatible Access group, see Some applications and APIs require access to authorization information on account objects (http://go.microsoft.com/fwlink/?LinkId=179420).


Start the Required Services


1. Start the User Profile Synchronization service through Central Administration


• Confirm that the user account performing this procedure is a member of the Farm Administrators SharePoint group. 


• On the SharePoint Central Administration Web site, click System Settings, and then on the System Settings page, in the Servers section, click Manage services on server.


• To change the server on which you want to start or stop the service, on the Server menu, click Change Server, and then click the server name that you want. 


• By default, only configurable services are displayed. To view all services, on the View menu, click All.


• To start the service, click Start in the Action column of the relevant service.


• Click OK to start or stop the service. Be sure to enter the account info for the SharePoint farm admin account.






Wait about 10 minutes and verify the both ForeFront Identity Management services start up properly in services.msc. Once they start, do an IISRESET.




Create a Profile Synchronization Connection


1. Verify that you have the following administrative credentials:


• You must be a member of the Farm Administrators group on the computer that is running the SharePoint Central Administration Web site 


• The Farm Administrator account must be a Service Administrator for the User Profile Service that you are configuring. For more information about how to set service permissions, see Assign administration of a User Profile service application (SharePoint Server 2010).


• If you are synchronizing profile information by using AD DS, the account that is used to connect to AD DS must have Replicate Directory Changes permissions in AD DS. This account must be the same as the farm administrator account or the User Profile Service administrator account and is required to do either full or incremental synchronization with AD DS. Create All Child Objects permission is needed to export properties, such as profile pictures, from SharePoint Server to AD DS.


2. Before proceeding, make sure that you have determined which directory service containers that you want synchronized with SharePoint Server. I have several test users already setup in an OU.


3. On the Central Administration Web site, in the Application Management section, click Manage service applications.


4. On the Manage Service Applications page, click the Name of the User Profile Service Application that you want to manage. 


5. On the Manage Profile Service page, in the Synchronization section, click Configure Synchronization Connections.


6. On the Synchronizations Connections page, click Create New Connection.


7. On the Add new synchronization connection page, type a name for the synchronization connection in the Connection Name box.


8. From the Type list, select the kind of directory service to which you want to connect. AD in this case.


9. If the selected type is Business Data Connectivity, enter a name for the connection in the Name box. Select a Business Data Connectivity application from the Business Data Connectivity Entity box. Select whether the entity has a 1:1 mapping or a 1:many mapping, enter the appropriate profile property, and then click OK. Otherwise, continue with the following steps. - I'm ignoring this functionality for this post.

10. In the Connection Settings section, type the name of the directory service forest to which you want to connect (domain.com), the account credentials for the directory service (domain\admin), and the port that you want to use when you connect to the directory service (use the default) . Select Auto discover domain controller to automatically locate the domain controller for this forest or type the name of the domain controller in the Domain controller name box. - I don't recommend using the autodiscover. There have been other users who've reported problems, but I'll leave it up to you.


11. In the Connection Settings section, select the Use SSL-secured connection: check box, if needed, to use a Secure Socket Layer connection when you connect to the directory service.


12. In the Containers section, click Populate Containers and then select the containers from the directory service that you want to synchronize. Click Select All if you want to synchronize all containers. For example, if you only want to synchronize user information, you can select only those containers that have user profile information.



13. Click OK.


To configure Profile Synchronization settings 




1. Verify that you have the following administrative credentials:


• You must be a member of the Farm Administrators group on the computer that is running the SharePoint Central Administration Web site 


• You must be a Service Administrator with Full Control permissions for the User Profile Service that you are configuring. For more information about how to set Full Control permissions, see Assign administration of a User Profile service application (SharePoint Server 2010).


• The Farm Administrator account, which is created during the SharePoint farm setup, must also be a System Administrator (sysadmin) on Microsoft SQL Server 2005 or Microsoft SQL Server 2008


• If you are synchronizing profile information with AD DS, the account that is used must have Replicate Directory Changes permissions. This account must be the same as the farm administrator account or the User Profile Service administrator account and is required to do either full or incremental synchronization with AD DS. Create All Child Objects permission is needed to export properties, such as profile pictures, from SharePoint Server to AD DS.


2. On the Central Administration Web site, in the Application Management section, click Manage service applications.


3. On the Manage Service Applications page, click the Name of the User Profile Service Application that you want to manage. 


4. On the Manage Profile Service page, in the Synchronization section, click Configure Synchronization Settings.


5. On the Configure Synchronization Settings page, in the Synchronization Entities section, select Users and Groups to synchronize both user information and group information or select Users to synchronize only user information.


You should first do a full synchronization of users only. Once this is complete, run an incremental synchronization of both users and groups. 


6. On the Configure Synchronization Settings page, in the Synchronize BDC Connections section, click to clear the Include existing BDC connections for synchronization? check box if you want to exclude data import from the Business Data Connectivity service. - No BDC for now.


7. On the Configure Synchronization Settings page, in the External Identity Manager section, select Use SharePoint Profile Synchronization to use the Profile Synchronization engine in SharePoint Server 2010 or select Enable External Identity Manager to use an external synchronization application such as Microsoft Identity Lifecycle Manager 2007.


Enabling an external identity manager disables all Profile Synchronization options and the status display in SharePoint Server 2010. 





8. Click OK.


In Part II of this blog I'll go through the steps to do the initial synchronization and show you how to use the MIIS client to verify it's working properly.