Get SharePoint 2013 Taxonomy Term by TermName - sharepoint

I am looking for a way to use Javascript to Query Taxonomy.js, to get a Term based on Term Name (I don't have ID available on page).
Only option that I am able to find is to retrieve all terms in the TermSet, loop through each term to match the name.
This works, but is causing performance issue. I am looking for a way to get the term directly, without looping through all.

I was finally able to cobble this together.
var context = SP.ClientContext.get_current();
var session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = session.getDefaultSiteCollectionTermStore();
var parentTermId = 'd89595cf-7d0d-4f19-8e14-8b8b05efb7de'; // Some parent term
var parentTerm = termStore.getTerm(parentTermId);
// arguments are termLabel, language code, defaultLabelOnly, matching option, max num results, trim unavailable
var terms = parentTerm.getTerms(series,1033,true,SP.Taxonomy.StringMatchOption.exactMatch,1,true);
context.load(terms);
context.executeQueryAsync(
function(){
//print child Terms
for(var i = 0; i < terms.get_count();i++){
var term = terms.getItemAtIndex(i);
console.log(term.get_name());
console.log(term.get_description());
}
},
function(sender,args){
console.log(args.get_message());
});
If you know one parent term's guid you can use that and then get a specific term below that. In our case the parent term only has one level of children, so I haven't checked if it searches children of children.
There is also the TermSet.getTerms() method which takes a labelMatchingInformation object as its argument. Here is the documentation and a blog about it. I couldn't get the lmi to work, but in the blog he seems to be apply it directly to a taxonomysession and I think it is supposed to be applied to a termset, so maybe that is the difference.

Related

C# Revit API, how to create a simple wall using ExternalCommand?

I just wanted to learn Revit API and create a simple wall using ExternalCommand. But I cannot figure it out...
I think my problem is here:
var symbolId = document.GetDefaultFamilyTypeId(new ElementId(BuiltInCategory.OST_Walls));
When I debug it symbolId always -1.
Can you help me what is wrong with this code snippet?
public Autodesk.Revit.UI.Result Execute(
Autodesk.Revit.UI.ExternalCommandData command_data,
ref string message,
Autodesk.Revit.DB.ElementSet elements)
{
var document = command_data.Application.ActiveUIDocument.Document;
var level_id = new ElementId(1526);
// create line
XYZ point_a = new XYZ(-10, 0, 0);
XYZ point_b = new XYZ(10, 10, 10);
Line line = Line.CreateBound(point_a, point_b);
using (var transaction = new Transaction(doc))
{
transaction.Start("create walls");
Wall wall = Wall.Create(doc, line, level_id, false);
var position = new XYZ(0, 0, 0);
var symbolId = document.GetDefaultFamilyTypeId(new ElementId(BuiltInCategory.OST_Walls));
if (symbolId == ElementId.InvalidElementId) {
transaction.RollBack();
return Result.Failed;
}
var symbol = document.GetElement(symbolId) as FamilySymbol;
var level = (Level)document.GetElement(wall.LevelId);
document.Create.NewFamilyInstance(position, symbol, wall, level, StructuralType.NonStructural);
transaction.Commit();
}
return Result.Succeeded;
}
Work through the Revit API getting started material and all will be explained. That will save you and others many further questions and answers.
To address this specific question anyway, GetDefaultFamilyTypeId presumably does not do what you expect it to for wall elements. In the GetDefaultFamilyTypeId method API documentation, it is used for structural columns, a standard loadable family hosted by individual RFA files. Walls are built-in system families and behave differently. Maybe GetDefaultFamilyTypeId only works for non-system families.
To retrieve an arbitrary (not default) wall type, use a filtered element collector to retrieve all WallType elements and pick the first one you find.
Here is a code snippet that picks the first one with a specific name, from The Building Coder discussion on Creating Face Wall and Mass Floor
:
WallType wType = new FilteredElementCollector( doc )
.OfClass( typeof( WallType ) )
.Cast<WallType>().FirstOrDefault( q
=> q.Name == "Generic - 6\" Masonry" );

SharePoint NavigationTermSet - Nested Terms

I'm trying to access the Term Store Navigation by SharePoint JSOM.
My Term Store Navigation is set up like this.
Navigation Link 1
Sub Navigation Link 1
Sub Navigation Link 2
Navigation Link 2
To access the Term Store Navigation use the following code.
this.getNavigationTermSet=function(currentTermStore,navTermSetId){
var deferred = $.Deferred();
var termSet = currentTermStore.getTermSet(navTermSetId);
var navTermSet = SP.Publishing.Navigation.NavigationTermSet.getAsResolvedByWeb(this.clientContext,termSet, this.clientContext.get_web(), "GlobalNavigationTaxonomyProvider");
this.clientContext.load(navTermSet,'Terms');
this.clientContext.executeQueryAsync(
function(terms){
deferred.resolve(navTermSet);
},
function(sender,args){
deferred.reject(args.get_message());
});
return deferred;
}
The code returns a Termset Collection to the calling method that looks like this.
txCon.getNavigationTermSet(termStore,
'6b361f3a-d8c5-40eb-89d0-c503a91eb033').then(function(navTerms){
for(var i = 0 ; i<navTerms.get_terms().get_count();i++){
var navTerm = navTerms.get_terms().getItemAtIndex(i);
console.log(navTerm.get_id() + " - "+ navTerm.get_taxonomyName());
}
}
I'm able to cycle through the Terms, but i can only access the first level. Is there anybody out there who can tell me how to access the second or any other nested level from there? Or is there a request for each child term necessary? i don't get it at the moment ;)

Different variable name case convention in one application

This is a really trivial problem. I am just curious on how to deal with this in a "professional" manner.
I am trying to stick to variable naming convention. For NodeJs I am doing camelCasing. For database, I am using PostgreSQL and using underscore_casing.
Now the problem arises when I query data from PostgreSQL. I'll get a user object with following format,
{user_id: 1, account_type : "Admin"}
I can pass this object directly to server side-render and will have to use underscore casing to access account_type. Of course, I can manually create a new user JSON object with property userId and accountType but that is unnecessary work.
Is it possible to follow variable naming convention for both language and avoid having mixed variable names casing in some files? What is a good way to stay organized?
The are two good ways to approach this issue. The simplest one - do no conversion, use the exact database names. And the second one is to camel-case columns automatically.
Either way, you should always follow the underscore notation for all PostgreSQL declarations, as it will give you the option to activate camel-casing in your app at a later time, if it becomes necessary. Never use camel-case inside the database, or you will end up in a lot of pain later.
If you want the best of both worlds, follow the underscore notation for all PostgreSQL declarations, and convert to camel-case as you read data.
Below is an example of how to do it properly with pg-promise, copied from event receive example:
// Example below shows the fastest way to camelize column names:
const options = {
receive(e) {
camelizeColumns(e.data);
}
};
function camelizeColumns(data) {
const template = data[0];
for (var prop in template) {
const camel = pgp.utils.camelize(prop);
if (!(camel in template)) {
for (var i = 0; i < data.length; i++) {
const d = data[i];
d[camel] = d[prop];
delete d[prop];
}
}
}
}
Also see the following article: Pg-promise and case sensitivity in column names.
UPDATE
The code above has been updated for use of pg-promise v11 or later.
I've struggled with this too, and I've concluded that there's really no way to avoid this kind of ugliness unless you rewrite the objects that come from the database. Fortunately, that's not too difficult in Javascript:
const fromDBtoJS = (obj) => {
// declare a variable to hold the result
const result = {};
// iterate over the keys on the object
Object.keys(obj).forEach((key) => {
// adjust the key
const newKey = key.replace(/_[a-z]/g, (x) => x[1].toUpperCase());
// add the value from the old object with the new key
result[newKey] = obj[key];
});
// return the result
return result;
};
Here's a JSFiddle. The "replace" code above was found here
If you wanted to use classes for models in your application, you could incorporate this code into the constructor or database load method so it's all handled more-or-less automatically.

Retrieve related entities of each, using RetrieveMultipleRequest

I'm trying to retrieve a list of entities from CRM, but I'd like to get each one with the related entities. So far, I've the following code:
FilterExpression filterExpression = new FilterExpression();
ConditionExpression condition = new ConditionExpression(Constants.ModifiedOnAttribute, ConditionOperator.GreaterEqual, lastSync);
filterExpression.AddCondition(condition);
QueryExpression query = new QueryExpression()
{
EntityName = entityName,
ColumnSet = new ColumnSet(attributesMetadata.Select(att => att.Name).ToArray<string>()),
Criteria = filterExpression,
Distinct = false,
NoLock = true
};
RetrieveMultipleRequest multipleRequest = new RetrieveMultipleRequest();
multipleRequest.Query = queryExpression;
RetrieveMultipleResponse response = (RetrieveMultipleResponse)proxy.Execute(multipleRequest);
In the variable response, I can see the EntityCollection attribute, but inside, Related entities always come empty.
I'd like to know if it is possible to retrieve the set of a given entities, with the related entities, using RetrieveMultipleRequest, rather than go one by one using RetrieveRequest.
One approach to retreive related entities data - adding LinkEntities to your query. Example below will make you an idea how to make this:
LinkEntity linkEntity = new LinkEntity("email", "new_emails", "activityid", "new_relatedemail", JoinOperator.Inner);
linkEntity.Columns.AddColumn("versionnumber");
linkEntity.Columns.AddColumn("new_emailsid");
linkEntity.EntityAlias = "related";
query = new QueryExpression("email");
query.ColumnSet.AddColumn("activityid");
query.ColumnSet.AddColumn("versionnumber");
query.Criteria.AddCondition("modifiedon", ConditionOperator.NotNull);
query.LinkEntities.Add(linkEntity);
And then you can access attributes from related entities using EntityAlias you specified above:
foreach (Entity entity in entities.Entities)
{
if ((long)(entity["related.versionnumber"] as AliasedValue).Value > 0)
{
stop = false;
}
}
The RetrieveMultipleRequest is for returning multiple instances of a particular type of entity. I have spent a year using the CRM SDK from C# and I have found no way of populating those related entity collections in a single query. This basically leaves you with two options:
Use the AliasedValue as SergeyS recommends. Remember when querying 1:Many relationships, be aware that you could be returning multiple results for the same parent entity. This is what I use most of the time.
Perform a second query for each relationship you want access to. You'll probably get better performance if you can use an IN statement in your second query, based on the results of the first, rather than performing a separate query for each result of the first.
Below is some pseudo code to show the difference.
var contacts = GetContacts();
// One Request to get the cars for the contacts
var cars = GetCarsWhereContactIdIn(contacts.Select( c => c.new_ContactId));
foreach(var c in contacts){
c.new_Cars.AddRange(cars.where(car => car.new_contactId = c.ContactId));
}
// Verses
var contacts = GetContacts();
foreach(var c in contacts){
// One Request for each contact
c.new_Cars.AddRange(GetCarsForContact(c.ContactId));
}

Couchdb: Access to two documents in a shows function

I'm trying to create a show function which needs to access to two documents: The document in 'doc' reference and another document called 'users'
My function looks like:
function(doc,req){
var friends = doc.friends;
var listFriends = [];
for(int i = 0; i<friends.length; i++){
var phone = friends[i].phone;
if(users[phone] != "" ){
listFriends.push(users[phone]);
}
}
return JSON.stringify(listFriends);
}
I'm not an expert nor javascript neither couchdb. My question is, Is it possible to access to the second document (users) in a similar way like in the code? So far it returns a compilation error.
Thanks
You can only access one document in a CouchDB show function. You could look at using a list function, which works on view results instead of documents.
Create a view where the two documents collate together (appear side-by-side in the view order) and you achieve an effect pretty close to what you wanted to achieve with the show function.

Resources