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

In ASP.Net C#, Call webpage asynchronously with get and post method type and additional parameters in callback method

Asynchronous method call is a mechanism in which control execution returns directly to the next statement without waiting for the method operation execution. Every asynchronous call is associated with a dedicated thread. IIS has limited number of application thread pools (default 5000 per CPU). IIS can handle that number of concurrent request at a time. So if you have a situation where you expect large number of concurrent requests in a single application, asynchronous method call will be a good practice. Where synchronous call executes by occupying 5000 threads, asynchronous can perform the same task with only 50 available threads. Here you can read more on thread pools here

In C# data posting with get() method in asynchronous calls can be done by just passing parameters in URL where as in asynchronous post() method for passing the parameters you will need to write them in stream asynchronously. For that .Net is providing reach HttpWebRequest class methods.

Recently I had a situation where my application was expecting very heavy user traffic and I had a requirement to store them into my database as well as also need to pass the data to a third party webpage. So I needed to pass the data asynchronously to that third party webpage without waiting for the response from that webpage. Also if any asynchronous call fails during the execution due to any data mismatch, I need to log the error along with an “id” from my database for that user request. And to achieve that I needed to pass some extra data like “UserId”, which was not a part of asynchronous method parameters. Also I could not add the “id” in webpage parameter collection as it was not a part of the third party webpage definition.
So to accomplish this I have sent the parameter of type Object array into asynchronous method request with method type post. Following are the example of code for asynchronous get method, asynchronous post method and asynchronous post method with extra parameters.

Example for asynchronous GET method:

protected void Page_Load(object sender, EventArgs e)
{
//For testing I have used current application’s about.aspx itself
//Passes id, firstname and lastname as a quesrystring in URL
GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
}
private static void GetMethodCall(string URL)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//BeginGetResponse is used to call asynchronously URL
IAsyncResult result =
(IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
request.Method = “GET”;
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//Log the error
string errormessage = ex.Message;
}
}

 

Example for POST method:

protected void Page_Load(object sender, EventArgs e)
{
// GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
//For post data testing I have used current application’s aboutpost.aspx
PostMethodCall(“http://localhost:2839/aboutpost.aspx”);
}
private static void PostMethodCall(string URL)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//Set method verb type to POST
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;// BeginGetRequestStream is used to set post data content in asynchronously call
IAsyncResult result =
(IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), request);}
private static void GetRequestCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
Stream postStream = request.EndGetRequestStream(asynchronousResult);//Set data to be post
string postData = “id=1&firstname=abc&lastname=xyz”;// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
//Log the error
string errormessage = ex.Message;
}
}

You need to use same GetResponseCallback method as previous example.

Example for GET & POST methods with additional user defined parameters:

protected void Page_Load(object sender, EventArgs e)
{
// GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
//For post data testing I have used current application’s aboutpost.aspx
PostMethodCall(“http://localhost:2839/aboutpost.aspx”, “L001020″, “U112″);
}
private static void PostMethodCall(string URL, string logID, string userid)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//Set method verb type to POST
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;// BeginGetRequestStream is used to set post data content in asynchronously call
//Use 2nd parameter for asyncresult as oject type and pass additional parameters comma separated
IAsyncResult result =
(IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), new object[] { request, userid, logID });}
private static void GetRequestCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
Stream postStream = request.EndGetRequestStream(asynchronousResult);//Set data to be post
string postData = “id=1&firstname=abc&lastname=xyz”;// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();// Start the asynchronous operation to get the response
//Use 2nd parameter for asyncresult as oject type and pass additional parameters comma separated
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), new object[] { request, userid, MyUniqueLogID });
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}

Similarly you can pass additional parameters in GET method type by calling same GetResponseCallback callback.

request.BeginGetResponse(new AsyncCallback(GetResponseCallback), new object[] { request, userid, MyUniqueLogID });

Additional information:

  • You can retrieve GET method parameters as follows:

  • You can retrieve POST method parameters as follows:

You can retrieve return value from asynchronous web page call using following code:

private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
//Get response stream for check return values by external webpage
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Get response in string object
string myResult = responseString;
if (myResult == “success”)
{
string status = “I am done”;
}
else
{
string status = “I am done with some error”;
}

// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}

Required additional namespaces

System.Net.HttpWebRequest
System.Text; // for Encoding.UTF8

Supported .NET Frameworks

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

Posted By: Kruti V Parmar