How to add extra data to a member in MDS? - sql

I'm running MDS on a virtual machine and trying to access the service from my host OS.
I've been able to add something to the database but my data is all over the place and in the Master Data Manager (website) I don't see the new member.
I suppose I shouldn't be using Attributes but something else but what and how? Are there tutorials because I can't find any ...?
Here's the code I'm using:
International international = new International();
EntityMembers entityMembers = new EntityMembers();
// Set the modelId, versionId, and entityId.
entityMembers.ModelId = new Identifier { Name = modelName };
entityMembers.VersionId = new Identifier { Name = versionName };
entityMembers.EntityId = new Identifier { Name = entityName };
entityMembers.MemberType = memberType;
Collection<Member> members = new Collection<Member>();
Member aNewMember = new Member();
aNewMember.MemberId = new MemberIdentifier() { Name = employee.FullName, Code = aNewCode, MemberType = memberType };
Collection<MDS.Attribute> attributes = new Collection<MDS.Attribute>();
MDS.Attribute attrOrgUnit = new MDS.Attribute();
attrOrgUnit.Identifier = new Identifier() { Name = "OrganizationalUnit" };
attrOrgUnit.Value = employee.OrganizationalUnit;
attrOrgUnit.Type = AttributeValueType.String;
attributes.Add(attrOrgUnit);
aNewMember.Attributes = attributes.ToArray();
members.Add(aNewMember);
entityMembers.Members = members.ToArray();
// Create a new entity member
OperationResult operationResult = new OperationResult();
clientProxy.EntityMembersCreate(international, entityMembers, false, out operationResult);
HandleOperationErrors(operationResult);

I have been able to fix my own problem.
First of all: creating separate variables with collections and converting them to arrays afterwards is not necessary. The code from the tutorials works but fails to mention that, when adding the service reference, you have to configure it (right-click on the service reference -> configure) to use Collections as "Collection type" instead of arrays and to generate message contracts.
Second, the code above with the attributes is correct and works perfectly. The problem I had which failed to add messages with attributes was unrelated. It was a connection/authentication problem between my Host OS and Guest OS.
Hope this helps someone.

Related

why it is showing project name as "Default" in sitefinity dashboard portal once I run it

I am new to Sitefinity. But I followed steps from tutorial and created the one project named as "SFcmsDemo" and when I run this project and Sitefinity dashboard appears on localhost it is showing name as "Default" instead of "SFcmsDemo", The tutorial I read is showing the correct name in that but when I tried it is showing as "Default". Can anyone please help me find out the root cause and solution for this. I am attaching some screenshot which will help to understand more. Thanks.
Default can be easily changed if you click on it and then Manage Site.
UPDATE
From the decompiled Telerik.Sitefinity.dll (v.12.2):
internal static Site GetOrCreateDefaultSite()
{
Site site;
string str = "CreateDefaultSite";
MultisiteManager manager = MultisiteManager.GetManager(null, str);
using (ElevatedModeRegion elevatedModeRegion = new ElevatedModeRegion(manager))
{
ProjectConfig projectConfig = Config.Get<ProjectConfig>();
Guid siteMapRootNodeId = projectConfig.DefaultSite.SiteMapRootNodeId;
Site site = (
from s in manager.GetSites()
where s.SiteMapRootNodeId == siteMapRootNodeId
select s).FirstOrDefault<Site>();
if (site == null)
{
site = (projectConfig.DefaultSite.Id == Guid.Empty ? manager.CreateSite() : manager.CreateSite(projectConfig.DefaultSite.Id));
site.IsDefault = true;
site.IsOffline = false;
site.site = projectConfig.DefaultSite.site;
site.SiteMapRootNodeId = siteMapRootNodeId;
site.Name = (projectConfig.ProjectName != "/" ? projectConfig.ProjectName : "Default");
....
Note in the last line how it looks in the projectConfig.ProjectName value and if it is equal to "/" then it sets it to "Default"
Now, if we look at the ProjectConfig there is this:
[Browsable(false)]
[ConfigurationProperty("projectName", DefaultValue="/")]
[ObjectInfo(typeof(ConfigDescriptions), Title="ProjectNameTitle", Description="ProjectNameDescription")]
public string ProjectName
{
get
{
return (string)this["projectName"];
}
internal set
{
this["projectName"] = value;
}
}
So, default value is indeed "/", so that's why when the site is created it has a name of Default.

Using TFS API to rollback a changeset

I am trying to use the TFS API to rollback a changeset.
I tried using all Workspace.Rollback methods but the action does nothing (The GetStatus returned says NoActionNeeded:true).
Has anyone managed to get this to work and can send a working code sample?
From the documentation of the method:
public GetStatus Rollback(
string[] paths,
RecursionType recursion,
VersionSpec itemSpecVersion,
VersionSpec versionFrom,
VersionSpec versionTo,
LockLevel lockLevel,
RollbackOptions options,
string[] itemAttributeFilters
)
I do not understand what the parameter VersionSpec itemSpecVersion means.
It says 'The version spec that identifies the item to which the user is referring.' but then how does it differ from the parameter versionFrom?
What should I pass as the itemAttributeFilters (the last paramter)?
You can rollback changeset programmatically with the following code:
TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("tfsCollectionURL"));
VersionControlServer vcs = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));
string workingDirectory = #"localPath";
string[] workigDnirectoryArr = new string[] { workingDirectory };
Workspace ws = vcs.GetWorkspace("$/serverPath");
int fromCS = 456; //changesetid
int toCS = 495; //changesetid
VersionSpec versionSpecFrom = new ChangesetVersionSpec(fromCS);
VersionSpec versionSpecTo = new ChangesetVersionSpec(toCS);
var status = ws.Rollback(workigDnirectoryArr, RecursionType.None,null, versionSpecFrom, versionSpecTo,LockLevel.None,RollbackOptions.None,null);

Adding roles to users in team area in RTC

I need to add users ( users are already present in repository. I only need to add them.) and roles from a CSV file to team areas. Project area and Team Area already exists.I could successfully add users but not the roles from csv file.
The CSV file format is :
Project name,Team Area name,Members,roles
Project1,User_Role_TA,Alex,Team Member
Project2,TA2,David,Scrum Master
Below is the code for it. It successfully add the users and currently add roles to them from project area but I need to add roles to the users from CSV file. In the below code, If I can get roles from csv file in the line "IRole[] availableRoles = clientProcess.getRoles(area, null);" , I think it should resolve the issue. I am not getting any error but it doesn't add the roles.
while((row = CSVFileReader.readLine()) != null )
{
rowNumber++;
st = new StringTokenizer(row,",");
while (st.hasMoreTokens()) {
projectAreaList.add(st.nextToken());
teamAreaList.add(st.nextToken());
membersList.add(st.nextToken());
roleList.add(st.nextToken());
}
}
for (int i=1; i<rowNumber; i++)
{
projectAreaName = projectAreaList.get(i);
teamAreaName = teamAreaList.get(i);
members = membersList.get(i);
member_roles =roleList.get(i);
URI uri = URI.create(projectAreaName.replaceAll(" ", "%20"));
IProjectArea projectArea = (IProjectArea) processClient.findProcessArea(uri, null, null);
if (projectArea == null)
{
System.out.println("Project Area not found");
}
if (!teamAreaName.equals("NULL")){
List <TeamAreaHandle> teamlist = projectArea.getTeamAreas();
ITeamAreaHandle newTAHandle = findTeamAreaByName(teamlist,teamAreaName,monitor);
if(newTAHandle == null) {
System.out.println("Team Area not found");
}
else {
ITeamArea TA = (ITeamArea)teamRepository.itemManager().fetchCompleteItem(newTAHandle,ItemManager.DEFAULT,monitor);
IRole role = getRole(projectArea);
IContributor user = teamRepository.contributorManager().fetchContributorByUserId(members,monitor);
/*role1 = getRole(area).getId();
if(role1.equalsIgnoreCase(member_roles))
{
user_role = getRole(area);
}*/
IProcessAreaWorkingCopy areaWc = (IProcessAreaWorkingCopy)service.getWorkingCopyManager().createPrivateWorkingCopy(TA);
areaWc.getTeam().addContributorsSettingRoleCast(
new IContributor[] {user},
new IRole[] {role});
areaWc.save(monitor);
}
public static IRole getRole(IProcessArea area) throws TeamRepositoryException {
ITeamRepository repo = (ITeamRepository) area.getOrigin();
IProcessItemService service =(IProcessItemService) repo
.getClientLibrary(IProcessItemService.class);
IClientProcess clientProcess = service.getClientProcess(area, null);
IRole[] availableRoles = clientProcess.getRoles(area, null);
for (int i = 0; i < availableRoles.length; i++) {
return availableRoles[i];
}
throw new IllegalArgumentException("Couldn't find role");
}
Some of the API you are trying to use are private in RTC3.x
See this thread for different options (a bit similar to your code):
ProjectAreaWorkingCopy workingCopy = (ProjectAreaWorkingCopy)manager.getWorkingCopy(project);
this class extends to ProcessAreaWorkingCopy
public class ProjectAreaWorkingCopy extends ProcessAreaWorkingCopy implements IProjectAreaWorkingCopy
In ProcessAreaWorkingCopy setRoleCast retrieves the team and sets the role.
One can set the role at the team level via
team.setRoleCast(contributor, roleCast);
# or
projWc.getTeam().addContributorsSettingRoleCast(new IContributor[] {contributor}, roles);
The OP Kaushambi Suyal reports:
Created a method as mentioned in the thread with few changes and it worked.
Also we need to pass the process area here and not the project area, because I am trying to add roles to users in team area and not project area.

API to update users image - Identity Extended Properties not saving

I'm trying to write a small script to set all users images to their AD image, I did some jumping around in ILSpy and found out what to set using the TFS Server API, however the code needs to be a bit different because I'm using the client API instead.
The code I have below can succesfully iterate through all the users in tfs, look them up in AD, grab the thumbnail, set the property on the TFS identity. But I can't for the life of me figure get the extended property to save back into TFS.
The code doesn't exception, but the property isn't set to the value I set it to when I next run the application.
Does anyone know the way to save extended properties via the client api?
Microsoft.TeamFoundation.Client.TeamFoundationServer teamFoundationServer = new Microsoft.TeamFoundation.Client.TeamFoundationServer("{URL TO TFS}");
FilteredIdentityService service = teamFoundationServer.GetService<FilteredIdentityService>(); ;
IIdentityManagementService2 service2 = teamFoundationServer.GetService<IIdentityManagementService2>();
foreach (var identity in service.SearchForUsers(""))
{
var user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), identity.UniqueName);
if (user == null) continue;
var de = new System.DirectoryServices.DirectoryEntry("LDAP://" + user.DistinguishedName);
var thumbNail = de.Properties["thumbnailPhoto"].Value as byte[];
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.Data", thumbNail);
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.UploadDate", DateTime.UtcNow);
service2.UpdateExtendedProperties(identity);
}
Figured it out, needed to set some additional properties.
Microsoft.TeamFoundation.Client.TeamFoundationServer teamFoundationServer = new Microsoft.TeamFoundation.Client.TeamFoundationServer("http://urltotfs");
FilteredIdentityService service = teamFoundationServer.GetService<FilteredIdentityService>(); ;
IIdentityManagementService2 service2 = teamFoundationServer.GetService<IIdentityManagementService2>();
foreach (var identity in service.SearchForUsers(""))
{
var user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), identity.UniqueName);
if (user == null) continue;
var de = new System.DirectoryServices.DirectoryEntry("LDAP://" + user.DistinguishedName);
var thumbNail = de.Properties["thumbnailPhoto"].Value as byte[];
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Data", thumbNail);
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Type", "image/png");
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Id", Guid.NewGuid().ToByteArray());
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.Data", null);
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.UploadDate", null);
service2.UpdateExtendedProperties(identity);
}

SharpArch.Data.NHibernate.Repository.SaveOrUpdate() don't save

I have this code for filling DB, but after finish, DB is still empty. Only number in hibernate_unique_key table is higher.
The next thing which is interesting is, that during debugging instances has id, after save, but not like 1,2,3... but very high like 60083, 60084, ... etc. (It not seems normal, because there is only several rows for save).
Before that, there was some problems with references and so on, but now there is no error message or exception.
code is there:
using System;
using NHibernate.Cfg;
using SharpArch.Data.NHibernate;
using LaboratorniMetody.Data.NHibernateMaps;
using SharpArch.Core.PersistenceSupport;
using LaboratorniMetody.Core;
namespace LaboratorniMetody.FillSchema
{
class Program
{
private static Configuration configuration;
static void Main(string[] args)
{
configuration = NHibernateSession.Init(new SimpleSessionStorage(), new String[] { "LaboratorniMetody.Data" },
new AutoPersistenceModelGenerator().Generate(),
"../../../../app/LaboratorniMetody.Web/NHibernate.config");
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
}
}
}
I use DB schema genereted by NUnit from Project.Core classes.
Do you have any ideas where i should find problem? I have 2 very similar project which working with no problem. I Copyed this code from one of them and there is practicly no differents (except DB model and so on.)
You need to do your changes in a transaction and commit the transaction afterwards.
using(var tx = NHibernateSession.Current.BeginTransaction())
{
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
tx.Commit();
}
I advise to look at the SharpArchContrib project wiki, which has some samples on using SharpArch in a windows app/service and how to use Transaction attributes from there.
https://github.com/sharparchitecture/Sharp-Architecture-Contrib/wiki/