Friday, September 30, 2011

Step By Step External Content Type and External List

Steps to create External Content Types using SQL Server Table.

Open Central Administration > Application Management > Manage Service Applications

Select Business Data Connectivity Sevice and click "Manage"

We first need to give permissions to the user. Click "Set Metadata Store Permission". This will open up a Modal Window. Add required user set all permisions and click "OK".


Open SharePoint Designer 2010.

Open your site in SharePoint Designer.

Click "External Content Type" under Left Navigation.Click "New External Content Type".




Enter "Name" and "Display name" of new content type.Select "Generic List" for "Office Item Type"


Under "External Content Type Operation" click on "Click here to discover external Data source and define operations".


Click Add Connection.


Select "SQL Server" for "Data Source Type" and Click Ok


Enter SQL Server and Database Detail and click "OK"


Under "Data Source Explorer" select Table


Right Click Table and click "Create All Operations". This will open up operation creation window. Click Next.


Under Properties check "Show in Picker" and click Next.


On this screen you can set "Filter" if so required. Click Finish. Save External Content Type.


Steps to create External List using External Content Types created above.

Right Click External Content Type and Click "External List".


This will open a window. Enter "Name" and "Description" of new external list name.

Thats all a new External List is created will all Operations.

Thursday, September 29, 2011

SharePoint Role Definition (SPRoleDefinition) Programmatically

The role definition, or permission level, is the list of rights associated with the role. For example, a user with the Read role can browse pages in the Web site and view items in lists. A role definition is a collection of rights bound to a specific object. Role definitions (for example, Full ControlReadContributeDesign, or Limited Access) are scoped to the Web site.


We can create Role definitions easily thru Web Site. But in this Blog I will tell how we can do this using programmatically.




using(SPSite site = new SPSite("http://anmol-pc"))
{
using(SPWeb web = site.OpenWeb())
{



SPRoleDefinition customRoleDef = new SPRoleDefinition();
customRoleDef.Name = "Custom-Role-Def";
customRoleDef.Description = "Can view, add and update";



customRoleDef.BasePermissions = 
SPBasePermissions.AddListItems |
SPBasePermissions.EditListItems |            
SPBasePermissions.ViewListItems | 
SPBasePermissions.OpenItems |
SPBasePermissions.ViewVersions |
SPBasePermissions.ViewFormPages |
SPBasePermissions.BrowseDirectories |
SPBasePermissions.ViewPages |
SPBasePermissions.BrowseUserInfo |
SPBasePermissions.UseRemoteAPIs |
SPBasePermissions.Open ;



//if role Definition found do nothing
if (web.RoleDefinitions.Cast<SPRoleDefinition>().Any(r => r.Name == customRoleDef.Name))
{}
else
{

//add role definition if not found
 web.RoleDefinitions.Add(customRoleDef);
 web.Update();
}



}
}

Tuesday, September 27, 2011

SharePoint Working with QuickLaunch Programmatically

Working with QuickLaunch Programmatically.

In QuickLaunch navigation structure, the tree is rooted on a single SPNavigationNode object. This object has a Children property that returns an SPNavigationNodeCollection object with navigation nodes one level down from the root. Each of these nodes has a Children property that can contain a collection of nodes for another level down the hierarchy.
You can get the parent node for a collection by getting the value of the collection's Parent property. You can return to the collection by getting the value of the parent node's Children property.

To add QuickLaunch Root and Children programmatically use code as described below:



public static void AddQuickLaunchItem(string header, string item, string url)
{
using(SPSite site = new SPSite("
http://anmol-pc"))
{
using(SPWeb web = site.OpenWeb())
{

SPNavigationNodeCollection quickLaunch = web.Navigation.QuickLaunch;

// try to get quick launch header
SPNavigationNode nodeHeader =
quickLaunch.Cast<SPNavigationNode>().Where(n => n.Title == header).FirstOrDefault();


//if header not found create it
if (nodeHeader == null)
    nodeHeader = quickLaunch.AddAsFirst(new SPNavigationNode(header, ""));

nodeHeader.Update();

//try to get node item under header
SPNavigationNode nodeItem =
      nodeHeader.Children.Cast<SPNavigationNode>().Where(n => n.Title == item).FirstOrDefault();


//If item not found under heading then create it
if (nodeItem == null)
      nodeItem = nodeHeader.Children.AddAsLast(new SPNavigationNode(item, url));
else
      nodeItem.Url = url;


nodeItem.Update();
nodeHeader.Update();


}
}
}

Monday, September 26, 2011

SharePoint 2010 Setting Lookup Relationship Behavior (RelationshipDeleteBehavior)

If we want to enforce referential integrity in the relationship between two lists then we need to make use of RelationshipDeleteBehavior property of lookup field. If a lookup field in the dependent list has the RelationshipDeleteBehavior property set to Cascade, then deleting an item from the source list causes all related dependent list items to be deleted as well.
A lookup field that enforces a deletion constraint must be indexed. That means we first need to set Indexed property of Lookup field to True.

See programmatically example below:



using(SPSite site = new SPSite("http://anmol-pc"))
{
using(SPWeb web = site.OpenWeb())
{

SPList list = web.Lists.TryGetList("MyChildList");
SPFieldLookup lookupField = (SPFieldLookup)list.Fields.GetFieldByInternalName("fieldname");
lookupField.Indexed = true;
lookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Cascade;

lookupField.Required = true;
lookupField.LinkToItem = true;
lookupField.EnforceUniqueValues = false;
lookupField.Update();

}
}

Wednesday, September 21, 2011

SharePoint 2010 Page Rating using Social Data Service (SocialDataService.asmx)

To retrieve social data stored in SharePoint we can use Social Data Service. The web services are located at ISAPI folder found under {Sharepoint Root}. If you site url is http://anmol-pc/ then the SocialDataService url would be http://anmol-pc/_vti_bin/socialdataservice.asmx









You can see lot of functionality exposed, but in this Post I will explain "GetRatingOnUrl". First create Console Application project in Visual Studio. Add reference to socialdataservice.asmx service and add code as mentioned below.


ServiceReference1.SocialDataService _SocialDataService =
            new ServiceReference1.SocialDataService();


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


_SocialDataService.Url =  "http://anmol-pc/_vti_bin/socialdataservice.asmx";

SocialRatingDetail _SocialRatingDetail =
           _SocialDataService.GetRatingOnUrl(
http://anmol-pc/Pages/MyPage.aspx);

string rating = _SocialRatingDetail.Rating.ToString();



Tuesday, September 20, 2011

SharePoint 2010: Client Object Model: Content Type Development

To Create a content type using client object model, first create new Project using Console project Template. Add refrence to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll asemblies. You can find tyhen at {SharePoint Root}\ISAPI folder.

SharePoint code can run externally with help of ClientContext object. The ClientContext object provides access to site collection objects.

Code:

ClientContext clientContext = new ClientContext("http://anmol-pc");
Web web = clientContext.Web;


ContentTypeCollection contentTypes = web.ContentTypes;
clientContext.Load(contentTypes);
clientContext.ExecuteQuery();


ContentTypeCreationInformation newConInfo = new ContentTypeCreationInformation();
newConInfo.Name = "MyFirstContentType";
newConInfo.ParentContentType = contentTypes.GetById("add parent content ID");
newConInfo.Group = "My Group";
           
//Create
ContentType newContent = contentTypes.Add(newConInfo);
clientContext.ExecuteQuery();

SharePoint 2010: Workflow Activity to trigger another Workflow

While creating a workflow in SharePoint Designer, You may find a situation in which you may require to create a Step to trigger another workflow on same list. By default its not possible in Sharepoint Designer. So to achieve this we can create a custom workflow activity.

Steps to acheive this
  • Create Empty SharePoint Project.
  • Add Sharepoint Mapped Folder
    "{SharePointRoot}\Template\1033\Workflow"
  • Create new file "SPDStartWorkflow.actions" in mapped folder. And paste below code in this
    <?xml version="1.0" encoding="utf-8" ?>
    <WorkflowInfo>
      <Actions Sequential="then" Parallel="and">
        <Action Name="Start Another Workflow"
         ClassName="WorkflowStarter.StartAnotherWorkflow"
         Assembly="WorkflowStarter, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3b0e31fdf8deb757"
         AppliesTo="all"
         Category="Custom Actions">
          <RuleDesigner Sentence="Start another workflow on %2, named %1">
            <FieldBind Field="WorkflowIdentifier" Text="Call Self" Id="1" DesignerType="TextArea" />
            <FieldBind Field="ListId,ListItem" Text="this item" Id="2" DesignerType="ChooseListItem" />
          </RuleDesigner>
          <Parameters>
            <Parameter Name="__Context" Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext" Direction="In" />
            <Parameter Name="WorkflowIdentifier" Type="System.String, mscorlib" Direction="Optional" />
            <Parameter Name="ListId" Type="System.String, mscorlib" Direction="In" />
            <Parameter Name="ListItem" Type="System.Int32, mscorlib" Direction="In" />
          </Parameters>
        </Action>
      </Actions>
    </WorkflowInfo>

  •  Add new class "StartAnotherWorkflow" and inherit it from "Activity". Add below code in file.
        public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context",
                                                                                       typeof(WorkflowContext),
                                                                                       typeof(StartAnotherWorkflow));


        public static DependencyProperty ListIdProperty = DependencyProperty.Register("ListId", typeof(string),
                                                                                      typeof(StartAnotherWorkflow));

       
        public static DependencyProperty ListItemProperty = DependencyProperty.Register("ListItem", typeof(int),
                                                                                        typeof(StartAnotherWorkflow));

       
       public static DependencyProperty WorkflowIdentifierProperty = DependencyProperty.Register("WorkflowIdentifier",
                                                                                                  typeof(string),
                                                                                                  typeof(
                                                                                                      StartAnotherWorkflow
                                                                                                      ), new PropertyMetadata(""));


        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public WorkflowContext __Context
        {
            get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); }
            set { base.SetValue(__ContextProperty, value); }
        }

       
        [Description("ID of the list we are working with")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string ListId
        {
            get { return ((string)(base.GetValue(ListIdProperty))); }
            set { base.SetValue(ListIdProperty, value); }
        }

       
        [Description("ID of the list item we are working with")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public int ListItem
        {
            get { return ((int)(base.GetValue(ListItemProperty))); }
            set { base.SetValue(ListItemProperty, value); }
        }

       
        [Description("Workflow name or template base id")]
        [ValidationOption(ValidationOption.None)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string WorkflowIdentifier
        {
            get { return ((string)(base.GetValue(WorkflowIdentifierProperty))); }
            set { base.SetValue(WorkflowIdentifierProperty, value); }
        }

       
         protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                //need to run under SHAREPOINT\system account because workflow owner might not have start workflow permissions on the target list
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(__Context.Site.ID))
                    {
                        using (SPWeb web = site.AllWebs[__Context.Web.ID])
                        {
                            SPList list = web.Lists[new Guid(ListId)];

                           
                            SPListItem listItem =
                                list.Items.GetItemById(ListItem);

                           
                             //resolve any lookup parameters
                            string wkId =
                                Common.ProcessStringField(executionContext,
                                                          WorkflowIdentifier);

                           
                            //find workflow association by name
                            SPWorkflowAssociation myWorkflowAssoc =
                                list.WorkflowAssociations.GetAssociationByName(
                                    wkId, Thread.CurrentThread.CurrentCulture);
                           
                            if (myWorkflowAssoc != null)
                            {
                                //start the workflow
                                site.WorkflowManager.StartWorkflow(listItem,
                                                                   myWorkflowAssoc,
                                                                   myWorkflowAssoc.AssociationData);
                            }
                        }
                    }
                });
            }
            catch (Exception e)
            {
              
            }

            return ActivityExecutionStatus.Closed;
        }

Wednesday, September 14, 2011

Create User Profile Programmatically Sharepoint 2010

You can create new user profile using object model as demonstrated below. UserProfileManager class can be used for this purpose. UserProfileManager can be found under namespace Microsoft.Office.Server.UserProfiles.

using (SPSite _site = new SPSite("http://anmol"))
{
       SPServiceContext _context = SPServiceContext.GetContext(_site);

       UserProfileManager _profileManager = new UserProfileManager(_context);

       string _userName = "domain\\AnmolRehan"
       if(_profileManager.UserExists(_userName))

             _profileManager.CreateUserProfile(_userName);}

How to update existing user profile programmatically?

Update User Profile Programmatically Sharepoint 2010

You can update properties of existing profile using object model as demonstrated below. UserProfileManager class can be used for this purpose. UserProfileManager can be found under namespace Microsoft.Office.Server.UserProfiles.


Code to update user profile:

using (SPSite _site = new SPSite("http://anmol"))
{
       SPServiceContext _context = SPServiceContext.GetContext(_site);

       UserProfileManager _profileManager = new UserProfileManager(_context);
       
       string _userName = "domain\\AnmolRehan"
       UserProfile _profile = _profileManager.GetUserProfile(_userName);
       _profile[PropertyConstants.AboutMe].Value = "This is about me";
       _profile[PropertyConstants.Manager].Value = "domain\Manager1";
       _profile[PropertyConstants.Skills].Value = "Skill1, Skill2";
       _profile.Commit();

}


PropertyConstants contains the property constants to be passed into the indexer of the UserProfile object. All fields in the PropertyConstants class are string values that contain the names of properties that hold user profile information.


How to create user profile programmatically?



Tuesday, September 13, 2011

How to create SPWebApplication (SharePoint Web Application) programmatically?

SPWebApplication programmatically

For creating SharePoint Web Application programmatically you first need to enable Remote Administration using Sharepoint 2010 Management Shell. Open Sharepoint 2010 Management Shell and type following commands one at a time

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $null



$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$contentService.RemoteAdministratorAccessDenied = $false
$contentService.Update()



Below is the code to create SPWebApplication programmatically:

SPWebApplication newApplication;

SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);

webAppBuilder.Port = 80;
webAppBuilder.RootDirectory = new DirectoryInfo("C:\intepub\wwwroot\wss\80");

webAppBuilder.ApplicationPoolId = "My First site on port 80";
webAppBuilder.ApplicationPoolUsername = "domain\ServiceAccount";
webAppBuilder.ApplicationPoolPassword = StringToSecureString("password");


webAppBuilder.ServerComment = "My First Site";
webAppBuilder.CreateNewDatabase = true;
webAppBuilder.DatabaseServer = "sql01"; // DB server name
webAppBuilder.DatabaseName = "WSS_Content_MyFirstSite";// DB Name
webAppBuilder.HostHeader = "contoso.com"; //if any


webAppBuilder.UseNTLMExclusively = true;  // authentication provider for NTLM
webAppBuilder.AllowAnonymousAccess = true; // anonymous access permission
                                   
// Finally create web application
newApplication = webAppBuilder.Create();


//Enable Claims
newApplication.UseClaimsAuthentication = true;
newApplication.Update();
newApplication.Provision();
 

Popular Posts