Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Sunday, January 4, 2015

Allow CAML Query to get items inside Library Folders

Usually a CAML query would query a SharePoint library and get all available items matching the where clause, except the ones within folders of the Library. There is a property which needs to be explicitly set, in order for the query to return all items pertaining to the where clause, including the ones inside folders and nested folders. In the view attribute, the scope needs to be set to Recursive All. A sample CAML query would be:


SPListItemCollection itemCollection = null;
...
...
SPQuery myQuery = new SPQuery();

myQuery.ViewFields = @"<FieldRef Name='UniqueId'/>
                                            <FieldRef Name='ContentType'/>
                                            <FieldRef Name='ID'/><FieldRef Name='FileLeafRef'/>";

                string whereClause = @"<Where>
                                    <Eq>
                                        <FieldRef Name='" + myVariableOne + @"' />
                                            <Value Type='Text'>" + myVariableTwo + @"</Value>
                                    </Eq>
                                  </Where>";

myQuery.Query = whereClause;
myQuery.ViewAttributes += " Scope='RecursiveAll'";


Now use the SPLists GetItems() method to execute the query
Eg: testLibrary.GetItems(myQuery);




Sunday, November 23, 2014

JavaScript to Access List Item GUID in SharePoint 2010

The SharePoint 2010 client object model has provided JavaScript means to access SharePoint Lists, Libraries and items, etc.... Below is a sample where I access a SharePoint list item GUID information during a on click event on a list item. The item click is triggered at the XSLT code rendering the custom field. This is the related JavaScript.

Here the item GUID is captured.



var itemID = null;
var item = null;
var currentItemGUID = null;

//Assigned the itemID value coming from XSLT [JavaScript method call on a hyperlinks OnClick() method]

function MyTestFunction() {
    context = new SP.ClientContext.get_current();
     list = context.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
     item = list.getItemById(itemID);

    context.load(item);
    context.executeQueryAsync(
        function(sender, args) {
            currentItemGUID = item.get_item('UniqueId');
        },
        function(sender, args) {
            alert('Request Failed' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        }, "sp.js");
    
}

Saturday, November 22, 2014

Adding a Web Part Property


1) Declare a private  variable
        private bool mySampleCheckBox = true;

2) Add the browsable web part property

        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
        System.Web.UI.WebControls.WebParts.WebDisplayName("Property Display Name on Web Part Edit"),
        System.Web.UI.WebControls.WebParts.WebDescription("Description of the property"),
        System.Web.UI.WebControls.WebParts.Personalizable(
            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
        System.ComponentModel.Category("Category to include the property"),
        System.ComponentModel.DefaultValue(true)
        ]
        public bool SampleCheckBox
        {
            get { return mySampleCheckBox; }
            set { mySampleCheckBox =  value; }
       }

It would be much cleaner to use two using directives to refer System.ComponentModel and System.Web.UI.WebControls.WebParts and then, remove the repeated code above.

You could set the personalization scope to either Shared or User depending on your requirement.
     
Web part property types and their respective display controls in the web part properties pane are as below:

Property Type
Display
string
Textbox
bool
Checkbox
int
Textbox
float
Textbox
DateTime
Textbox
Enum
Dropdown

Saturday, November 8, 2014

Programmatically Adding User to Site - SPRoleAssignment & RoleDefinitionBindings


In this post I'm adding a domain user to a SharePoint 2010 site programmatically.
I am using a simple console application for this purpose. The code is as below:

using Microsoft.SharePoint;

namespace SPTestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            AddUser();
        }

        static void AddUser()
        {
            string siteUrl = "http://localhost:1000/SitePages/Home.aspx";

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPRoleDefinitionCollection collroleDefinitions = web.RoleDefinitions;
                        SPRoleAssignmentCollection colllroleAssignments = web.RoleAssignments;

                        SPRoleAssignment oRoleAssignment = new SPRoleAssignment("DOMAIN\\username","user@company.lk", "UserName","Notes");
                        SPRoleDefinitionBindingCollection collRoleDefBinding=oRoleAssignment.RoleDefinitionBindings;
                        collRoleDefBinding.Add(collroleDefinitions["Read"]);
                        colllroleAssignments.Add(oRoleAssignment);
                    }
                }
            });
        }
    }
}


Roll Assignments -> are the permissions in the site &
RoleDefinition -> are the permission levels in the site

Sunday, May 11, 2014

New Farm Administrator - could not be updated because the current user is not a farm administrator

You might have come across situations where a new farm administrator via the Central Admin, but the granted rights to the user account does not work as you expected.

In SharePoint 2010, even though a user is added as farm administrator, you might get an error in the log as "could not be updated because the current user is not a farm administrator".

This is due to the ShrarePoint 2010 security feature, which blocks modifications to any object inheriting from SPPersistedObject in the Microsoft.SharePoint.Administration namespace.

To resolve this issue, run the below script in powershell, which grants access.


function RemoteAdministrator-GiveAccess()                                                                                                
{                                                                                                                                                                 
    [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()                                                                                                                        
}                                                                                                                                                                 
                                                                                                                                                                   
RemoteAdministrator-GiveAccess       




                                                                                                        

Saturday, May 10, 2014

Error occurred in deployment step retract solution cannot start service SPUserCodeV4 - SP2010 Foundation

Developers might come across an error in Visual Studio where deployments fails with the error

"error occurred in deployment step retract solution cannot start service SPUserCodeV4 on computer .."

To resolve this issue in SharePoint foundation, follow the below steps:

1) Go to Central Administration
2) Click on "System Settings"
3) Click "Manage Services on Server"
4) The service "Microsoft SharePoint Foundation Sandboxed Code Service" might be stopped. Start it.


Sunday, February 16, 2014

Basic PowerShell for SharePoint and the Equivalent STSADM used in Earlier Version

This is a simple list down of basic PowerShell commands used in command line deployments in SharePoint. [SP 2010 and 2013]  &
The equivalent STSADM commands used in SharePoint 2007 ... back in the day ;)


1. Adding a new WSP to farm solution

SP 2010/2013 PowerShell
 Add-SPSolution -LiteralPath "C:\FolderName\Solution.wsp"
SP 2007 
Stsadm
 stsadm -o addsolution -filename "Solution.wsp"
[Assuming command runs from the correct folder location]


2. Deploy WSP 

SP 2010/2013 PowerShell
 Install-SPSolution -Identity "Solution.wsp" -WebApplication "http://WebSiteUrl" -CASPolicies -GACDeployment -Local -Force

AllWebApplications vs WebApplication - All allows the wsp to be deployed in all SP web applocations. WebApplication - allows the wsp to be deployed to a target web app
CASPolicies - Allows Code Access Security Policies to be deployed [optional]
GACDeployment - Allows DLL installation in the global assembly cache [optional]
Force [optional]
Local - Deploys only in the current server [optional]
SP 2007 
Stsadm
stsadm -o deploysolution -name "SolutionName" -url "Site URL" -immediate -allowgacdeployment -allowcaspolicies -force

instead of -url, you can use -allcontenturls 
instead of -immediate, you can use -time "time to deploy"

GACDeployment - Allows DLL installation in the global assembly cache [optional]


3. Activate feature

SP 2010/2013 PowerShell
 Enable-SPFeature –identity "FeatureName" -URL http://WebSiteUrl
SP 2007 
Stsadm
 stsadm -o activatefeature -id feature_ID -url http://WebSiteUrl -force
[Instead of -Id, you can use -filename or -name with appropriate values]



4. De-activate feature

SP 2010/2013 PowerShell
 Disable-SPFeature –identity "FeatureName" -URL http://WebSiteUrl
SP 2007 
Stsadm
stsadm -o deactivatefeature -id feature_ID -url http://WebSiteUrl
[Instead of -Id, you can use -filename or -name with appropriate values]



5. Retract WSP 

SP 2010/2013 PowerShell
Uninstall-SPSolution -Identity "Solution.wsp" -WebApplication http://WebSiteUrl
SP 2007 
Stsadm
stsadm -o retractsolution -name "Solution.wsp" -url http://WebSiteUrl -immediate 
[Instead of -immediate, you can use -time "TimeToRun"]



6. Remove WSP from SharePoint farm

SP 2010/2013 PowerShell
Remove-SPSolution -Identity "Solution.wsp"
SP 2007 
Stsadm
stsadm -o deletesolution -name "Solution.wsp"

Saturday, January 18, 2014

SharePoint Web Parts Maintenance Page

SharePoint web part maintenance pages allows to manage (reset, delete) the web parts embedded into a particular page. It's useful in situations where its required to remove any web parts from a page which has caused a page crash.

For an instance if the page urls is:
http://localhost:1000/SitePages/Home.aspx

you can get the maintenance page by typing in "?contents=1" at the end of the URL string. Below is a sample:

http://localhost:1000/SitePages/Home.aspx?contents=1

This works the same in  SharePoint 2007, 2010 and 2013