Thursday, December 29, 2011

To create a service reference to access SharePoint lists

  1. Open or create a Visual Studio project.
  2. In Solution Explorer, right-click the References node, and then click Add Service Reference.
  3. In the Address box, type the URL to the target site and append /_vti_bin/ListData.svc. For example, the address for the site intranet.wingtip.com would be http://intranet.wingtip.com/_vti_bin/ListData.svc.
  4. Change the default name in the Namespace box from ServiceReference1 to something more appropriate, such as WingtipSite.
  5. Click OK to create proxy classes, including a data context and entity classes for the lists that you want to access.
  6. Begin writing code against these proxy classes, which provide strongly typed access to the columns of SharePoint list items.
Programming with the DataContext Class
When you add a service reference to your project, the WCF Data Services support can inspect the target site and build a DataContext class that exposes a property for each list in the site. For example, if the target site has a list named "Developers", the DataContext object exposes a property named Developers that holds a collection of items that you can enumerate with a simple foreach loop. Be aware that you must set the proper credentials for the DataContext object before you make the first call to a SharePoint site.

WingtipDevSiteDataContext dc = 
  new WingtipDevSiteDataContext(new 
  Uri("http://intranet.wingtip.com/_vti_bin/ListData.svc/"));

dc.Credentials = System.Net.CredentialCache.DefaultCredentials;

var source = dc.Developers;

lstDevelopers.Items.Clear();
foreach (var dev in source) {
    string devName = dev.FirstName + " " + dev.LastName;
    lstDevelopers.Items.Add(devName);
}
Adding New List Items 
When you add a service reference to ListData.svc, in addition to generating a proxy class for the DataContext object, the WCF support also creates an 
entity class for each list. For example, if the target site has a list named "Developers", the creation of a service reference creates an entity class named DevelopersItem.
This entity class provides an easy way to add items to a SharePoint list. You use the entity class to create and initialize an object that holds the data for a new SharePoint 
list item. Next, you pass the object to one of the Add methods in the DataContext object. For example, if you have a list named "Developers", 
the DataContext object contains a method named AddToDevelopers. After you call the Add method with a new instance of the entity class, you can call the SaveChanges method on the 
DataContext object to call across the network and create a new item inside a SharePoint list.

Create Folder in list/library using Ecmascript/Javascript client object model

I have written a quick example of how to add a folder in a list using Ecmascript/Javascript client object model in SharePoint 2010.
You can add this script in a CEWP for testing purposes. In the below script Replace “ListName” with your list or library name and “NewFolder” with whatever you want to call your folder.
<script type=”text/javascript”>
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(AddFolder, “sp.js”);
function AddFolder()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle(“ListName“);
var listItemCreationInfo = new SP.ListItemCreationInformation();
listItemCreationInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
listItemCreationInfo.set_leafName(‘NewFolder‘);
var newItem = list.addItem(listItemCreationInfo);
newItem.update();
currentcontext.load(currentweb);
currentcontext.load(list);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
SP.UI.Notify.addNotification(‘Folder created successfully’, false);
}
function ExecuteOnFailure(sender, args) {
alert(“Error in Script”);
}
</script>

Retrieve all user in SharePoint 2010 site using Javascript client object model

function GetAllUsers()
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var userInfoList = web.get_siteUserInfoList();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘’ +’’ + userID + ‘’ +
1
’);
this.collListItem = userInfoList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
var item = collListItem.itemAt(0);
var profileNotes = item.get_item(‘Notes’);
alert(profileNotes);
}
function onQueryFailed(sender, args)
{
}
}

Get all users and groups client object model sharepoint 2010

function GetUsersGroups()
{
ClientContext context = new Microsoft.SharePoint.Client.ClientContext(“http://SPSite”);
GroupCollection groupCollection = context.Web.SiteGroups;
context.Load(groupCollection,
groups = > groups.Include(
group = > group.Users));
context.ExecuteQuery();
foreach (Group group in groupCollection)
{
UserCollection userCollection = group.Users;
foreach (User user in userCollection)
{
MessageBox.Show(“User Name: ” + user.Title + ” Email: ” +
user.Email + ” Login: ” + user.LoginName);
}
}
//Iterate the owners group
Group ownerGroup = context.Web.AssociatedOwnerGroup;
context.Load(ownerGroup);
context.Load(ownerGroup.Users);
context.ExecuteQuery();
foreach (User ownerUser in ownerGroup.Users)
{
MessageBox.Show(“User Name: ” + ownerUser.Title + ” Email: ” +
ownerUser.Email + ” Login: ” + ownerUser.LoginName);
}
context.Dispose();
}

Sunday, December 25, 2011

Create Custom Content Types in SharePoint 2010

In this task, you create an empty SharePoint 2010 project in Microsoft Visual Studio 2010.

To create the SharePoint project

  1. To start Visual Studio 2010, click the Start Menu, click All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog window, in the Installed Templates section, click Visual C#, click SharePoint, and then click 2010.
  4. Select Empty SharePoint Project from the project items.
  5. In the Name box, type CreateContentType and then click OK.
  6. In the SharePoint Customization Wizard, type the local Web site that you want to use for this exercise (such as http://localhost/SampleWebSite).
  7. For the trust level, select Deploy as a farm solution and then click Finish.

Create a Content Type

In this task, you create the content type as a feature and add an event receiver.

To create a content type

  • Right-click the Features folder in Solution Explorer and then click Add Feature.
  • Right-click Feature1 and then click Add Event Receiver. Visual Studio adds a feature event receiver to Feature1.
  • Right-click Feature1.EventReceiver.cs and then click View Code.
  • Uncomment the FeatureActivated method in the Feature1EventReceiver class.
  • Insert the following code in the FeatureActivated method.
     
    using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
    {
        SPContentType newAnnouncement = spWeb
            .ContentTypes
            .Cast<SPContentType>()
            .FirstOrDefault(c => c.Name == "New Announcements");
        if (newAnnouncement != null)
        {
            newAnnouncement.Delete();
        }
    
        SPField newField = spWeb.Fields
            .Cast<SPField>()
            .FirstOrDefault(f => f.StaticName == "Team Project");
        if (newField != null)
        {
            newField.Delete();
        }
    
        SPContentType myContentType = 
            new SPContentType(spWeb.ContentTypes["Announcement"], 
                spWeb.ContentTypes, "New Announcements");
        myContentType.Group = "Custom Content Types";
    
        spWeb.Fields.Add("Team Project", SPFieldType.Text, true);
        SPFieldLink projFeldLink = new SPFieldLink(spWeb.Fields["Team Project"]);
        myContentType.FieldLinks.Add(projFeldLink);
    
        SPFieldLink companyFieldLink = new SPFieldLink(spWeb.Fields["Company"]);
        myContentType.FieldLinks.Add(companyFieldLink);
    
        spWeb.ContentTypes.Add(myContentType);
        myContentType.Update();
    }
    
    The FeatureActivated method is run when Feature1 is started. This code does the following:
    • Deletes the content type New Announcements and the field Team Project, if they exist.
       
       
    • Creates a parent content type Announcement based on the New Announcements content type.
       
       
    • Creates a text field, which is titled Team Project, and then adds it to the content type.
       
       
    • Adds an existing field, which is titled Company, to the content type.
       
       
  • Uncomment the FeatureDeactivating method.
  • Insert the following code in the FeatureDeactivating method.
     
    using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
    {
        SPContentType myContentType = spWeb.ContentTypes["New Announcements"];
        spWeb.ContentTypes.Delete(myContentType.Id);
        spWeb.Fields["Team Project"].Delete();
    }
    
    The FeatureDeactivating method is run when Feature1 is deactivated. This code does the following:
    • Deletes the content type New Announcements.
    • Deletes the text field Team Project.
  • In Solution Explorer, right-click CreateContentType and then click Deploy.

Verify that the Project Works Correctly

In this task, you verify the presence of the content type and the two fields.

To test the project

  1. Start Internet Explorer and browse to the Web site that you specified previously.
  2. At the upper-left section of the screen, click Site Actions, and then click Site Settings.
  3. Under Galleries, click Site Columns.
  4. In the Show Group options, click Custom Columns.
    You should see the new field Team Project.


    Figure 1. Team Project field

    Team Project field
  5. Click Site Actions and then click Site Settings.
  6. Under Galleries, click Site content types.
  7. From the Show Group options, select Custom Content Types.
    You should see the new content type New Announcements.


    Figure 2. New Announcements content type

    New Announcements content type

Creating a Database-Based External Content Type Association

  1. Open your site by using SharePoint Designer 2010, and then go to the External Content Type Designer view.


    Figure 1. SharePoint Designer 2010 External Content Types list page

    External Content Type Designer
  2. Create external content types, which you can base on a combination of tables, views, stored procedures, web methods, Microsoft .NET Framework methods, and so on, as shown in Figure 2.


    Figure 2. Creating external content types

    Creating external content types
  3. In SharePoint Designer 2010, open the external content type that contains the foreign key of the related external content type. For example, you might create two external content types, X and Y, as shown in Figure 3.


    Figure 3. Two related external content types

    Two related external content types If X contains a foreign key that holds a value that specifies a Y external content type item, open X in SharePoint Designer, and navigate to Operation Designer, as shown in Figure 4.


    Figure 4. Operation Designer

    Operation Designer
  4. Determine the association that you want to create.
    An association can retrieve and display items of one type when you select an item of another type, based on their relationship, as shown in Figure 5.


    Figure 5. Two types of associations in SharePoint Designer

    Two types of associations in SharePoint Designer In most scenarios, the association is all that is required. (Reverse associations are discussed in Creating a Reverse Association.)
    note Note:
    The association that is labeled Association in Figure 5 can also be thought of as a forward association. As described, it is typically all that is needed to create an association between two entities.
  5. In Operation Designer, expand your data source in the Data Source Explorer.
    Creating an association for databases (a Microsoft SQL Server data source connection) is slightly different from creating one for a WCF service or .NET Framework type connection. This example starts with databases and continues with WCF in Creating External Content Type Associations Based on WCF.
  6. If you want to create an association on a table, right-click the same table that you used when you created the other operations for that external content type (see Figure 6).


    Figure 6. Selecting a table in Data Source Explorer

    Selecting a table in Data Source Explorer
  7. Click New Association.
    The Association wizard opens. It contains an Association Properties section and three Parameter sections: Input Parameters, Filter Parameters, and Return Parameter, as shown in Figure 7.


    Figure 7. Association wizard

    Association wizard
  8. You are now asked to select a related external content type. (See the Errors and Warnings pane for guidance throughout the wizard.) Click Browse, and in the External Content Type Selection dialog box, select the external content type that you want to associate with the current external content type, as shown in Figure 8. This should be the external content type that you currently have open in SharePoint Designer.


    Figure 8. External Content Type Selection dialog box

    External Content Type Selection dialog box
    note Note:
    The current external content type is appended with (Current) for guidance.
  9. After you select a related external content type, a table appears (see Figure 9). This table lists all identifiers that are present on that external content type.


    Figure 9. Identifiers present on the external content type

    Identifiers present on the external content type
  10. For this association to work in all user scenarios (that is, those that use the External Content Type Picker), each operation on the current external content type (Read Item, Read List, Create, or Update) must have all occurrences of the Foreign Key field marked with a foreign identifier. As instructed in the text above the table in Figure 9, select a field in the list of all fields on the current external content type, which should be mapped to the identifier.
    note Note:
    Typically, this field is the Foreign Key field. If the names are the same, it is mapped for you, and the error message will disappear.
  11. On the next page of the wizard, shown in Figure 10, you configure the parameters for the input to the association. In many cases, the names of the fields and columns are the same; therefore, this step resembles the previous step, in which you set up the properties.


    Figure 10. Input Parameters Configuration page

    Input Parameters Configuration page
  12. On this page of the wizard, you configure the "input" to the association (for example, an item that is specified or provided through a Web Part). You must map the data source element (typically the Foreign Key column) to an identifier of the related external content type as input to the association. In the Data Source Elements pane on the left side, select the data source element in the list. In the Properties pane on the right side, select the Map to Identifier check box. In the Identifier list, select the appropriate identifier, as shown in Figure 12.
    To view the name of the external content type and the name of its identifier, see the Errors and Warnings pane, as shown in Figure 11.


    Figure 11. Errors and Warnings pane showing external content type and identifier names

    Errors and Warnings pane


    Figure 12. Selecting the identifier

    Selecting the identifier
  13. In the Filter Parameters section, you can create a filter to screen what is returned from the association (see Figure 13). This is not required, and typically is not done. One possible example of using a filter here could be to filter on an association to an Employee, filtering Part Time staff from Full Time staff.


    Figure 13. Filter Parameters Configuration page

    Filter Parameters Configuration page
  14. Similar to the Input Parameters section, the Return Parameter section enables you to configure the data that is returned (for example, if an item of one type is specified, you can configure the list of items that is returned that are associated or related to that item—such as all Orders for a Customer).
    On this page, map the field of the current external content type to the identifier of the current external content type, if it is not done already (see Figure 14). In some cases, this page is configured for you.


    Figure 14. Return Parameter Configuration page

    Return Parameter Configuration page
  15. Click Finish to save your external content type. The association is now enabled in Web Parts, the Picker, and the cache.


    Figure 15. External Content Type Operations

    External Content Type Operations
You can view the association by creating a profile page, as shown in Figure 16.


Figure 16. Profile page

Profile page
note Note:
When creating a profile page, the association is displayed in the Related List Web Part, which is set up on the page automatically. In this case, all surveys are displayed for the customer who filled them out. If another customer is selected and displayed in the profile page, the list of survey items on the page changes accordingly (see Figure 17).


Figure 17. Profile page for customer and related surveys

Profile page for customer and related surveys

Creating a Reverse Association

To create a reverse association, you must have a stored procedure. You cannot create a reverse association on a table for the current external content type. If you already created an association, a reverse association is not necessary to enable associations in Web Parts and the Picker.
You should note that an association is a way to return multiple items of the current type (the external content type that you have open in SharePoint Designer). A reverse association, however, is a way to return a single item of the related external content type (not the external content type that you are creating operations on).
You cannot create a reverse association on the table for the current external content type because it would return information based on that table, which does not provide information about the related external content type. A stored procedure can bridge this gap by implementing the necessary query.
The benefit of creating a reverse association is that the wizard handles the foreign identifier mappings on the other external content type operations. For off-lining an external list to Microsoft Outlook 2010 or Microsoft SharePoint Workspace 2010, you can create a simple [ 1 . . 1 ] association with a reverse association to enable the Picker, item retrieval for the cache, and so on.
An example of a simple "one-to-one" foreign key–based association is a music album to an album cover.

Creating External Content Type Associations Based on WCF

 

  1. To create associations for WCF service connections, just create the association on the appropriate web method. Again, you create the association on the external content type that contains the foreign key. In this example, you know that in the metadata for each product there is a subcategory for that particular product. Therefore, you open Product in SharePoint Designer and create an association there.
    For example, you might want to create the association GetProductsofSubcategory between the following (see Figure 18):
    • External Content Type Product (Identifier = ProductId and FK Field = ProductSubcategoryKey)
    • External Content Type SubCategory (Identifier = ProductSubcategoryID)


    Figure 18. Creating a new association

    Creating a new association
  2. The rest of the wizard is the same as in the previous example. This example demonstrates a scenario in which the name of the identifier on the related external content type (ProductSubcategoryID of SubCategory) is different from the name of the Foreign Key field on the current external content type (ProductSubcategoryKey of Product).
    note Note:
    Because the names ProductSubcategoryID and ProductSubcategoryKey are different, this matching cannot be done for you on the Association Properties page. You must select the correct field from the Field list, as shown in Figure 19.


    Figure 19. Association Properties page

    Association Properties page
  3. Select the field on the current external content type (Product), which indicates the foreign key to the related external content type (SubCategory)—again, this is ProductSubcategoryKey. This is mapped to the ProductSubcategoryID identifier of Subcategory.


    Figure 20. Selecting ProductSubcategoryKey field in Association Properties

    Selecting ProductSubcategoryKey field
  4. On the Input Parameters page, you must configure the input to the association. Under Errors and Warnings, the message states that you must select a data source element. The element that you select must represent the identifier of the input to the association.


    Figure 21. Selecting data source elements in Input Parameters

    Selecting data source elements in Input Parameters
  5. Again, the association that you are creating is GetProductsofSubcategory. The input to the association is the Subcategory, and what you are "getting" (returning) are the Products. Because Subcategory is the input, in the Data Source Elements pane, select the Subcategory identifier and map it, as shown in Figure 22.


    Figure 22. Mapping ProductSubcategoryID

    Mapping ProductSubcategoryID
  6. You cannot create filter parameters for WCF service–based external content type associations, so there is no corresponding wizard page. Click Next to go to the Return Parameter page.
  7. Finally, to return products, you must configure the return parameters for Product. As stated earlier, the identifier for Product is ProductID. Under Errors and Warnings, the error message guides you to map this identifier, as shown in Figure 23.


    Figure 23. Mapping the identifier in Return Parameter Configuration

    Identifier in Return Parameter Configuration In this particular web service web method, the creators of the service renamed the data source element to ProductKey instead of ProductID, as shown in Figure 24.
    note Note:
    You will have already mapped the other operations (for example, the Read Item operation) similarly on the Return Parameter Configuration page of the wizard.


    Figure 24. Read Item operation

    Read Item operation
  8. Map the return parameter identifier by selecting the Map to Identifier check box, and then selecting the identifier in the Identifier list, as shown in Figure 25.


    Figure 25. Mapping the return parameter

    Mapping the return parameter
  9. Click Finish to save the external content type. The association is now enabled in Web Parts, the picker, and the cache, as shown in Figure 26.


    Figure 26. Association is enabled

    Association is enabled
  10. Again, create a profile page to view the working association, as shown in Figure 27.


    Figure 27. Profile page showing the working association

    Profile page with working association

Conclusion

This article, intended for experienced users of Microsoft Business Connectivity Services (BCS) in Microsoft SharePoint Server 2010, describes how to create associations between external content types declaratively (that is, without using code). The article addresses the following associations for external content types:
  • Supported associations in Microsoft SharePoint Designer 2010
  • Unsupported associations in SharePoint Designer 2010
  • Database-based associations
  • Reverse associations
  • Associations based on Windows Communication Foundation (WCF)

Thursday, December 22, 2011

Site Columns &ContentTypes

Introduction to Site Columns :
 In General we can create columns to the lists and Sites. We can reference these columns to the Content Types in the sites. A Site column   is a reusable column definition, which can assign to multiple lists across multiple sites.  Site columns decreases re-work and help us in consistency of metadata across all sites.
For example, suppose we define a site column named Customer. We can add that column to our lists, and reference it in our content types.
Site Column Scope:
Site columns also behave like site content types in terms of scope. When you create a site column on a site, that site column also becomes available to any child sites, and thereby, the lists on those sites.

Adding Site Columns to Lists:

    We can add Site Columns to the lists. When we add, Windows SharePoint services copies the site column locally onto the list as a list column. When you add a site column to a content type, Windows SharePoint Services includes only a reference to that site column in the content type, not the entire column definition.

Referencing Columns in Content Types:

We can reference site and list columns in content types. When we reference a column in a content type, Windows SharePoint Services adds a reference to the column to the content type. This reference includes the column ID. When you add a content type to a list, the columns referenced in that content type are added to the list as list columns, if have not already been added.
We can reference site columns in a site content type. The site column must be in scope for the content type. That is, the site column must be defined on the same site, or on a parent site of the site content type. For a list content type, you can reference site columns, as well as any list columns defined on the same list.

Site Content Types in SharePoint:Site content type is nothing but Meta data. It adds additional information for the documents which is in the libraries/lists in SharePoint and this is called data about data. We can use same content type for the succeeding sites document libraries or lists when it's created once. Main advantage of this site content type is very much helpful for content searching, document routing, workflows etc., following same contracts (Templates) for all the libraries or lists in the SharePoint site within the organizations.
Let uss see, how to create Site Content Type and how to add this site content type to any of the document libraries/ lists in the SharePoint Site.

 

Image2.gif

Image1.gif





Creating Site Content Type
Step 1: We need to create new site content types Galleries section in Site Actions - > Site Settings. It will look as the below screen,

Step 2: Click on that Site content types link for creating new Site Content types. In the coming screen we can see all the predefined site content type which is available for the site collections as below,


Step 3: Then in the above screen, we can edit existing content type or we can create new site content type. Now we will create new site content type by clicking on that Create link. Then we will see the page as below,

Image3.gif

Step 4: In the above screen, we need to give Site Content type name, description, Parent Content type and the place where to put this new content type. Parent Content type is to inherit its properties into our new content type. We can specify new group name to place our new content type or we can give existing one. In this sample, am going to have existing group for storing my new site content type and click ok button.

Step 5: Then we can see all the settings, columns for our new site content type as below,

Image4.gif

Step 6: Under settings section, we can see the title, description, group of the site content type. In the advanced settings, we may update existing template for this site content type. We can set workflowhttp://images.intellitxt.com/ast/adTypes/mag-glass_10x10.gif settings for this site content type. Under Columns section, we can see two existing columns for this content type. If we want then we could add new or existing columns for this site content type.

Step 7: Now we will add one existing column for this site content type by clicking on that Add from existing site columns link and we can see upcoming page as below to add new columns.

Image5.gif

Step 8: As we see in the above screen, am adding Department column for this site content type and click ok. Now we have three columns for this site content type as below,

Image6.gif

Step 9: So for, we have created new site content type. Now we need to add this site content type to any of the document library. Now am going to add this content type to My Documents document library. So am going to advance settings of my documents library and allow site content type to this library by selecting yes option as below,

Image7.gif

Step 10: Then, I need to add my Site Content type to my documents library in the document library settings. Under Content Types section, I am going add my site content type by clicking on the link Add from existing site content type as below,
Image8.gif

Step 11: We need select our Site Content Type from Custom Content Types group and click ok to have this content type for our document library as below,

Image9.gif

Step 12: Now we can see our new site content type in our document library New Menu like,

Image10.gif

Step 13: Ms Office will open new document by clicking on that Demo Type content type as below,

Image11.gif

Step 14: Now we could see our two site content type columns. There user has to enter his title and department name as Meta data for this document.

This is all about Site Content type creation and usage in SharePoint Site.