Tuesday, 14 February 2012

SP 2010: Introduction to programmatically working with Taxonomies in SharePoint Server 2010

Introduction

One of the coolest new set of functionality for SharePoint 2010 is the Taxonomies (Term Store,
Term Sets, Terms) that you can easily create using the amazing Managed Metadata Manager service application.
In this article I’ll talk briefly about how you can utilize the SharePoint API to programmatically
work with Taxonomies and create terms and fetch the terms in your term store. This should give
you some nice ideas on how to get going!

A simple example of a taxonomy

Let’s say we’ve got a taxonomy worked out and implemented in SharePoint. It could look something like this (I’m using some made up samples below):
image
So, if you’ve got a taxonomy configured in your Managed Metadata Service Application
, you can work with those programmatically – and that’s what this little tip is about.

Work with the taxonomy API’s programmatically in SP 2010

In this article I will talk about some of the basics to get started with taxonomies in
SharePoint 2010 programmatically. First, of course, we need to create a new project and
add the references for the Taxonomy API.

Preparing for development

First of all, create a new project (In my case, I chose to create a Visual Web Part project).
You’ll need to add the following reference to your project:
image
You’ll find this reference here:
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.Taxonomy.dll

Namespaces

So, the first thing we would like to do is to learn how we can read the taxonomies
we’ve got in our store.
 To do this, we utilize Microsoft.SharePoint.Taxonomy.
There’s a few good-to-know classes in this namespace that we’re going to work with:
The above classes are stated in their hierarchically correct order, meaning means that
you start out with the TaxonomySession which contains the TermStore,
 which contains the Groups.. and so on.

Reading the Metadata store (Managed Metadata Service) programmatically

Sample code from my Visual Web Part’s user control (I have a control called tvMetadataTree in
 the user control):
     public  partial  class  TaxonomyWebPartUserControl  : UserControl 
     {
         protected  void  Page_Load(object  sender, EventArgs  e)
         {
             SPSite  thisSite = SPContext .Current.Site;
             TaxonomySession  session = new  TaxonomySession (thisSite);

             TreeNode  treeNode = new  TreeNode ();
             treeNode.Text = "Metadata Awesomeness" ;
             tvMetadataTree.Nodes.Add(treeNode);

             foreach (TermStore  termStore in  session.TermStores)
             {
                 var  tsNode = new  TreeNode (termStore.Name, null , null 
                 , "" , null );
                 treeNode.ChildNodes.Add(tsNode);
                 //treeNode = tsNode; 

                 foreach (Group  group in  termStore.Groups)
                 {
                     var  node = new  TreeNode (group.Name, null , null ,
                     "" , null );
                     treeNode.ChildNodes.Add(node);
                     //treeNode = node; 
                     
                     foreach (TermSet  termSet in  group.TermSets)
                     {
                         node = new  TreeNode (termSet.Name, null , null , "" 
                         , null );
                         treeNode.ChildNodes.Add(node);
                         treeNode = node;

                         foreach (Term  term in  termSet.Terms)
                         {
                             AddTermSet(term, treeNode);
                         }
                     }
                 }
             }
         }

         void  AddTermSet(Term  term, TreeNode  treeNode)
         {
             var  node = new  TreeNode (term.Name, null , null
            "" , null );
             treeNode.ChildNodes.Add(node);
             treeNode = node;

             foreach  (Term  t in  term.Terms)
             {
                 AddTermSet(t, treeNode);
             }
         }
     }
The end result will be a simple TreeView control filled with the Metadata structure from the store,
 looking something like this:
image
That’s about what you would need to get started with this!

Monday, 13 February 2012

SharePoint 2010: Administer Taxonomy Using Term Store Management

Taxonomy management in SharePoint 2010 (news, site) sees a significant improvement over functionality offered by the product’s predecessors.
First and foremost is the creation of a term store repository, enabling centralized vocabulary management applicable across site collections. Management of taxonomy takes place within the Term Store Management Tool, which is accessible through either Central Administration or Site Administration. Basic functionality provided for the management of taxonomy includes:

Groups

Groups represent defined security boundaries in terms of taxonomy governance. Multiple groups may be created within a Managed Metadata Service, with each Group having multiple Terms Sets. Management (create, edit, delete) of Group properties takes place here.
SP2010_MMS_Groups.jpg

Term Sets

One or more Term Sets (up to 1,000) are defined as part of a Group. Term Sets can be created manually or imported through the interface. Management (create, edit, delete) of Term Set properties, including Term hierarchy, takes place here.
SP2010_MMS_TermSets.jpg

Terms

Individual words or phrases are added to a Term Set with management (create, copy, reuse, merge, deprecate, move or delete) taking place here. A maximum of 30,000 Terms can be added to a single Term Set.
Sp2010_MMS_Terms.jpg

Introduction to SharePoint Managed Metadata


I have the day off and as I ate my brown sugar Mini-Wheats, I naturally came to the conclusion that today would be the day that I would finally begin to write a series of blog posts about the biggest new SharePoint 2010 feature: Enterprise Managed Metadata (a.k.a. EMM, Managed Metadata Service (MMS) or SharePoint 2010 taxonomy).
image
More consistent use of terminology
Managed metadata facilitates more consistent use of terms, as well as more consistent use of the managed keywords that are added to SharePoint Server items. You can pre-define terms, and allow only authorized users to add new terms. You can also prohibit users from adding their own managed keywords to items, and require them to use existing ones. Managed metadata also provides greater accuracy by presenting only a list of correct terms from which users can select values. Because managed keywords are also a type of managed metadata, even the managed keywords that users apply to items can be more consistent.

Because metadata is used more consistently, you can have a higher degree of confidence that it is correct. When you use metadata to automate business processes—for example, placing documents in different files in the record center based on the value of their department attribute—you can be confident that the metadata was created by authorized users, and that the value of the department attribute is always one of the valid values.
Better search resultsA simple search can provide more relevant results if items have consistent attributes.
As users apply managed terms and keywords to items, they are guided to terms that have already been used. In some cases, users might not even be able to enter a new value. Because users are focused on a specific set of terms, those terms—and not synonyms—are more likely to be applied to items. Searching for a managed term or a managed keyword is therefore likely to retrieve more relevant results.
DynamicIn previous versions of SharePoint Server, to restrict the value of an attribute to being one of a set of values, you would have created a column whose type is "choice", and then provided a list of valid values. When you needed to add a new value to set of choices, you would have to modify every column that used the same set of values.
By using managed metadata in SharePoint Server 2010, you can separate the set of valid values from the columns whose value must be one of the set of valid values. When you need to add a new value, you add a term to the term set, and all columns that map to that term set would use the updated set of choices.
Using terms can help you keep SharePoint Server items in sync with the business as the business changes. For example, assume your company's new product had a code name early in its development, and was given an official name shortly before the product launched. You included a term for the code name in the "product" term set, and users have been identifying all documents related to the product by using the term. When the product name changed, you could edit the term and change its name to the product's official name. The term is still applied to the same items, but its name is now updated.”
image - Adding keywords to a document in SharePoint 2010 Beta 2

What’s in this release?

To borrow a joke from Dan Kogan’s SharePoint Conference 2009 (#SPC09) talk, when we talk about terms, we need to first define our terms. From MSDN’s definitions of SharePoint Managed Metadata:
termA word or phrase that can be associated with an item in SharePoint Server 2010.
term setA collection of related terms.
managed termA term that can be created by users only with the appropriate permissions and often organized into a hierarchy. Managed terms are usually predefined.
managed keywordA word or phrase that has been added to SharePoint Server 2010 items. All managed keywords are part of a single, non-hierarchical term set called the keyword set.
term storeA database that stores both managed terms and managed keywords.
Also, one definition that isn’t in the list:
groupIn the term store, all term sets are created within groups. In other words, group is the parent container for term sets.
image - The Term Store Management Tool
These are the elements within the SharePoint 2010 managed metadata functionality, but the pieces aren’t the only consideration—it’s also important how they fit together. According to information management experts Earley & Associates, there are three different types of relationships in taxonomies:
Equivalent (Synonyms: "LOL = Laughing out loud")
Hierarchical (Parent/Child : "Sports Equipment => ball")
Associative (Concept/Concept: "Bouncy things - ball")
SharePoint 2010 will provide SharePoint users, administrators and developers with the UI and API required for the first two. This means that faculties such as centrally managed terms, folksonomy and tag clouds (social tagging) are enabled. The third type—that SharePoint 2010 will not be offering—is ontologies. Here’s a quick discussion of each type.
Equivalent Terms
SharePoint taxonomy will allow synonyms and preferred terms. Synonyms allow a central understanding that LOL is the same as “laughing out loud,” and preferred terms specify which of the two should be used.
The other side of the equivalence coin is dealing with words with more than one meaning. To help disambiguate terms, SharePoint term descriptions show in a tooltip so that users can differentiate between G-Force (the recent movie featuring a specially trained squad of guinea pigs) vs. G-Force (my favourite childhood cartoon) from Battle of the Planets.
Hierarchical Terms
A central repository of terms enables consistency across users. Providing a hierarchy allows for information architecture and organization. In the SharePoint Term Store Management Tool, users with sufficient permissions will be able to perform many operations on terms in the hierarchy. These include: copying, reusing, moving, duplicating (for polyhierarchy), deprecating, and merging. The hierarchy is broken down into a term store at the top, then a group, term sets, and finally, managed terms.
image - Example of a taxonomy hierarchy (image courtesy Microsoft)
Note: managed keywords (or just keywords) will be stored in a separate single database. Keywords will be used for social tagging such as tag clouds and folksonomy, but keywords can be promoted to managed terms.
Associative Terms
An ontology is a means of classifying data based on an associative relationship. There are endless possibilities for these types of relationships. For example, I could have a hierarchy of terms in SharePoint 2010 that includes the terms “ball” and “bat” as children of the term “sports equipment.” An ontology would allow me to also create a relationship between “Bouncy things” and “ball” because they are conceptually related. Why didn’t the SharePoint team add ontologies? That’s a reasonable question, but the fact is that it simply may not have been worth the effort to tackle such a specialized function when they were already trying to build an ambitious feature. Also, many people wonder if anyone but a library scientist or a taxonomist will complain.

How will SharePoint taxonomy be used?

Obviously, the most popular end-user use of EMM will be taxonomy to fulfill business needs and social tagging. Many content types will ship with a Managed Metadata data-type column and users will be able to tag their list items, documents, etc, with shared terms. This end-user associated metadata will then be used to classify, organize, find and share information within SharePoint. By tagging external pages, users have a way to add links to their favourite browser’s bookmarks.
However, another aspect of the new managed metadata functionality is how it could be used for enhanced navigation and search. For example, terms can be used to enable more advanced parametric search features, targeted search and possibly even lemmatisation in FAST search—but I’m not a search expert, so I’d have to do some more research to find out what’s happening on the search side. One thing is for sure, customers and partners will find interesting ways to use the taxonomy framework.
In terms of navigation, the ability to alter the way you navigate your data based on tags is also referred to as faceted navigation. When I was working on SharePoint navigation, we nicknamed faceted navigation, “navigation goggles.” The idea being that you could choose different types of navigation the same way you can shift between song view, albums or artists on many MP3 players.
For developers, SharePoint 2010 EMM also includes the Taxonomy APIs. Most of the EMM classes are found in the Microsoft.SharePoint.Taxonomy namespace.

• TaxonomySession class
• TermStore class
• Group class
• TermSet class
• Term class
• CommitAll method
• IsAvailable property
• Name property
• CreateLabel method
• SetDescription method
This block of sample code (courtesy of Microsoft) shows how the taxonomy API can be used.
using (SPSite site = new SPSite(http://localhost/)){//Instantiates a new TaxonomySession for the current site.TaxonomySession session = new TaxonomySession(site);
//Instantiates the connection named "Managed Metadata Service//Connection" for the current session.
 TermStore termStore = session.TermStores["Managed Metadata Service Connection"];
// Creates and commits a Group object named Group1, a TermSet object// named termSet1, and several Term objects. Term1, Term2, and Term3 are// members of termSet1. Term1a and Term1b are children of Term1.
 Group group1 = termStore.CreateGroup("Group1");
 TermSet termSet1 = group1.CreateTermSet("TermSet1");
 Term term1 = termSet1.CreateTerm("Term1", 1033);
 Term term2 = termSet1.CreateTerm("Term2", 1033);
 Term term3 = termSet1.CreateTerm("Term3", 1033); 
 Term term1a = term1.CreateTerm("Term1a", 1033);
 Term term1b = term1.CreateTerm("Term1b",1033);
 termStore.CommitAll();
// Sets a description and some alternate labels for term1 and commits// the changes to termStore.
term1.SetDescription("This is term1",1033);
term1.CreateLabel("TermOne", 1033, false); 
term1.CreateLabel("FirstTerm", 1033, false);
termStore.CommitAll();
// Deletes an unnecessary term, term3, from termStore and commits changesterm3.Delete();termStore.CommitAll();
}

Multilingual Taxonomy In SharePoint 2010

In the Enterprise Metadata Management documentation it states that Managed Terms could be used when metadata "Can be applied in one language, but might be viewed in other languages"
This is available in term stores because Managed terms can be assigned multiple labels. When someone types in any of the labels (which could be in different languages), they will be applying the same term. This creates a multilingual term system.
Here is the documentation page about Multilingual term sets (SharePoint Server 2010)
Note: Labels are different than descriptions. There can only be one description on a term and it's generally used for disambiguation. (e.g., "this is Dallas the city, not Dallas the TV show")

Conclusion

The new SharePoint 2010 Managed Metadata functionality is exciting and provides a framework to build more taxonomy features. Through managed metadata, SharePoint users gain access to functionality such as folksonomy, social tagging (tag clouds) and more powerful search options. EMM also provides a way to centrally manage bookmarks.
The Term Store Management Tool available in Central Administration (and Site Settings) enables administrators to manage a central vocabulary of terms for the whole farm. Operations that administrators can perform on the term hierarchy include copying, reusing, moving, duplicating, deprecating, and merging. Furthermore, having a managed repository enforces consistency across users.
Enterprise Metadata Management is a huge topic. In fact, how SharePoint 2010 exposes the taxonomy features (e.g., the new tag cloud web part) is worthy of its own post, so I’m not going to try and sum it all up in one.
These are the upcoming posts:
SharePoint Taxonomy Part One – Introduction to SharePoint Managed Metadata
SharePoint Taxonomy Part Two – End-User Experience
SharePoint Taxonomy Part Three – Administrator Experience
(including Using SharePoint Term Stores and SharePoint Taxonomy Hierarchy)
SharePoint Taxonomy Part Four – Developer Experience
(including SharePoint 2010 Visual Web Parts, SharePoint 2010 Taxonomy Web Part Development Screencast and SharePoint 2010 Taxonomy Reference Issues)
Managed Metadata Best Practices from Microsoft:
Plan managed metadata (SharePoint Server 2010)
Managed metadata overview (SharePoint Server 2010)
Managed metadata service application overview (SharePoint Server 2010)
Managed metadata roles (SharePoint Server 2010)
Plan terms and term sets (SharePoint Server 2010)
Plan to import managed metadata (SharePoint Server 2010)
Plan to share terminology and content types (SharePoint Server 2010)
SharePoint Enterprise Content Management

Sunday, 12 February 2012

Enable Claims based authentication on an existing web application in SharePoint



When you provision a web application in SharePoint 2010 you get the option to enable Claims based authentication. However, after the provisioning there's no option in the GUI to turn it on. PowerShell saves the day again with the option to change from classic to claims based authentication using the lines below.
$WebAppName = "http://test:8001"
$account = "Administrator" 
$wa = get-SPWebApplication $WebAppName
Set-SPwebApplication $wa –AuthenticationProvider (New-SPAuthenticationProvider) 
–Zone Default

The user running these command should be a member of the SharePoint_Shell_Access role on the config DB, and a member of the WSS_ADMIN_WPG local group.

Monday, 6 February 2012

Custom sign out SharePoint page for FBA user.


Hi, everyone!
In my latest project we are using FBA users for our portal. And in the prototype of the master page such as generic web page we have login control with username, password boxes and ‘sing in’ button. If you will use for login just general sign in control of ASP .NET we will lose with authentication, exception will appear in the page. For fixing this problem we have to use SPClaimsUtility.
For example:
protected void OnAuthenticate(object sender, AuthenticateEventArgs e)
{
    e.Authenticated = 
SPClaimsUtility.AuthenticateFormsUser(Request.Url, signIn.UserName, 
signIn.Password);
}
But for sign out we have to create custom page for logout current user from portal. In all forums you can find information that’s you can use default signout.aspx page from 14 hive. But it’s true if you created custom login page inherited from SharePoint SignInPage. Default page is working incorrectly, it made sign out but doesn’t remove cookies from browser and the next page what you will see after signout, it will ‘Exception … ArgumentException … encodedValue’.
Insert the next following code to the page for clearing sign out.
protected override void OnLoad(EventArgs e)
{
 base.OnLoad(e);

 FormsAuthentication.SignOut();
 var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        // Clear .ASPAUTH cookie key.
 if (authCookie != null)
 {
  var myCookie = new HttpCookie(authCookie.Name)
               {Expires = DateTime.Now.AddDays(-1)};
  Response.Cookies.Add(myCookie);
 }

 SPIisSettings iisSettingsWithFallback = 
        
 Site.WebApplication.GetIisSettingsWithFallback(Site.Zone);
 if (iisSettingsWithFallback.UseClaimsAuthentication)
 {
  FederatedAuthentication.SessionAuthenticationModule.SignOut();
                // Clear FedAuth Cookie key
  FederatedAuthentication.SessionAuthenticationModule.DeleteSession       
 TokenCookie();
 }


 SPUtility.Redirect(Web.ServerRelativeUrl, SPRedirectFlags.Default,
       
   Context);
}
That’s all what you need to add to the custom sign out page.

Replacing Signout.aspx in SharePoint 2010


Yes, this was a common requirement in SharePoint 2007 and there wasn’t an easy and supportable approach to achieve that. Now in SharePoint 2010, it’s as easy as calling a method, specifying the
page that you want to replace (for instance: Signout, error, access denied, ..) ,the URL of your new
custom page and that's it!
The following feature receiver replaces the default SignOut page with a custom one on activation
and resets the SignOut page to the default one on deactivation.

image

You can also replace other pages like AccessDenied.aspx, Confirmation.aspx, Error.aspx,
Login.aspx, ReqAcc.aspx, SignOut.aspx or WebDeleted.aspx by specifying a member of SPWebApplication.SPCustomPage enum.



Generate MD5 Hash code from a string using C#


For security purpose, passwords are encrypted using a hash and then stored in databases or in xml files. MD5 is a very common hash algorithm and it is very easy to use it from C#. Hash code is basically a 32-character string of hexadecimal numbers.
.Net Framework class library contains a class “MD5” which is used to create hash code based on the MD5 hash algorithm. This class “MD5” can be found in the “System.Security.Cryptography” namespace.
Following implementation of a method can be used to convert string to an MD5 hash code:
public static  string CalculateMD5Hash(string strInput){  MD5 md5 = System.Security.Cryptography.MD5.Create();  byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strInput);  byte[] hash = md5.ComputeHash(inputBytes);             

  
StringBuilder sb = new StringBuilder();
            
  
for (int i = 0; i < hash.Length; i++)
            
  
{
                
    
sb.Append(hash[i].ToString("x2"));
 
  
}
         
  
return sb.ToString();
       }
An example call of the above method:
string strHashCode = CalculateMD5Hash("abcdefgh");
the variable “strHashCode” will receive a hash code as below:
a8dc4081b13434b45189a720b77b6818

SQL SERVER – Difference TempTable and Table Variable – TempTable in Memory a Myth


During the discussion of temp table and table variable, I quite commonly hear that Table Variables are stored in memory and Temp Tables are stored in TempDB. I would like to bust this misconception by suggesting following:
Temp Table and Table Variable — both are created in TempDB and not in memory.
Let us prove this concept by running the following T-SQL script.
/* Check the difference between Temp Table and Memory Tables */
-- Get Current Session ID
SELECT @@SPID AS Current_SessionID
-- Check the space usage in page files
SELECT user_objects_alloc_page_count 
   FROM   sys.dm_db_session_space_usage 
   WHERE session_id 
   (SELECT @@SPID )GO
-- Create Temp Table and insert three thousand rows
   CREATE TABLE #TempTable 
   (Col1 INT)
   INSERT INTO #TempTable (Col1)
   SELECT TOP 3000 ROW_NUMBER() OVER(ORDER BY a.name)FROM sys.all_objects a 
   CROSS JOIN sys.all_objects b
  GO
-- Check the space usage in page files
SELECT user_objects_alloc_page_count 
    FROM   sys.dm_db_session_space_usage
   WHERE session_id =(SELECT @@SPID )
    GO
 -- Create Table Variable and insert three thousand rows
  DECLARE @temp TABLE(Col1 INT)
  INSERT INTO @temp (Col1)SELECT TOP 3000 ROW_NUMBER() 
  OVER(ORDER BY a.name)FROM sys.all_objects a 
  CROSS JOIN sys.all_objects b
  GO
 -- Check the space usage in page files
  SELECT user_objects_alloc_page_count 
  FROM sys.dm_db_session_space_usage
  WHERE session_id (SELECT @@SPID )
  GO
-- Clean up
DROP TABLE #TempTableGO
Let us see the resultset. It is very clear that the size of the table variable and temp table is the
same and created in TempDb.
Have you ever heard of this misconception? Do you know any other method to prove that both
 Temp Table and TableVariable are created in TempDB.

Sharepoint 2010 Form Based Authentication Using Active Directory


In this article I will try to show how we can use Active Directory Form Based Authentication in Sharepoint 2010 using Lightweight Directory Access Protocol (LDAP)
1. Add Connection string and membership provider in Central Administration web.config
1.png

2.png

3.png

4.png

NOTE: connectionString will differ based on domain configuration. Please contact you Administrator to provide the LDAP details.
2. Add Connection string and membership provider in SecurityTokenServiceApplication web.config
5.png

6.png

7.png

NOTE: connectionString will differ based on domain configuration. Please contact you Administrator to provide the LDAP details.

3. Create a new site with claim based authentication using Central Administration
8.png

Authentication : Claim Based
Claims Authentication Types: Enable Windows Authentication -> Integrated Windows authentication - > NTLM
Leave others to default

9.png
4. Now Create Site Collection at port 2233
10.png

And add Primary / Secondary Site Collection Administrators

11.png

12.png

So the resultant site will look like below.
13.png

5 Extend the web application to port 3322 and enable form based authentication (FBA)
14.png

Set the public URL Zone- Intranet or Extranet
5. Add Users to the Intranet zone using User Policy
15.png

16.png

17.png


18.png

Add more users as required with desired permissions.
Now open the newly extended application, and use your domain credentials to login the app.

19.png

20.png