Sunday, March 31, 2013

Disable Attachments in SharePoint List

If you want to disable attachments for a SharePoint list for whatever reason, head on to
  • List Settings >> Advanced 
  • Choose "Disabled" under Attachments section! That's it!
disable attachment in SharePoint List
To make this change programmatically, set SPList.EnableAttachments = false. Its possible to hide attachment link using JavaScript or jQuery. We can also use "SPSecurityTrimmed" control using SharePoint designer. Refer: http://social.technet.microsoft.com/Forums/sharepoint/en-US/d6dc1621-4265-4c4b-8ac8-3c83eefb674c/how-to-disable-or-hide-the-attachment-upload-on-a-lists-new-form

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, March 29, 2013

How to Add Users to SharePoint Site and Grant Permissions

Adding users to SharePoint site is a frequent activity for SharePoint site owners. Users can be added either to any existing SharePoint group or directly under site permissions. Lets see how to add users in SharePoint site.

How to Add Users to SharePoint 

1. To add users to SharePoint 2010 site, Log-in to your SharePoint site with Site owner (or with more) permission.

2. Click on Site Actions > Site Permissions
add users to sharepoint

3. Select the SharePoint Group to which you want to add users. By default, SharePoint sites comes with these user groups:
  • Owners with Full Control Permissions.
  • Members with Contribute Permissions
  • Visitors with Read Only
add users to sharepoint 2010 
4. Click on New and Select Add Users ADS\username) or ADS group names of the people or groups you want to add (separated by semicolons). You can use "Browse" button to search and select the user names.
add users to sharepoint 2010 group
5. To check the accuracy of the user names you added, click the Check Names icon.
how to add users to sharepoint 2010
6. Now after clicking Ok, you could able to see user name added with the permission, we specified. This is how we add users to SharePoint group.

Add User to SharePoint Group using PowerShell:
You can also add users to SharePoint group using PowerShell. Say, You want to add an user to "Marketing Members" group of "Marketing Site collection", Here is how:
Set-SPUser -Identity "domain\user" -Web "http://sharepoint.crescent.com/sites/marketing" -Group "Marketing Owners"

Adding Users Directly to Site Permissions
Its a best practice to add users to a group instead of adding them directly. However, if needed you can grant access to SharePoint users directly.

1. To add users to SharePoint 2010 site directly: Under the Edit tab, click on Grant Permissions from the ribbon.
how to add users to sharepoint
2. In the Users/group field, enter the user's Account name or email address

3. Choose the permissions you wish the user to have under Give Permission, and then click on OK.
how to add users to sharepoint 2010 site
Users will receive a welcome mail based on the selection.

PowerShell Script to Grant Direct User Permission:
Here is the PowerShell to add user permission
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Parameters
$WebURL = "http://intranet.crescent.com"
$UserID="Crescent\Charles"
$PermissionLevel="Read"

#Get the Web 
$Web = Get-SPWeb $WebURL
$User = $web.EnsureUser($UserID)

#Grant Permission to User
Set-SPUser -Identity $User -Web $WebURL -AddPermissionLevel $PermissionLevel


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, March 28, 2013

Package and Delpoy Content Types as Feature Based Solutions in SharePoint 2010

Task: Create a feature based solution package to pack and deploy the content type from DEV environment to STAGING environment in SharePoint 2010.

Although SharePoint 2010 supports content type hub, where content types of one site collection can be used by other site collections/web application/even Farms, we needed an isolation and wanted to pack & deploy content types between different environments.

Solution: Create a Visual Studio project to pack the content type as a feature based solution package (wsp). Lets pack the Content Type "Crescent Travel Request" with Few Columns & Form Template. Here is the step by step guide on Creating Visual Studio Solution for Content Types in SharePoint 2010: 

Create a Visual Studio Project To Package Content Type as a Feature based solution:
1. Create a New Visual Studio 2010 Project of "Empty SharePoint Project" Type, Give it a name, say: "Crescent.TravelRequest.CotentType"
Creating Visual Studio Solution for Content Types in SharePoint 2010
Make it as a Farm Solution and Specify the site for debugging. Click Finish.
Build a deployable Content Type for SharePoint 2010

2. Go to Server Explorer from Visual Studio 2010 (View >> Server Explorer), Expand the nodes and Navigate to your desired content type, In our case it is: Crescent Travel Request. Right click and choose "Import Content Type"
How to Deploy Content Types in SharePoint 2010
This will create a feature "Feature1" and a Content Type element with the selected content type's schema XML. Rename the Feature1 to "Travel Request".
sharepoint 2010 content type deployment
Crescent Content Type's Elements.xml
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ContentType ID="0x01010100C977E928AAE65D498957261048306247" Name="Crescent Travel Request" Group="Crescent Content Types" Inherits="true" Hidden="false" ReadOnly="false" Sealed="false">
    <FieldRefs>
      <FieldRef ID="002acd66-abf3-4cca-9a92-2fe8d93a3de2" Name="Traveller_x0020_Name" DisplayName="Traveller Name" />
      <FieldRef ID="48d47953-dd68-4a51-8990-768438b908e8" Name="Project_x0020_Manager" DisplayName="Project Manager" />
      <FieldRef ID="c600e139-1c03-4524-8ef9-72d8462e3992" Name="Travel_x0020_Date" DisplayName="Travel Date" />
      <FieldRef ID="e9d07d8f-9066-47ae-9d0e-7249386cde5b" Name="Travel_x0020_Coordinator" DisplayName="Travel Coordinator" />
      <FieldRef ID="839c026b-15b4-4d81-8c1a-bb7e53be7120" Name="Origin_x0020_Country" DisplayName="Origin Country" />
      <FieldRef ID="737c35ae-0b8a-494d-baf1-dfcf4271ad53" Name="Origin_x0020_City" DisplayName="Origin City" />
      <FieldRef ID="2489cb17-cace-48bc-939e-438d458d90b0" Name="Destination_x0020_Country" DisplayName="Destination Country" />
      <FieldRef ID="4820f860-1512-44ec-bdb0-2c0994d0c6c9" Name="Destination_x0020_City" DisplayName="Destination City" />
      <FieldRef ID="2ae77016-bd02-4bd4-95b3-250df489ebde" Name="Travel_x0020_Desk_x0020_Comments" DisplayName="Travel Desk Comments" />
      <FieldRef ID="2b41e4b5-2bce-4a6d-9167-0d3b38b89917" Name="Approval_x0020_Status" DisplayName="Approval Status" />
    </FieldRefs>
    <DocumentTemplate TargetName="TravelRequest.xsn" xmlns="http://schemas.microsoft.com/sharepoint/" />
    <XmlDocuments xmlns="http://schemas.microsoft.com/sharepoint/">
      <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
        <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
          <Display>DocumentLibraryForm</Display>
          <Edit>DocumentLibraryForm</Edit>
          <New>DocumentLibraryForm</New>
        </FormTemplates>
      </XmlDocument>
    </XmlDocuments>
  </ContentType>
  
</Elements>

3. Now, We got the content type with the references to Fields and Document Template. Since the columns (or fields) referenced in our content type are not default OOTB site columns, We must package the site columns referenced in the content type. So, Right click the Project from server explorer, Choose Add New Item, and then select "Empty Element"
sharepoint 2010 content type deploy
Like the content type, Fields also have schema XML. There are many ways to get Field's XML like using SharePoint Manager, Using PowerShell, etc. Lets use the OOTB way again: Server Explorer.
Deploying Content Types as a Feature
Copy the Field Schema from the Elements.xml of the field object, To the Element.xml file under "Columns" Object, and then delete the newly created Field object from Solution Explorer.

Repeat the above step for all fields referenced in the content type.
Create a Content Type using Features
Finally, the Elements.xml file under "Columns" will look like:
Columns Object's Elements.xml File:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field Type="Text" DisplayName="Traveller Name" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{002acd66-abf3-4cca-9a92-2fe8d93a3de2}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Traveller_x0020_Name" Name="Traveller_x0020_Name" Customization="" />
  <Field Type="User" DisplayName="Project Manager" List="UserInfo" Required="FALSE" EnforceUniqueValues="FALSE" ShowField="ImnName" UserSelectionMode="PeopleOnly" UserSelectionScope="0" Group="Crescent Site Columns" ID="{48d47953-dd68-4a51-8990-768438b908e8}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Project_x0020_Manager" Name="Project_x0020_Manager" Customization="" />
  <Field Type="DateTime" DisplayName="Travel Date" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" Format="DateOnly" Group="Crescent Site Columns" ID="{c600e139-1c03-4524-8ef9-72d8462e3992}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Travel_x0020_Date" Name="Travel_x0020_Date" Customization="" />
  <Field Type="User" DisplayName="Travel Coordinator" List="UserInfo" Required="FALSE" EnforceUniqueValues="FALSE" ShowField="ImnName" UserSelectionMode="PeopleOnly" UserSelectionScope="0" Group="Crescent Site Columns" ID="{e9d07d8f-9066-47ae-9d0e-7249386cde5b}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Travel_x0020_Coordinator" Name="Travel_x0020_Coordinator" Customization="" />
  <Field Type="Text" DisplayName="Origin Country" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{839c026b-15b4-4d81-8c1a-bb7e53be7120}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Origin_x0020_Country" Name="Origin_x0020_Country" Customization="" />
  <Field Type="Text" DisplayName="Origin City" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{737c35ae-0b8a-494d-baf1-dfcf4271ad53}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Origin_x0020_City" Name="Origin_x0020_City" Customization="" />
  <Field Type="Text" DisplayName="Destination Country" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{2489cb17-cace-48bc-939e-438d458d90b0}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Destination_x0020_Country" Name="Destination_x0020_Country" Customization="" />
  <Field Type="Text" DisplayName="Destination City" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{4820f860-1512-44ec-bdb0-2c0994d0c6c9}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Destination_x0020_City" Name="Destination_x0020_City" Customization="" />
  <Field Type="Note" DisplayName="Travel Desk Comments" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" NumLines="6" RichText="TRUE" RichTextMode="FullHtml" IsolateStyles="TRUE" Sortable="FALSE" Group="Crescent Site Columns" ID="{2ae77016-bd02-4bd4-95b3-250df489ebde}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Travel_x0020_Desk_x0020_Comments" Name="Travel_x0020_Desk_x0020_Comments" Customization="" />
  <Field Type="Text" DisplayName="Approval Status" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Crescent Site Columns" ID="{2b41e4b5-2bce-4a6d-9167-0d3b38b89917}" SourceID="{2a4152d0-7cf4-4014-997f-0fce5e803436}" StaticName="Approval_x0020_Status" Name="Approval_x0020_Status" Customization="" />
</Elements> 

4. The next thing we need to do is: Pack the Document template associated with out content type. Add New Item to the project, Choose "Module" and name it. I've named it as "FormTemplate"
Custom Content Type using Visual Studio
Now from Solution Explorer, Right click the Form Template, Add >> Exising Item >> Specify the Form Template to Add.
Provision Cotent Type with document template in Visual Studio
Update the Elements.xml file under "FormTemplate" as below:
FormTemplate Module's Elements.xml file:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="FormTemplate">
    <File Path="FormTemplate\TravelRequest.xsn" Url="_cts/Crescent Travel Request/TravelRequest.xsn" Type="Ghostable" />
</Module>
</Elements>

5. Done, We have the Content Type, Columns and the Document templates referenced by the content type. Now the project structure should look like:
sharepoint 2010 content type feature
Go to the feature designer, Include above three objects to the feature.
sharepoint 2010 content type wsp
Build, Pack and Deploy the Project! That's all!! We are done packaging and deploying content types with document template using Visual Studio 2010.

While its also possible to have a single Elements.xml file for all these artifacts, I've separated them into three for the sake of simplicity!

In this demo, I've selected "Blank SharePoint Project", But you can choose "Content Type" Project and copy paste the Content Type & Fields Schema XML)
Export Import Content Types using Visual Studio

Export Import Content Types with PowerShell:
Here is my another post on Exporting and Importing Content Types using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, March 27, 2013

How to Change Central Administration Port in SharePoint

Changing Central Administration Port in SharePoint isn't frequent task, but you may have to do it in some situations:
  1. Perhaps during SharePoint installation, Central Administration Web site may be established with a random port, and you want to change it now.
  2. It was assigned with a port number which is prone to cause port conflicts, 
  3. Some other programs (such as backup software) wants to use the port assigned to Central Admin 
  4. Your organization's IT Policy doesn't allow to host the site on the particular port, etc.
Anyway, If you want to change central administration port number in SharePoint 2010, there is no web interface available! But we have these methods to change port of central administration:

The simplest way to accomplish this is by using the PowerShell cmdlet
To change central administration port in SharePoint 2010 or in SharePoint 2013, use the PowerShell cmdlet: Set-SPCentralAdministration

Set-SPCentralAdministration -port <Port Number>
Change central administration port in SharePoint 2010
The above cmdlet allows ports between 1023 and 32767 and blocks any other ports (Port 443 is not allowed). You will get "Invalid Port" error message if you try some other port doesn't fall under this criteria.

While the above cmdlet helps change SharePoint 2010 central administration port and for SharePoint 2013, In MOSS 2007 we've the same old Stsadm tool!

Use Stsadm to change Central Admin Port in SharePoint 2007:
If  you still want to use the port which is not supported by the Set-SPCentralAdministration or if you are running SharePoint 2007, you got to use the same old STSADM command line tool.

Stsadm -o setadminport -port <PortNumber>
 How to change SharePoint 2007 central administration port
Once you get "Operation completed successfully." you can access the Central Admin in New port.

Not sure, in which port central admin is hosted? sure, run stsadm.exe -o getadminport command if you want to get the current port of central administration. Both the PowerShell cmdlet and STSADM commands updates everything including IIS Bindings, all the shortcuts.

Re-run SharePoint Product Configuration Wizard
You can also change port by run the SharePoint Product & Technologies Configuration Wizard (Psconfigui.exe)
Change central administration port in SharePoint 2010
If you want to change the URL for SharePoint Central Administration site, Refer: Distribute and Load Balance Central Admin

Technet Reference: Change the Central Administration Web site port number
Want to find which ports are being used by the server? Use "Netstat -a" command in command prompt. This will give you the ports already in use!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, March 26, 2013

Set SharePoint Search Settings (Search Center URL, Scope Dropdown Mode) Programmatically

After migrating SharePoint 2007 sites to SharePoint 2010, we decided to set search center URL to a Enterprise Search center site and scope settings Dropdown mode to use "Show scopes dropdown" for all site collections.

To update search center and search scope dropdown settings in SharePoint sites, We used to go:
  • Site Actions >> Site Settings 
  • Click on "Search Settings" under "Site collection Administration"
  • Set search center URL and search scope dropdown
set sharepoint search center URL programmatically powershell
Update SharePoint Search Settings Programmatically:
Alright, How about new site collections which we are going to create down the line? Well, We used this code in a feature stapler to programmatically set SharePoint search center URL:
   //Read Search Center URL value from Feature.xml
   if (properties.Feature.Properties["SearchCenterURL"] != null)
       {
           string searchCenterURL = properties.Feature.Properties["SearchCenterURL"].Value;
           //Set the Search Center URL
           web.AllProperties["SRCH_ENH_FTR_URL"] = searchCenterURL;
           web.Update();
        }
property segment from Feature.xml file:
  <Properties>
    <Property Key="SearchCenterURL" Value="http://SearchCenter.Crescent.com" />
  </Properties>

Set Search Center URL using PowerShell
To update the Search Settings programmatically, There is no API available, but these values are stored as a part of the property bag of the SPWeb object. For existing sites which are already created prior to deploying this feature, Lets use PowerShell to set search center URL and Search scope dropdown mode:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

$WebAppURL = "http://sharepoint.crescent.com"
$SearchCenterURL= "http://search.crescent.com"

#Iterate through each site in the given web application
Get-SPWebApplication -Identity $WebAppURL | Get-SPSite -Limit ALL | foreach{ 
        $_.RootWeb.AllProperties["SRCH_ENH_FTR_URL"] = $SearchCenterURL
        $_.RootWeb.AllProperties["SRCH_SITE_DROPDOWN_MODE"] = "ShowDD"
        $_.RootWeb.Update()         
        Write-Host "Search settings Updated for "$_.RootWeb.Url -ForeGroundColor DarkGreen
}   

Set SharePoint Search Settings Programmatically using C#:
In an another scenario, I wrote a .net C# console application that does the job of updating search center URL and search scope dropdown mode.
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://sharepoint.crescent.com"));

            foreach (SPSite site in webApp.Sites)
            {
                SPWeb web = site.OpenWeb();

                web.AllProperties["SRCH_ENH_FTR_URL"] = "http://search.crescent.com/pages/";
                web.AllProperties["SRCH_SITE_DROPDOWN_MODE"] =    "ShowDD"       ;
                //web.AllProperties["SRCH_TRAGET_RESULTS_PAGE"] = "http://search.crescent.com/pages/Results.aspx";
                
                web.Update();
                Console.WriteLine ("Updated Search settings for " + web.Url);
                web.Dispose();
                site.Dispose();
            }

Search Scope Dropdown modes:
Below are the valid values you can use for SRCH_SITE_DROPDOWN_MODE
  • ShowDD - Show scopes dropdown
  • ShowDD_DefaultURL - Show, and default to ‘s’ URL
  • ShowDD_DefaultContextual - Show and default to contextual scope
  • ShowDD_NoContextual - Show, do not include contextual scopes
  • ShowDD_NoContextual_DefaultURL - Show, do not include contextual scopes, and default to ‘s’ URL paramete
  • HideScopeDD_DefaultContextual - Do Not Show Scopes Dropdown, and default to contextual scope
  • HideScopeDD - Do not show scopes dropdown, and default to target results page
For Search Scope Dropdown modes, Refer: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.portal.webcontrols.dropdownmodes%28v=office.14%29.aspx

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Configuring BLOB Cache in SharePoint 2010

What is BLOB:
BLOB means Binary Large Object and refers any binary format file that is stored as a single entity  and not converted to text. Usually, BLOB files are of type images, audio/video files.

What is BLOB Cache:
When BLOB types of files are uploaded to a SharePoint site (E.g. Images on a page), they are stored
inside the SQL Server content databases in BLOB data fields. When users request for these files for the first time, SharePoint retrieves them from database, stores the copies in WFEs and from next time, it serves those files from WFEs instead going back to database.

What benefit We'll Get by Enabling BLOB Cache in SharePoint 2010
A file retrieved from Web Front End's File System is much faster, compared with when it retrieved from the database! It helps to improve performance by decreasing the number of requests from SQL Server! It reduces end-user response time too.

Although, it is possible to enable the BLOB cache for all file types, its usually enabled for images, scripts, audio/video media file types and its ideal for Public web sites and sites where most of the users will have read-only permissions. (of course, BLOB could also be a document or spreadsheet even!)

Warning: Do not configure blob cache on collaborative file types such as Microsoft Word Documents! Because: The latest version of the document should be always be retrieved from the database and free from and conflicts. That would cause negative effect!!

How to configure the BLOB cache in SharePoint 2010:
The BLOB cache is configured in the web.config file for each Web application. Since BLOB cache is not enabled by default, it must be manually configured. To configure BLOB cache, we need to modify the web.config file of the WFE server(s). Follow this Step by step instruction to setup blob cache in SharePoint 2010.

1. Log on to SharePoint WFE server(s) as a Administrator

2. Go to Internet Information Services (IIS) Manager.

3. Expand the server, Sites node and then select your target the web application

4. Right-click the web application and click Explore to open the file system directory for the web application.sharepoint 2010 blob cache configuration
5. Open the web.config file in any text editor such as Notepad.

sharepoint 2010 blob cache web config
6. Locate the following line in the web.config file:

By default, BLOB Cache configuration in Web.Config file would be:

<BlobCache location="C:\BlobCache\14" 
       path="\.(gif|jpg|jpeg|bmp|tiff|ico|png|css|js|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|wma|wmv)$" 
            maxSize="10" enabled="false" />

Simply change the enabled property to "true" to enable BLOB cache! SharePoint will  create the folder specified in location parameter and assign folder permissions automatically! To disable BLOB cache in SharePoint 2010, simple revert it back to "false".
sharepoint 2010 blob cache
BLOB Cache Configuration has the following Parameters:
  • location - Is the file system folder where SharePoint server stores cached files.Make sure you select the BLOB cache location on a drive with sufficient disk space!
  • path - Is a lists all file extensions that will be cached. File types are separated by vertical pipe character.
  • maxSize - In GB, disk space that the BLOB cache will occupy. If BLOBs exceeds this limit, SharePoint will delete older items in the cache to make room for newer items.
  • max-Age - In seconds. It tells How long Browser can cache these files without making request to the server. Use it with value: 1814400 (Three Weeks), if you get: HTTP 304 error!
  • enabled - Sets BLOB Cache ON or OFF. Make it "false" to disable BLOB Cache.
XML is case sensitive! so be cautious when making changes to web.config file.

Enable BLOB Cache using PowerShell?
Why not! Web.config file changes can be made with "SPWebConfigModification" class. Lets utilize that to make a web.config change to enable BLOB cache:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Web Application
$WebApp = Get-SPWebApplication "http://sharepoint.crescent.com" 

#Create a web.config modification
$WebconfigMod = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
$WebconfigMod.Path = "configuration/SharePoint/BlobCache"
$WebconfigMod.Name = "enabled"
$WebconfigMod.Sequence = 0
$WebconfigMod.Owner = "BlobCacheModification"
$WebconfigMod.Type = 1
$WebconfigMod.Value = "true"
   
#Apply the web.config change
$WebApp.WebConfigModifications.Add($WebconfigMod)
$WebApp.Update()
$WebApp.Parent.ApplyWebConfigModifications()
 
This will enable BLOB Cache. If you want to disable BLOB cache, just change the Parameter "enabled" to "false". Same method applies for additional parameters such as: Location, MaxSize, etc.

See the BLOB Cache in action:
how to enable blob cache sharepoint 2010

How to Flush(Reset/Clear) BLOB cache in SharePoint 2010
Some times, You may notice your changes don’t appear in the site. All you have to do is: Flush the Cache! Here is the PowerShell to flush the BLOB cache (No GUI to do this!).

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$webApp = Get-SPWebApplication "http://sharepoint.crescent.com"
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
Write-Host "BLOB Cache Flushed for:" $webApp 

Found a CodePlex solution Blob cache manager (haven't tried it but): http://sp2010blobcachemgr.codeplex.com/

Tail: SharePoint 2010 foundation blob cache
BLOB cache is not supported in SharePoint Foundation 2010! This feature is available in SharePoint Server


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, March 25, 2013

Export Import Site Columns with PowerShell

Its a frequent requirement to copy site columns between SharePoint environments, isn't it? Today had a requirement to copy bunch of site columns from development environment to staging environment.

We used to package site columns as a WSP Solution package in such requirements: Create Site Column Feature for SharePoint 2010 ,This time, Lets use PowerShell to Export and Import Site Columns!

PowerShell Script to Export Site columns:
    #Get the Source Web
    $sourceWeb = Get-SPWeb "http://dev.crescent.com"
 
    #Create a XML File to Export Fields
    $xmlFile = "C:\SiteColumns.xml"
    New-Item $xmlFile -type file -force

    #Wrap Field Schema XML inside <Fields> Element 
    Add-Content $xmlFile "`n<Fields>"
 
    #Export All Site Columns of specific Group to XML file
    $sourceWeb.Fields | ForEach-Object {
        if ($_.Group -eq "Crescent Travel Request") {
            Add-Content $xmlFile $_.SchemaXml
        }
    }
    #Closing Wrapper
    Add-Content $xmlFile "</Fields>"
 
    #Dispose the web object
    $sourceWeb.Dispose()

PowerShell Script to Import Site Columns from XML:
  
  #Get the Target Web
  $TargetWeb = Get-SPWeb "http://test.crescent.com"
 
  #Get XML file exported
  [xml]$fieldsXML = Get-Content("C:\SiteColumns.xml")
 
  #Loop Through Each Field
  $fieldsXML.Fields.Field | ForEach-Object {
  #Check if the target web has the field already!
  if ($TargetWeb.Fields.ContainsField( $_.Name) -Eq $false){ 
   #Add Site column to Target Web
   $TargetWeb.fields.AddFieldAsXml($_.OuterXml)
  }
}
Thanks Phil for the idea: http://get-spscripts.com/2011/01/export-and-importcreate-site-columns-in.html

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, March 24, 2013

Clicking Document Type Icon does not open document, Selects the Row Instead

Issue: SharePoint 2010 clicking type icon does not open document! Clicking Type Icon Selects the Row Instead of Opening the Document!!

Fix: Its a known issue! Microsoft released a KB article: http://support.microsoft.com/kb/2457975
Clicking Type Icon Selects the Row Instead of Opening the Document
In short: Copy Paste the below code as a file named: "fldtypes_docicon.xsl" and save it under 14 Hive folder of all WFEs:  \14\template\layouts\XSL\  and do an IISReset!

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal" ddwrt:oob="true">
    <xsl:output method="html" indent="no"/>
  
  <xsl:template ddwrt:dvt_mode="body" match ="FieldRef[@Name='DocIcon']" mode="Computed_DocIcon_body">
    <xsl:param name="thisNode" select="."/>
    <xsl:param name="folderUrlAdditionalQueryString" select="''"/>
    <xsl:choose>
      <xsl:when test="$thisNode/@FSObjType='1'">
        <xsl:variable name="alttext">
          <xsl:choose>
            <xsl:when test="starts-with($thisNode/@ContentTypeId, &quot;0x0120D5&quot;)">
              <xsl:value-of select="$thisNode/../@itemname_documentset"/>: <xsl:value-of select="$thisNode/@FileLeafRef"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$thisNode/../@listformtitle_folder"/>: <xsl:value-of select="$thisNode/@FileLeafRef"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:variable name="mapico" select="$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapico"/>
        <xsl:variable name="folderIconPath">
          <xsl:call-template name="GetFolderIconSourcePath">
            <xsl:with-param name="thisNode" select="$thisNode"/>
          </xsl:call-template>
        </xsl:variable>
        <!-- This is a folder -->
        <xsl:choose>
          <xsl:when test="$RecursiveView='1'">
            <img border="0" alt="{$alttext}" src="{$folderIconPath}" />
            <xsl:choose>
              <xsl:when test="$thisNode/@IconOverlay != ''">
                <img src="/_layouts/images/{$thisNode/@IconOverlay.mapoly}" class="ms-vb-icon-overlay" alt="" title="" />
              </xsl:when>
            </xsl:choose>
          </xsl:when>
          <xsl:otherwise>
            <xsl:variable name="FolderCTID">
              <xsl:value-of select="$PagePathFinal" />RootFolder=<xsl:value-of select="$thisNode/@FileRef.urlencode" /><xsl:value-of select="$ShowWebPart"/>&amp;FolderCTID=<xsl:value-of select="$thisNode/@ContentTypeId" />&amp;View=<xsl:value-of select="$View"/><xsl:value-of select="$folderUrlAdditionalQueryString"/>
            </xsl:variable>
            <a href="{$FolderCTID}" onmousedown ="VerifyFolderHref(this, event, '{$thisNode/@File_x0020_Type.url}','{$thisNode/@File_x0020_Type.progid}','{$XmlDefinition/List/@DefaultItemOpen}', '{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon}', '{$thisNode/@HTML_x0020_File_x0020_Type}', '{$thisNode/@serverurl.progid}')"
               onclick="return HandleFolder(this,event,&quot;{$PagePathFinal}RootFolder=&quot; + escapeProperly(&quot;{$thisNode/@FileRef}&quot;) + '{$ShowWebPart}&amp;FolderCTID={$thisNode/@ContentTypeId}&amp;View={$View}{$folderUrlAdditionalQueryString}','TRUE','FALSE','{$thisNode/@File_x0020_Type.url}','{$thisNode/@File_x0020_Type.progid}','{$XmlDefinition/List/@DefaultItemOpen}','{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon}','{$thisNode/@HTML_x0020_File_x0020_Type}','{$thisNode/@serverurl.progid}','{$thisNode/@CheckoutUser.id}','{$Userid}','{$XmlDefinition/List/@ForceCheckout}','{$thisNode/@IsCheckedoutToLocal}','{$thisNode/@PermMask}');">
              <img border="0" alt="{$alttext}" title="{$alttext}" src="{$folderIconPath}" />
              <xsl:choose>
                <xsl:when test="$thisNode/@IconOverlay != ''">
                  <img src="/_layouts/images/{$thisNode/@IconOverlay.mapoly}" class="ms-vb-icon-overlay" alt="" title="" />
                </xsl:when>
              </xsl:choose>
            </a>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:when>
      <xsl:otherwise>
        <xsl:choose>
          <xsl:when test="$IsDocLib">
            <a onfocus="OnLink(this)" href="{$thisNode/@FileRef}" onmousedown="return VerifyHref(this,event,'{$XmlDefinition/List/@DefaultItemOpen}','{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon}','{$thisNode/@serverurl.progid}')"
   onclick="return DispEx(this,event,'TRUE','FALSE','{$thisNode/@File_x0020_Type.url}','{$thisNode/@File_x0020_Type.progid}','{$XmlDefinition/List/@DefaultItemOpen}','{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon}','{$thisNode/@HTML_x0020_File_x0020_Type}','{$thisNode/@serverurl.progid}','{$thisNode/@CheckoutUser.id}','{$Userid}','{$XmlDefinition/List/@ForceCheckout}','{$thisNode/@IsCheckedoutToLocal}','{$thisNode/@PermMask}')">
              <xsl:choose>
                <xsl:when test="not ($thisNode/@IconOverlay) or $thisNode/@IconOverlay =''">
                    <xsl:choose>
                        <xsl:when test="not ($thisNode/@CheckoutUser.id) or $thisNode/@CheckoutUser.id =''">
                            <img border="0" alt="{$thisNode/@FileLeafRef}" title="{$thisNode/@FileLeafRef}" src="/_layouts/images/{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapico}"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:variable name="alttext"><xsl:value-of select="$thisNode/@FileLeafRef"/><xsl:text disable-output-escaping="yes" ddwrt:nbsp-preserve="yes">&#10;</xsl:text><xsl:value-of select="$thisNode/../@managecheckedoutfiles_header_checkedoutby"/>: <xsl:value-of select="$thisNode/@CheckoutUser.title"/></xsl:variable>
                            <img border="0" alt="{$alttext}" title="{$alttext}" src="/_layouts/images/{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapico}" />
                            <img src="/_layouts/images/checkoutoverlay.gif" class="ms-vb-icon-overlay" alt="{$alttext}" title="{$alttext}" />                            
                        </xsl:otherwise>
                    </xsl:choose>                  
                </xsl:when>
                <xsl:otherwise >
                    <img border="0" alt="{$thisNode/@FileLeafRef}" title="{$thisNode/@FileLeafRef}" src="/_layouts/images/{$thisNode/@IconOverlay.mapico}" />
                  <img src="/_layouts/images/{$thisNode/@IconOverlay.mapoly}" class="ms-vb-icon-overlay" alt="" title="" />
                </xsl:otherwise>
              </xsl:choose>
            </a>
          </xsl:when>
          <xsl:otherwise>
            <img border="0" src="/_layouts/images/{$thisNode/@HTML_x0020_File_x0020_Type.File_x0020_Type.mapico}">
              <xsl:attribute name="alt">
                <xsl:value-of select="$thisNode/@Title"/>
              </xsl:attribute>
              <xsl:attribute name="title">
                <xsl:value-of select="$thisNode/@Title"/>
              </xsl:attribute>
            </img>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  
</xsl:stylesheet>




You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, March 20, 2013

SharePoint 2010 Content Editor Web Part Hidden property is Disabled

Found a interesting issue today. Wanted to place some CSS code in Content Editor Web Part (CEWP) and hide it, so that it won't appear to end-users. I added a content editor web part, Placed some CSS code, went to web part properties, oops! Hidden property under Layout is disabled (greyed out)!!
content editor web part Layout hidden property is disabled
SharePoint web part hidden disabled
Cause: For some reasons, SharePoint doesn't allow us to hide web parts on publishing pages! So Content Editor Web Part's Layout hidden property is disabled!!

Workaround:
Here is the workaround to fix SharePoint 2010 web part hidden grayed out: Just Append  ToolPaneView=2 to the URL to open the page in Edit mode. E.g. http://sharepoint.crescent.com/sitepages/home.aspx?ToolPaneView=2

This opens Add Web Parts Pane, from there we can add new CEWP to bottom zone of the page (Verified in SharePoint 2010 web part hidden property is not greyed out this time!) and  hide the web part with out any issue! 
sharepoint web part hidden disabled



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


"There has been an error creating the personal site. Contact your site administrator for more information" - SharePoint My Site Creation Error

When end-user tries to create My sites by clicking "My Content" link for the first time, They encountered this error message:
"There has been an error creating the personal site. Contact your site administrator for more information"
There has been an error creating the personal site. Contact your site administrator for more information.

Troubleshooting:
1. Make sure User Profile Service Application & My Sites configuration is proper. Verify My Site Host Web Application is created with a Top level site collection of "My Site Host" Site Template.

2. Make sure Self Service Site creation is enabled for My site Host web application. Go to: Central Administration >> Application Management >> Manage Web Applications >> Select the My Site Host Web Application >> Click on "Self-Service Site Creation" from Ribbon >> Set it to "On". Otherwise, you will receive this error: "Your personal site cannot be created because Self-Service Site Creation is not enabled. Contact your site administrator for more information."
Your personal site cannot be created because Self-Service Site Creation is not enabled. Contact your site administrator for more information.


3. Make sure "personal" wildcard inclusion Managed path is added for My site host web application.
otherwise, you will get an error message: "Your personal site cannot be created because the managed path personal has not been created for this site. Contact your site administrator for more information."
Your personal site cannot be created because the managed path personal has not been created for this site. Contact your site administrator for more information.

4. Try Changing My site name format by going to: User Profile Service Application >> My Site Settings >> Setup My Sites >> Site Naming Format >> click either User name (resolve conflicts by using domain_username) or Domain and user name (will not have conflicts).

5. Make sure "Use Self-Service Site Creation" is enabled under My site host web application's User Permissions.
use self-service site creation in web application user permissions


6. Make sure the application pool of my site  web application is in Farm administrator group. Verify its a domain account and able to access the target domain.

7. Make sure "Create Personal Site" permission is enabled for "All authenticated Users" in User Profile Service Application's "Manage User Permissions"
Create Personal Site permission for All authenticated Users

8. Go to User Profile Service Application >> click on Setup My Sites under My Site Settings  >> Make sure Personal Site Location is set to "Personal" (which we verified in step 3)
sharepoint my site personal site location

9. In an another case: Found Event IDs 6141 and 5187 logged in Event Log.
Event ID 6141
The site /personal/domain_user could not be created.  The following exception occurred: Your changes could not be saved because this SharePoint Web site has exceeded the storage quota limit.
You must save your work to another location.  Contact your administrator to change the quota limits for the Web site..

Event ID 5187
My Site creation failure for user 'domain\user' for site url 'http://mysite.crescent.com/personal/domain_user'. The exception was: Microsoft.Office.Server.UserProfiles.PersonalSiteCreateException:

A failure was encountered while attempting to create the site. ---> Microsoft.SharePoint.SPException: Your changes could not be saved because this SharePoint Web site has exceeded the storage quota limit. You must save your work to another location.  Contact your administrator to change the quota limits for the Web site. ---> System.Runtime.InteropServices.COMException (0x80070718):
<nativehr>0x80070718</nativehr><nativestack></nativestack>Your changes could not be saved because this SharePoint Web site has exceeded the storage quota limit.
You must save your work to another location.  Contact your administrator to change the quota limits for the Web site.

Fix:
Check the Quota Template Limits: Verified "Personal" Quota Template has been set in My site web application's General Settings. To check the Personal Quota Template values, Navigated to: Central Admin >> Application Management >> Specify Quota Templates >> Personal >> Storage Limit values for maximum and warning was: 1 MB!!! (Not sure why!) I increased them to 100 MB and fixed this issue.

My Sites troubleshooting - Technet
http://technet.microsoft.com/en-us/library/gg750250%28v=office.14%29.aspx

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, March 18, 2013

Show Quick Launch in SharePoint 2010 Web Part Pages

By default, SharePoint 2010 Web part pages don't have quick launch navigation! Web part page missing quick launch in SharePoint 2010. 
show quick launch sharepoint web part page
show quick launch in SharePoint web part page
Show quick launch SharePoint 2010 web part page:
We can bring it by editing web part page. Just Edit the webpart page in the SharePoint Designer 2010 Advanced mode and remove the following code (As same in SharePoint 2007):
add quick launch to sharepoint web part page
<asp:Content ContentPlaceHolderId="PlaceHolderNavSpacer" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server"></asp:Content>
sharepoint 2010 quick launch missing from web part page

In SharePoint 2010 you have to also remove the following CSS code:
<style type="text/css">

body #s4-leftpanel
{
display:none;
}
.s4-ca

{
margin-left:0px;
}
</style>
sharepoint display quick launch web part page
Save the page! This will bring Quick launch bar again!! Here is the result: quick launch on SharePoint 2010 web part page.
sharepoint 2010 add quick launch menu to web part page
This solves the issue of SharePoint 2010 quick launch missing from web part page. Here is my SharePoint 2007 version of this post: SharePoint 2007 Quick Launch (left navigation) Missing in Web part pages - Solutions

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, March 16, 2013

How to Connect to a Specific Web Front End Server in SharePoint Farm

A typical SharePoint farm may contain more than one web front end servers - load balanced. When you hit the SharePoint site URL, say: http://portal.crescent.com, it hits the load balancer first. Load balancer decides to which web front end server this request needs to be transferred based on server load and other load balancing algorithms. Here is a nifty trick to hit specific WFE, bypassing load balancer in SharePoint farm.

Connect to a Specific WFE Server in SharePoint with HOST file Edit:
  • Go to "C:\WINDOWS\system32\drivers\etc" in your local machine
  • Open the "HOST" file in notepad.
  • Add an entry at the end of the file with: WFE IP and SharePoint site's Host header. 
    • E.g. 10.129.150.25 extranet.crescent.com
      How to Hit a Specific Web Server in SharePoint Farm
  • Save and close the file.
  • Clear your browser cache and reopen the site.
Now you should get responses from the specified web front end server. BTW, Web Front End Server (WFE) is the one with IIS Web sites running.

Add a Binding to SharePoint Web Application in IIS:
Alternatively, you can add an additional binding to your SharePoint web application and hit that URL from your local machine. Say, You have a SharePoint web application: Intranet.Crescent.com which has port 80 and Port 443 bindings on a web server: Abz-SPS2013-V1. Now,
  • Go to IIS >> Expand Sites >> Pick your web app >> Click on Bindings >> Add a binding. E.g. Type: HTTP, IP: All Unassigned, Port: 8888. 
  • Add an alternate access mapping with the new URL to complete.
Now you can hit: http://Abz-SPS2013-V1:8888/ from your local machine!

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Add User to SharePoint Group using PowerShell

Requirement: Add user to SharePoint Group using PowerShell! We've site collections grouped by managed paths such as "Teams", "Projects". Got a requirement to add a user to Members group of all sites under a particular managed path.

How to Add an User to SharePoint Group?
Adding an user to any SharePoint group is quite simple. Login as a Site owner, Open the SharePoint site and:
  • Click on "Site Settings Gear" Icon from SharePoint site
  • Click on "People and Groups" link under Users and Permissions
  • Pick the Relevant group from Left navigation
  • Click on "New" and choose "Add Users"
  • Enter the Name of the user, Optionally select "Send an email invitation" checkbox and click on "Share" button.
    Add User to SharePoint Group using PowerShell
PowerShell script to add user to Groups in SharePoint:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site path Variable
$SitesPath="http://inside.crescent.com/projects/*" 
$UserAccount="i:0#.w|Crescent\DavidP"

#Get all sites under the specific managed path
$SitesColl = Get-SPSite $SitesPath -limit All 

Foreach($site in $SitesColl)
{
    #Get the default members group
    $MembersGroup = $Site.RootWeb.AssociatedMemberGroup

    #To get a particular group, use: $group = $web.SiteGroups[GroupName];
    
    #Get the User Object
    $user = $web.EnsureUser($UserAccount)
 
    #Add User to the Group
    $MembersGroup.AddUser($user)

    Write-Host "User Added to the Members group of: $($Site.url)"  
}  

Related Post: How to Add User To SharePoint Site Group Programmatically

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, March 15, 2013

Create New Web Application in SharePoint 2013 using PowerShell

To Create new web application in SharePoint 2013, head on to SharePoint 2013 Central Administration site. Navigate to:
  • Application Management >> Manage web applications
  • Click on "New" button from the ribbon
  • Fill-out the details for your new web application. Such as: Web and click on "Create" to create a web application in SharePoint 2013.
    powershell script to create web application in sharepoint 2013
Create Web Application in SharePoint 2013 using PowerShell:
Here is my PowerShell script to create web application in SharePoint 2013:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Define Variables for Web Application Creation
$WebAppName = "Crescent Portal"
$HostHeader = "Portal.Crescent.com"
$WebAppURL = "http://"+$HostHeader
$WebAppPort = 80
$ContentDBName = "SP13_Content_Portal"
$AppPoolName = "Portal AppPool"
$AppPoolAccount = "Crescent\SP_Farm"
$AppPooPassword = "<<Password>>"

#Authentication Provider
$AuthProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication -DisableKerberos

#Create new Managed Account
$SecurePassword = ConvertTo-SecureString -String $AppPooPassword -AsPlainText -Force
$cred = new-object -typeName System.Management.Automation.PsCredential -argumentlist $AppPoolAccount,$SecurePassword
New-SPManagedAccount -Credential $cred

#Create new Web Application
New-SPWebApplication -name $WebAppName -port $WebAppPort -hostheader $HostHeader -URL $WebAppURL -ApplicationPool $AppPoolName -ApplicationPoolAccount (Get-SPManagedAccount $AppPoolAccount) -AuthenticationMethod NTLM -AuthenticationProvider $AuthProvider -DatabaseName $ContentDBName
Lets make use of an existing managed account this time:
$AuthProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication -DisableKerberos
New-SPWebApplication -Name "Crescent Portal" -Port 80 -HostHeader "portal.crescent.com" -DatabaseName "SP16_CrescentPortal_Content" -URL "http://portal.crescent.com" -ApplicationPool "Crescent Portal AppPool" -ApplicationPoolAccount (Get-SPManagedAccount "Crescent\Sp2016_Service") -AuthenticationProvider $AuthProvider
How about SSL Enabled Web Application?
$AuthProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication -DisableKerberos
New-SPWebApplication -Name "Crescent Internet" -ApplicationPool "Crescent Internet AppPool" -ApplicationPoolAccount (Get-SPManagedAccount "Crescent\SPS2016_AppPool") -URL "https://crescent.com" -Port 443 -HostHeader "crescent.com" -DatabaseName "SP16_CrescentInternet_Content01" -Path "C:\Crescent_Internet" -SecureSocketsLayer -AuthenticationProvider $AuthProvider

This creates a new web application using PowerShell for SharePoint 2010 or SharePoint 2013. But wait! You are not yet done. You got to create the root site collection for the web application. If you try to browse to the web application without creating top-level site collection, you'll get "HTTP 404" error!

Create Top-Level Site Collection with PowerShell:
#Create Top-Level Site collection in SharePoint 2013
$SiteURL="http://portal.crescent.com"
$SiteName="Crescent Portal"
$SiteOwner="Crescent\SP_Farm"
$SiteTemplate="STS#0"

#Create new Site collection
New-SPSite –url $SiteURL -Name $SiteName -OwnerAlias $SiteOwner -Template $SiteTemplate

Although this script is written to create web application with PowerShell for SharePoint 2013, It can be also used in creating a web application for SharePoint 2010 too.

SharePoint 2013 PowerShell to create web application in classic mode:
Just leave the AuthenticationProvider parameter in the above script to create new web application in Classic mode.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, March 14, 2013

Remove All Users from SharePoint Group using PowerShell

PowerShell script to remove all user from a SharePoint group programmatically:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site collection URL 
$SiteUrl="http://operations.cloudservices.com" 
$GroupName = "Operation Managers"

#get the Root Web
$web = Get-SPWeb $SiteUrl

#Get the Group
 $Group = $Web.sitegroups | Where-Object {$_.Name -eq $GroupName}

  if($Group -ne $null)
  {
        $GroupUsers = $Group.Users
        foreach ($User in $GroupUsers)
        {
            #powershell remove all users from sharepoint group

            $Group.RemoveUser($User)
            write-host "Removed User from Group:" $User
        } 
   }



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, March 13, 2013

How to Edit SharePoint Survey "All Responses" View

By default, SharePoint Survey's "All Responses" view shows "View Response", "Created By", "Modified", "Completed" columns. There was a requirement to add one of the Survey answer to the view for easier categorization and filter. Unfortunately, There is no direct provision to edit Survey views as we edit any other list/library's view.

Typical, any edit view page goes like this: http://sharepoint-site/_layouts/ViewEdit.aspx?List={GUID OF THE LIST}&View={GUID OF THE VIEW}

So, What we need? Just List ID & View ID. That's it!

How to Get List GUID:
To Get Survey List ID: Go to "Settings >> Survey Settings" from List toolbar. Now, Right click any of the settings links, such as: Rating Settings or Validation Settings, etc and select "copy Shortcut" to Get the List ID. You will something similar to: http://sharepoint.crescent.com/_layouts/RatingsSettings.aspx?List={502aa2ee-8127-4929-ba58-c9b64ea77a2d} . So my survey list ID is: {502aa2ee-8127-4929-ba58-c9b64ea77a2d}

How to View GUID:
To Get View GUID: Go to view source of the All Responses page, Search for "View=" and copy the View's GUID

Here, I got something like: View={9B271D35-9428-4F8E-BB24-E10CB6EF4771}

Now, we've got the List ID and View ID. Hit this URL in the browser to get Edit View Page for All Responses!
http://sharepoint.crescent.com/_layouts/ViewEdit.aspx?List={502aa2ee-8127-4929-ba58-c9b64ea77a2d}&View={9B271D35-9428-4F8E-BB24-E10CB6EF4771}

It took me to normal view edit page, where I was able set filters, group and add any survey questions as columns.
Edit SharePoint Survey "All Responses" View
Update: Lately, Found an another shortcut! From "All Responses" page, Go to: Site Actions >> Edit Page >> Edit Survey Web Part >> Edit the current View to get the edit view page!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, March 12, 2013

Create a Scheduled Task for PowerShell Script with Windows Task Scheduler

PowerShell is really a game changer for repeatable processes, isn't it? We've a PowerShell script to generate report on SharePoint content databases size growth SharePoint Content Databases Size - Storage Report, We used to run it on first day of every Month on SharePoint server to generate report.

Why don't we automate it with Windows Task scheduler? Sure! Lets create a scheduled task for PowerShell script with Windows task scheduler in Windows Server 2008/2012 R2. How to schedule a PowerShell script using Windows task scheduler?

How to Create a Scheduled Task for PowerShell Script with Windows Task Scheduler
Here is how you can create Scheduled Tasks manually:

1. Start >> Administrative Tools >> Task Scheduler.  From Actions menu click on "Create a Basic Task"
windows task scheduler run powershell script
2. Give it a Name & Description Say: Content Databases Report, and click "Next"
windows task scheduler powershell script 
3. Select the interval you want to run the program. In my case, I chose "Monthly"
powershell script task scheduler windows 2008 r2

4. Specify the Months, Days in which the script to run. I've selected "All Months" and Day 1
schedule powershell script using task scheduler

5. In Action Tab, Select "Start a program" option button. Click Next
task scheduler to run powershell script  
6. In Start a Program Tab:
  • In Program/script, Enter: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • In Arguments, Enter the path of the script. Say: D:\Scripts\ContentDatabaseReport.ps1
  • In Start in, Enter the path where the script is located. say: D:\Scripts
powershell script scheduled task parameters
You must specify value for Start-in field, even though its optional. This is why because, if no value specified there, PowerShell will create the output in "C:\Windows\System32" directory.

7. Select the check box, "Open the Properties dialog for this task when I click Finish" and click Finish button.

8. Now, in the properties dialog, under the General tab, Make sure that the "Run when user is logged on or not" and "Run with highest privileges" check boxes are selected.
You will get a login prompt on clicking "OK" button. Enter the User Name & Password in which the task runs.

Create Tasks in Task Scheduler Command Line:
We can create scheduled task with the command line tool schtasks too!
schtasks /create /TN "Content Database Report" /SC monthly /mo 1 /ST 00:00 /RU "Domain\UserName" /RP "Password" /RL "HIGHEST" /TR "PowerShell D:\Scripts\ContentDatabaseReport.ps1" 

This will set the options "Run with highest privileges" and "Run whether the user is logged on or not"  for the Scheduled Task.

To Run the Scheduled Task on-demand:
  • Right click on the created task and choose Run.
  • switch over to the script file location and verify new report has been generated as an output from the script.
run scheduled task on demand

That's all! We've created a task in windows task scheduler for PowerShell script!

Here is how you can Run PowerShell Script from Batch files: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -command "<Your PowerShell Script Location>"

PowerShell script with parameters in scheduled task:
Say, We've a Parameter "$WebAppURL" in our PowerShell script:

Param(
       [parameter(Mandatory=$true)] $WebAppURL
     )
   
 # We'll trigger the script as:  .\StorageReport "http://sharepoint.crescent.com"

So in Task scheduler, Add arguments(optional), Enter: d:\scripts\StorageReport "http://sharepoint.crescent.com"

When there are multiple parameters, you can separate them by giving parameter name as key. such as:

Param(
       [parameter(Mandatory=$true)] $WebAppURL,
       [parameter(Mandatory=$true)] $OutPut
     )

# We trigger it as: StorageReport -WebAppURL "http://sharepoint.crescent.com" -output "d:\Reports\StorageReport.csv"

Create Scheduled Tasks with PowerShell:
From PowerShell 3.0 (Windows Server 2012 R2) onwards , We've a new cmdlets to create and manage Scheduled Tasks! Here is an example:
#Variables
$TaskName = "Audit Large Lists"
$username ="Crescent\SP13_FarmAdmin" 
$password ="Password Here"

#Create Scheduled Task
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "E:\Scripts\AuditLists.ps1"
$Trigger = New-ScheduledTaskTrigger -Daily -At 1am
$ScheduledTask = New-ScheduledTask -Action $action -Trigger $trigger  

Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User $username -Password $password  



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...