Get top level parent of Term in SharePoint Taxonomy using C#

While working with SharePoint taxonomy sometimes we come across the problem where we want to get the top level parent of the given TermId. So here i am sharing the way of getting the top level parent term using given Term Id using c# code.

For the implementation of the code you will need to include Microsoft.SharePoint.Taxonomy library.

The below given code you can keep on any event action when you want to get the parent term.


try
{
HttpContext oldContext = HttpContext.Current;
HttpContext.Current = null;
string TermId = "Your Term Id"
Term ParentTerms = null;
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite("Your site URL"))
{
TaxonomySession taxonomySession = new TaxonomySession(site);
TermStore termStore = taxonomySession.TermStores["Your Managed MeataData Service Name"];
Group group = termStore.Groups["Your Termstore Group Name"];
TermSet sectionTermset = group.TermSets["Your Termset Name"];
ParentTerms = getParentTerm(sectionTermset, TermId);

/* “ParentTerms” is the object of your term, so using this you can get the details of the term like name, Id etc
}
});
}
catch (Exception ex)
{
// your catch code
}

Here the method “getParentTerm()” is called recursively to get the top level parent. The definition for the method is as below:-


public Term getParentTerm(TermSet termSet, string termGuid)
{
Term parentSectionTerm = null;
Term newParentSectionTerm = null;
parentSectionTerm = termSet.GetTerm(new Guid(termGuid));
var isTopLevelParent = parentSectionTerm.IsRoot;
if (!isTopLevelParent)
{
newParentSectionTerm = parentSectionTerm.Parent;
getParentTerm(termSet, Convert.ToString(newParentSectionTerm.Id));
}
else
{
newParentSectionTerm = parentSectionTerm;
}
return newParentSectionTerm;
}

Here “IsRoot” is the property of the term which returns true/false, if the term does not have any parent then it will return ‘true’, and if the term has the parent then it will return ‘false’.

I hope this article will help you to get rid of your problem for getting top level parent of the Term

SharePoint site migration from 2007(MOSS) to 2010

To migrate site we are using Database attach method.

Configurations and setting:-

Here AD of both server is same.

If one (normal) user from AD is able to login in 2007 server and not able to login in 2010 then you need to set up user profile for 2010 sever.

You will be able to migrate MySite also as a same way. For that first configure mysite and then attach database. For more information on it you can review this msdn site.

 Limitations:-

You will have to configure Search and User Profile service on Share Point 2010 server manually.

You won’t be able to migrate SharePoint designer workflow and event-receiver. You will have to create it manually.

It performs visual up gradation. That changes site UI from 2007 to 2010. So your Master page of site will not be longer available. You will have to set it up manually.

For more information on it you can refer this site.

Steps:-

  1. Before performing any task you must have following rights on 2007 server.
    • SharePoint Farm Admin.
    • Local Administration rights on the Web server.
    • db_owner permission on the content databases.
    • Make sure the access account has access to the site content
  2. SharePoint 2007 server must have SharePoint Service Pack 2 installed
    To verify it execute stsadm -o preupgradecheck command at location C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12BIN in command prompt.If you get any error then first resolve it. For more information review this site.
  3. Download all WSP from 2007 server using this command.
    [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
    $farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
    $solution = $farm.Solutions[“nameofthewsp.wsp”]
    $file = $solution.SolutionFile
    $file.SaveAs(“c:wspnameofthewsp.wsp”)
  4. If you have your web application with Host Header (on port 80) you will need to move it to any other port(eg 7777).
    So create web application on 2007 server.
  5. Export 80 port web application.
    stsadm -o export -url <URL name> -filename <export file name> -includeusersecurity
    (export file name = “C:ExportedFile.cab”)
    (URL name = “http://webapplicationname/site collectioname”)
    Execute this command in “Command Prompt” on location C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12BIN
  6. Import that cab file in newly created web application on 2007 server with port 7777.
    stsadm -o import -filename <import file name> -url <URL name> -includeusersecurity
    Here
    (import file name = “C:ExportedFile.cab”)
    (URL name = http://newwebapplication:7777)
    Execute this command in “Command Prompt” on location C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12BIN
  7. take back up database of 7777 web application from SQL Management Studio. (SQL 2008 R2)

Now move to 2010 server

  1. Create web application on 2010 server with same port number as 2007 server.(eg 7777)
  2. Add and deploy all WSP in your 2010 server.”C:Program FilesCommon FilesMicrosoft Sharedweb server extensions14BINstsadm.exe” -o addsolution -filename “C:deploymentv1.wsp”
    “C:Program FilesCommon FilesMicrosoft Sharedweb server extensions14BINstsadm.exe” -o deploysolution -name “CoverSoft.CompanyNews.wsp” -local -allowGacDeployment –url.
    Don’t activate the feature.
  3. Restore 2007 web application database on 2010 server SQL Management Studio. (SQL 2008 R2).
  4. Demount original database of web application.
    Dismount-SPContentDatabase <ContentdBName>
    Execute this command in “Management shell”If you are unaware about your database name then go to
    Central admin – > Application Management -> Databases -> Manage Content Databases and check your database name for particular web application

    Content Database Name

    Content Database Name

    Content Database Name

    Content Database Name[/caption}

  5. Test newly restored database.
    Test-SPContentDatabase -Name <DatabaseName> -WebApplication <URL>If you did not get any error you can go ahead. And if you got an error please resolve all the errors and then mount the database.
    Site Reference :- http://technet.microsoft.com/en-us/library/cc263299(v=office.15).aspx
  6. Attach the content database to the desired web application using Mount-SPContentDatabase cmdlet.
    Mount-SPContentDatabase -WebApplication<url>
    .If your test database operation has been performed successfully, then Mount operation should not create any issue.
    And if it is creating any issue then Demount it, retest it and then Mount it.

    Content Database Mount Operation

    Content Database Mount Operation

  7. Browse your site in 2010. It will be displayed in 2007 UI. And it will ask for up gradation at upper site in pink ribbon. Click on it and perform the visual up gradation.
    If you are not able to see pink ribbon you will be able to see visual upgrade option in Site Action tab or Site Setting page.If you want to migrate site in Share Point 2013, you will have to perform visual upgrade.
    You cannot directly move to Share Point 2013.
  8. Your site migration has been done successfully. Now you will have to perform below mention post migration steps.
    • Check all content of your site.
    • Check all links.
    • Create workflow.
    • Create Event-receiver
    • Set your master page
    • After this you might face some other UI issues. Be ready for that. Here I have add reference link with some common issues people is facing after site migration.

    https://wikis.utexas.edu/display/sharepoint/Known+Issues+after+site+was+migrated+to+SharePoint+2010

    http://en.share-gate.com/blog/not-working-after-sharepoint-migration-to-2013

 

 

Errors while test Database

A. Missing Feature

Missing Feature

Missing Feature

It might be because you are missing feature for any list or web-part or event-receiver.
If it is for web-part, then you will get one more error of MissingWebPart.
Otherwise it will be either list or event-receiver error. If it is so then you can ignore it. It will not block migration process.
If it is any other then try to find out from feature id and resolve it. Otherwise it is not a blocking issue if it has mention UpgradeBlocking value False.

B. Missing Setup file

Missing Setup file

Missing Setup file

If you have created any list or having event receiver on feature activation then SharePoint will ask for set up file.
So you can ignore this error. If it is due to some other reason than first make sure it is not important and then check UpgradeBlocking value. If it is False then you can ignore it.

C. Missing Web-part

Missing Web-part

Missing Web-part

In Share Point 2010 site if you don’t want to use any specific web-part then don’t need to deploy it on 2010 server. Web-part will not be available longer to use. And you can ignore this error.
Other than that if you want to use it in SharePoint 2010 site, than you have to deploy web-part.
To get missing web-part name you can refer this site.

D. Missing Event receiver

If you are getting Missing Event Receiver error then you can ignore it. But it again it will impact you site performance and some functionalities might not work. To solve this error remove Event Receiver.
To remove it you need to perform two simple steps

E. Legacy UI detected

Legacy in UI detected Legacy in UI detected

You can ignore this error. But to use all features that are introduced in SharePoint 2010 perform Visual up gradation

Summery

Active Directory, DNS, IIS and many other SharePoint features will play a part to make one complete SharePoint platform. In this article I tried to give you an idea of the most noticeable issues you may have migrating to SharePoint 2013. Be sure to add a comment if you encounter issues when migrating to help others work around them.SharePoint 2013. Be sure to add a comment if you encounter issues when migrating to help others work around them.

Site Reference

http://community.bamboosolutions.com/blogs/sharepoint-2010/archive/2010/11/02/sharepoint-2010-cookbook-migrate-a-sharepoint-2007-site-to-sharepoint-2010.aspx

Create Site Column, Content Type for multilingual site in SharePoint 2013

To create site column, content type and page layout for multilingual site first we have add resource file in our SharePoint project. The basic mechanism of localizing a SharePoint 2013 feature is same as we have in SharePoint 2010 and in Moss 2007.

Resource File

To deploy resource file to 15 hives, first we have to map project with the SharePoint Resource folder. Select your project – >Add->SharePoint Mapped Folder

b2

 

Select resource folder. Now right click on the mapped folder and select add new item and add resource file. I have added resource file for German and English. In resource file name you have to specify language code. Refer below image.

b1

Add your localize string in resource file. You will need to set the Build Action in the resx property to ‘Content’ otherwise a deployment to hive won’t take place. Below is my resource file.

b3

Form feature property set the Default Resource File to the resource file name and also set “Require Resource” to TRUE.

Site Column

To add site column select your project, add new item and select site column. Open Element.xml file of site column.

<Elementsxmlns=”http://schemas.microsoft.com/sharepoint/”>

<Field

ID=”{37e7b0d2-f12d-4204-a652-97fdf4b034e6}”

Name=”EventName”

DisplayName=”$Resources:EventName”

Type=”Text”

Required=”FALSE”

Group=”Events”>

</Field>

</Elements>

 

Now you have to set display name of site column from resource file name. Instead of “EventName” you have to change your name from resource file. By doing so display name is different for English and German site. Name is internal name of site column field. If you want to access site column from code behind than you have to use internal name of site column.

Content Type

To add content type selects your project, add new content type and select base content type. Open Element.xml file of

 

<ContentTypeID=”0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00D6DCE36F9DE043FE925DBA1E365BB75B”

Name=”$Resources:EventType”

Group=”Events”

Description=”$Resources:EventTypeDescription”

Inherits=”TRUE”

Version=”0″>

<FieldRefs>

<FieldRefID=”{37e7b0d2-f12d-4204-a652-97fdf4b034e6}”

Required=”FALSE”Name=”EventName” />

</FieldRefs>

</ContentType>

 

Set content type name from resource file. For content type we do not have display name property. We cannot set internal name for content type. If you want to access content type from code behind than you have to access with content type id.

 

Below is reference link for resource file

http://cann0nf0dder.wordpress.com/2013/05/16/resource-files-within-sharepoint-2010/

http://msreddysharepoint.blogspot.com/2013/01/resource-files-in-sharepoint-2010-and.html

Create List for multilingual site in SharePoint 2013

In our previous blog we have seen that how to create site column, content type for multilingual site. Now we will create custom list for all multilingual site with different name on feature activation.

 

try
{
    using (SPSite site = new SPSite(RootSiteUrl))
    {
        SPWebCollection allWebs = site.AllWebs;
        foreach (SPWeb currentWeb in allWebs)
        {
           if (PublishingWeb.IsPublishingWeb(currentWeb))
           {
               using (currentWeb)
               {
                 CreateListInstance(currentWeb.Url, "$Resources:EventNotification,EventListName", "", true, true);
               }
           }
         }
    }
}
catch (Exception ex)
{
     Logger.LogError(ex.Message, "List Error", ex.StackTrace);
}

Here the SPWeb object will give all multilingual site and sub site object. The above code will create list in all sub sites. If you want to avoid any sub site then you can specify that sub site name in if condition.

In the above code “EventNotification” is the name of the resource file and “EventListName” is the name attribute of resource file. It will get the value of “EventListName” from the resource file and create list with that name. In the above code CreateListInstance is the method to creates list which is below.

 

private void CreateListInstance(string absoluteSiteUrl, string dispalyNameFromResx, string description, bool allowContentType, bool allowVersioning)
{
     SPList list = null;
     try
     {
                SPSecurity.RunWithElevatedPrivileges(() =>
                 {
                     using (SPSite site = new SPSite(absoluteSiteUrl))
                     {
                         using (SPWeb web = site.OpenWeb())
                         {
                             if (web.Lists.TryGetList(dispalyNameFromResx) == null)
                             {
                                 Guid listId = web.Lists.Add(dispalyNameFromResx, description, SPListTemplateType.GenericList);
                                 list = web.Lists[listId];
                                 list.EnableVersioning = allowVersioning;
                                 list.ContentTypesEnabled = allowContentType;
                                 list.EnableModeration = false;
                                 list.Update();
                             }
                         }
                     }
                 });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message, "List create error", ex.StackTrace);
            }
}

 

Get Sharepoint Term’s Custom Local Property values (Server side)

We can get values of Custom local properties using server side code. There is no direct way to get custom local from terms. For that we need to do manual coding which is as follow:

 

/// Get Custom Local Property values of particular term.
private void GetCustomLocalPropertyValues(Term term)
{
       int valCnt = 0;
       int keyCnt = 0;
       string property1Val = null;
       string property2Val = null;
       string property3Val = null;
       int property1KeyId = 0;
       int property2KeyId = 0;
       int property3KeyId = 0;
       foreach (var custPropKey in term.LocalCustomProperties.Keys)
       {
       	keyCnt++;
              if (custPropKey == "Property1")
              	property1KeyId = keyCnt;
              if (custPropKey == "Property2")
              	property2KeyId = keyCnt;
              if (custPropKey == "Property3")
              	property3KeyId = keyCnt;
       }
       foreach (var custProp in term.LocalCustomProperties.Values)
       {
       	valCnt++;
              if (valCnt == property1KeyId)
              	property1Val = custProp;
              if (valCnt == property2KeyId)
              	property2Val = custProp;
              if (valCnt == property3KeyId)
              	property3Val = custProp;
       }
 }

 

See my previous blog : How to Create Custom Local Property in Sharepoint Terms