Tuesday, December 29, 2015

Set value to an Managed Metadata field


Managed Metadata is an extraordinary feature in SharePoint career path. It helps organization to structure all unstructured data and it is easy to use them.

The managed metadata field can be associated with List, document library.. etc

Also it has a feature that not used values(terms) can be deprecated instead deleting them permanently from centralized location. The deprecated terms can be used for future tracking. Normally if any MMD field associated with a TermSet then user can see only Enabled terms in the TermStore tree. It is a out-of-the-box feature that SharePoint will apply filter and display only enabled terms to the end user.

But deprecated term also can be assigned to a MMD field if necessary based on business need using Server Object model.

Find the code sample below which assign value to MMD field with enabled and deprecated term.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace SetMMD_Field {

    class Program {
        static void Main(string[] args) {
            SPList lst = null; ;
            
            using (SPSite site = new SPSite(@"http://kmstechs/")) {
                using (SPWeb web = site.RootWeb) {
                  //  SPSecurity.RunWithElevatedPrivileges(delegate() {
                        lst = web.Lists["SK_Test"];
                        SPListItem oSPListItem = lst.Items.Add();
                        oSPListItem["Title"] = "Hello SharePoint";
                        TaxonomySession session = new TaxonomySession(site);

                        TaxonomyField taxfield = oSPListItem.Fields["Invalid_MMD"] as TaxonomyField;

                        Term InvalidTerm = session.GetTerm(new Guid(@"7dba48a0-89fa-4203-a265-e49ca3752ab7"));
                        string taxFieldInternalname1 = oSPListItem.Fields["Invalid_MMD"].InternalName;
                        oSPListItem[taxFieldInternalname1] = InvalidTerm.Name + "|" + InvalidTerm.Id.ToString();
                        taxfield.SetFieldValue(oSPListItem, InvalidTerm);

                        TaxonomyField taxfield2 = oSPListItem.Fields["Valid_MMD"] as TaxonomyField;

                        Term validTerm = session.GetTerm(new Guid(@"dca67b77-e4f4-4630-8785-e22518945ecc"));
                        string taxFieldInternalname2 = oSPListItem.Fields["Valid_MMD"].InternalName;
                        oSPListItem[taxFieldInternalname2] = validTerm.Name + "|" + validTerm.Id.ToString();
                        taxfield2.SetFieldValue(oSPListItem, validTerm);

                        oSPListItem.Update();

                   // });
                }
            }

            Console.WriteLine("done");

            Console.ReadKey(true);
        }
    }
}

Enjoy working with SharePoint :-)

Monday, December 21, 2015

Add more properties (metadata) to SharePoint Folder

Add more properties (metadata) to SharePoint Folder

Folder is an content type in SharePoint and it being used for categorizing OR grouping specified items/documents OR Applying Explorer view on SharePoint contents.  The folder content type provide explorer view if user wanted to navigate an document among many.

But the Folder content type is sealed in SharePoint and it will not allow the administrator to amend folder’s properties. Instead we can create a new custom content type by inheriting base folder content type and add new properties that are needed.

Below are the steps to create new folder content type with additional properties (metadata)


  1. Login to the  SharePoint site where you need folder with additional properties
  2. Navigate to Site Actions -->  Site Settings
  3. Click on Site Content Types
  4. Click on Create link
  5. Enter new content type name 
  6. Set the parent content type group as “Folder Content Types”
  7. Set the parent content type to “Folder”
  8. Provide new group name for new content type. Or else the new content type will be displayed under Custom content type group.
  9. Click OK button
  10. Click on New column and provide the column details 
  11. Add the custom content type where ever you need and update the views with new folder properties.

Note: Make sure allow custom content type option is enabled in the document library advances settings to add custom content type.


Wednesday, May 13, 2015

SharePoint 2013 server is not allowing 32bit application

I got a task to setup SharePoint 2013 production environment. Simply I was told by customer that we need SharePoint 2013 setup in single server with Search and Excel services.  I have download AuthoSPInstaller from here and updated the configuration values as per customer need. The AutoSPIntstaller reduce most of my time on installing pre-requisites and SharePoint installation. I will write all in details in separate post.

Post SharePoint 2013 installation, Customer is happy with the configuration and they started using all SharePoint 2013 features. After a week of time customer planned to use same SharePoint server to deploy some 32bit .Net web services. But the deployment was not successful as the SharePoint server not to ready allow any 32bit application.

The issue reported to me then I have investigated the issue and found the problematic place. The global module web config does not have any  property to allow 32bit application. At same time I found some more 32bit related error in event viewer.

The Module DLL 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\isapi\spnativerequestmodule.dll' could not be loaded due to a configuration problem. The current configuration only supports loading images built for a x86 processor architecture. The data field contains the error number. To learn more about this issue, including how to troubleshooting this kind of processor architecture mismatch error, see http://go.microsoft.com/fwlink/?LinkId=29349.

New ISAPI module in SharePoint 2013 stopping our 32 site from loading. Probably part of the new Request Management piece in SP2013 (http://blogs.technet.com/b/speschka/archive/2012/09/14/working-with-request-manager-in-sharepoint-2013.aspx)

I  have verified global section in “ ApplicationHost.config” file which present at %systemroot%\system32\inetsrv\config

Alternatively command prompt can be used list global module section from “ ApplicationHost.config”

  1. Open command prompt
  2. Change directory to %systemroot%\system32\inetsrv (e.g. c:\windows\system32\inetsrv)
  3. Used below command to list all config details.

         appcmd list config  /section:globalmodules

Check the property in SharePoint Native Request Module

< add name="SPNativeRequestModule" image="C:\Program Files\Common Files\Micro
soft Shared\Web Server Extensions\15\isapi\spnativerequestmodule.dll" />

If precondition property not available then update property using below command to enable the server to allow 32bit application.

appcmd.exe set config -section:system.webServer/globalModules /[name='SPNativeRequestModule'].preCondition:integratedMode,bitness64

Once the above command executed successfully then the property of SharePoint Native Request Module will be updated as below.

   
< add name="SPNativeRequestModule" image="C:\Program Files\Common Files\Micro
soft Shared\Web Server Extensions\15\isapi\spnativerequestmodule.dll" preConditi
on="integratedMode,bitness64" />  

Restart the server and verify 32 bit application.

Good luck :-)





Tuesday, May 5, 2015

Retrieve Secure Store Service credentials in SharePoint 2010/13


There are some actions to be taken care manually in SharePoint 2010/13. If any service account password is updated then the same password can be updated using managed accounts which get updated in all the places in same SharePoint Farm. But if SharePoint using any services from other farm then the password will not be updated and create new issue while access the service from other farms.

The account details will be stored in secure store services. To update the new password, SharePoint Administrator should aware or refer any document to find services and currently using credentials. SharePoint 2010 service application does not have any user interface to identify those details quickly. In such case below PowerShell script can be used.

$serviceCntx = Get-SPServiceContext -Site http://kmsnet:12345/
$sssProvider = New-Object Microsoft.Office.SecureStoreService.Server.SecureStoreProvider
$sssProvider.Context = $serviceCntx
$marshal = [System.Runtime.InteropServices.Marshal]

try
{
$applicationlications = $sssProvider.GetTargetApplications()
foreach ($application in $applicationlications)
{
Write-Output "`n$($application.Name)"
Write-Output "$('-'*50)"
try
{
$sssCreds = $sssProvider.GetCredentials($application.Name)
foreach ($sssCred in $sssCreds)
{
$ptr = $marshal::SecureStringToBSTR($sssCred.Credential)
$str = $marshal::PtrToStringBSTR($ptr)
Write-Output "$($sssCred.CredentialType): $($str)"
}
}
catch
{
Write-Output "(Something went wrong) - Error getting credentials!"
}
Write-Output "$('-'*50)"
}
}

catch
{
Write-Output "(Something went wrong) - Error getting Target Applications."
}

$marshal::ZeroFreeBSTR($ptr)

Tuesday, November 25, 2014

Increase List items threshold in SharePoint

We think a lot if want to increase the list view items threshold for the web application because it will be applied to all the site collections that running under the same web application. When we work with list there are many question comes in our mind.

1. SharePoint list supports 3 million item in a list but if threshold limit is crossed the the user will not be able perform many operation including OOTB (Additional filter on list view, grouping, adding new filed or updating existing field). How to avoid such situation?

2. How to increase the threshold for a single list or single web(sub site)?

3. Are there any possibilities for viewing all items/ navigating to all items without any trouble?

4. How majorly system performance impacted if list view threshold increase for the total web application? Are there any best practices?

5. Why Server object model not returning all items from a view when fetching items from specific view?

6. Why OOTB view query is overriding custom CAML query when fetching specific view with CAML query?

and there are more question may arise if you dig further on SharePoint list.

But we can increase the List threshold for a specific list using server object mode / PowerShell scripts.

Server Object Model

using(SPSite site = new SPSite(@"http://kmsnet:5050"))
{
   foreach(SPWeb web in site.AllWebs)
   {
     web.AllowUnsafeUpdates=true;
     SPList lst=web.Lists.TryGetList("MyList");
     if(lst != null)
     {
        lst.EnableThrottling=false;
        lst.Update();       
     }
     web.Update();
     web.AllowUnsafeUpdates=false;
     web.Dispose();
   }
}

PowerShell

Add-PSSnapin Microsoft.SharePoint.PowerShell #-ErrorAction SilentlyContinue

$site = Get-SPSite -Identity "http://kmsnet:5050/"

foreach($web in $site.AllWebs)
{
   $web.AllowUnsafeUpdates = $True;
   $list=$web.Lists.TryGetList("MyList");
   if($list -ne $null)
   {
        $list.EnableThrottling = $False;
        $list.Update();
        Write-Host "List Updated in web" $web.Title
   }
   $web.Update();
   $web.AllowUnsafeUpdates = $False;
   $web.Dispose()
}
$site.Dispose();

Wednesday, November 19, 2014

Caching techniques in SharePoint

SharePoint Server 2010 provides three types of caches that help improve the speed at which Web pages load in the browser.

1.       The BLOB cache.
2.      The Page Output Cache.
3.       The Object Cache.

Page output and object cache require that you activate the ‘SharePoint Server Publishing’ feature located in the site features of your web site.

BLOB cache:

SharePoint Server 2010 provides a disk-based cache that stores files that are used by Web pages to help them load quickly in the browser, and reduces the load on the database server when it uses those files. The BLOB cache is stored directly on the hard disk drive of a front-end Web server computer. By default, the BLOB cache is off and must be enabled to use the functionality it provides. When you enable the BLOB cache on your front-end Web server, you reduce the load on the SharePoint Server 2010 database server created by read requests from Web browsers. You enable the BLOB cache in the Web.config file of the Web application to which you want to apply it. The changes that you make to the Web.config file will be applied to all site collections within the Web application. To configure and Setup BLOB Caching read here.
  1. BLOB cache should be used when pages that are accessed frequently have JavaScript, CSS, images files, and large rich media files that can be cached on the WFEs
  2. It is recommended that you not set the cache size smaller than 10 GB for BLOB Caching. When you set the cache size, make sure to specify a number large enough to provide a buffer at least 20 precent bigger than the estimated size of the content that will be stored in the cache.
  3. For a publishing site for which most of the visitors are anonymous or where most of the files are static content, enable the BLOB cache for as many file types as possible.
  4. For other sites that contain lots of media assets that are read-only, or where only a small percentage of the media assets are updated, enable the BLOB cache for media files only.
  5. Make sure that you put the BLOB cache on a drive that has sufficient disk space available in front-end Web server which to store the cache.
  6. Select a drive that will be used by as few processes as possible so that the BLOB cache process does not encounter conflicts when it tries to access the drive
  7. If there is a high read to write ratio BLOB caching should be used. For instance you would want to cache a site logo that is used on every page request versus a collaboration word document that is actively updated.
  8. BLOB caching is optimized for supporting large files which can significantly reduce bandwidth between the WFEs and SQL Server.
  9. BLOB caching is optimized to support cache control headers so that clients can cache small files which can reduce overall number of hits to the WFEs.
  10. If there is anonymous access, there can be dramatic improvements because permissions do not have to be validated for cache files.
  11. Client applications that use range requests can optimize load times to access large files.


Before you enable the BLOB cache, carefully consider the scenario in which you plan to use it. If your site will be used for heavy collaboration, enabling the BLOB cache might temporarily affect the performance of your site while the files to be cached are first written to the disk. After the files have been stored in the cache, site performance will improve, so take this into consideration when you decide whether or not to enable the cache. Base your decision to enable BLOB caching on the following criteria:
·         For a publishing site for which most of the visitors are anonymous or where most of the files are static content, enable the BLOB cache for as many file types as possible.
·         For other sites that contain lots of media assets that are read-only, or where only a small percentage of the media assets are updated, enable the BLOB cache for media files only.

Page output cache profiles:

The second caching option you have with SharePoint 2010 is ASP.net Output Cache. This is an in-memory cache that saves rendered ASPX pages. Using Output cache improves performance in two ways first it reduces the amount of SQL calls. Second it reduces workload on the WFE because pages do not need to be re-rendered. Along those lines if the pages are anonymous, then no SQL check needs to be done at all present the cached pages. Microsoft testing concluded a ninefold improvement in throughput when compared to having to render the page every time it was rendered. To configure and Setup Output Caching read here.
  1. The only catch for using Output Cache is that it can only be used in conjunction with publishing pages. It cannot be used with a collaboration site.
  2. Some examples of rules that can be capture in a cache profile would be to not cache if the requestor is a user who can edit pages to ensure they see the latest version of content.
  3. The cache profile also specifies rules for when a page is invalidated so that when the next request is made, it comes from the database.
  4. One of the main considerations for Output cache is the memory needed to support it. For each rendered page, 2(size of the page) + 32KB is needed to store the rendered page in memory.
  5. Output Cache should not be used with sites using a low read to write ratio because frequent changes to content make it hard to keep the cache fresh.
  6. On multi-WFE, output caching may affect consistency.

 Object cache

Object cache is the third caching option we have for SharePoint 2010. What Object cache does is stores metadata about SharePoint Server objects (like SPWeb, SPSite, SPList, etc.) on the WFEs. When a page is rendered, if there is data that needs to be retrieved through these objects, the SQL Server will not be hit. Features of SharePoint that uses Object cache are publishing, content query web part, navigation, search query box and metadata navigation. These features are specifically written to use the Object cache API instead of the SharePoint API directly. Developers writing custom functionality can also tap into the Object cache API. To configure and Setup Output Caching read here.
  1. The object cache cannot be disabled, and there is very little that can be configured. None of the out of box settings should have to be changed. Following article was written provides some additional information on this cache: Object Cache.
  2. They are normal ASP.net caching and can be a problem when Server data changes in case of multiple farm.
  3. It is recommended that you not set the cache size smaller than 3 MB.


Overall for caching we should keep in mind that any data where in Read/write ratio is less we should avoid caching. Only things which is static most of the time need to be cached like images etc.
When you flush the BLOB cache, you clear the contents of the BLOB cache for a Web application. This is useful if the BLOB cache becomes out of sync with the content. For example, after you restore a content database, the BLOB cache will be out of sync with the content. To correct that situation, you must flush the BLOB cache. The following procedure describes how to flush the BLOB cache for a Web application.

Important Information on Flushing:
a.       Flushing the BLOB cache for a Web application affects all site collections in the Web application.
b.      You cannot use the user interface to flush the BLOB cache. Instead, you use Windows PowerShell and the SharePoint object model to complete this task.
This is the link which tells you how to flush BLOB cache


Useful links

Configure Cache in SharePoint 2013

Custom Caching Overview

Output caching in SharePoint 2010

SharePoint 2010 developing for performance: caching-in-sharepoint-2010

Common coding issues in SharePoint caching

Machine caching in SharePoint 2010

Best coding practices

http://msdn.microsoft.com/en-us/library/aa661294.aspx

http://msdn.microsoft.com/en-us/library/aa661294.aspx

http://msdn.microsoft.com/en-us/library/ms550239.aspx

http://msdn.microsoft.com/en-us/library/aa622758.aspx

http://technet.microsoft.com/en-us/library/cc770229.aspx

http://technet.microsoft.com/en-us/library/cc770229.aspx#BLOB

http://www.zimmergren.net/archive/2008/10/07/web-part-caching-%E2%80%93-a-simple-approach.aspx

http://msdn.microsoft.com/en-us/library/bb687949%28office.12%29.aspx#UsingSPData

http://technet.microsoft.com/en-us/library/ee424404.aspx#Section1c

Thursday, October 16, 2014

Change site master page programmatically in SharePoint

It very simple to change the site's master page to custom master page programmatically in SharePoint 2007 environment. Recently we had released a new custom master pages. The master pages are with left menu place holders and another one is without left menu.

Provided a utility to update all sub sites master page. Find the same source code below.

siteUrl=@"http://kmsnet:2020/";
using (SPSite site =new SPSite(siteUrl))
{
foreach(SPWeb web in site.AllWebs)
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
if(web.CustomMasterUrl.ToLower().Equals(("/_catalogs/masterpage/NoLeftMenu.master").ToLower()))
{
web.CustomMasterUrl = "/_catalogs/masterpage/NewNoLeftMenu.master";
web.Update();
}
if (web.CustomMasterUrl.ToLower().Equals(("/_catalogs/masterpage/LeftMenu.master").ToLower()))
{
web.CustomMasterUrl = "/_catalogs/masterpage/NewLeftMenu.master";
web.Update();
}
});
}
}