TFS 2017+, C#, set Default Area - c#

I am working on creating a team in TFS using C# and the dll's provided. I'm having a hard time setting the default Area and could use some help.
VssCredentials vc = new VssCredentials(true);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(TFS_CONNECTION_URL), vc);
tpc.Authenticate();
TfsTeamService teamService = tpc.GetService<TfsTeamService>();
ProjectInfo projectInfo = cssService.GetProjectFromName(TEAM_PROJECT_NAME);
TeamFoundationTeam team = teamService.CreateTeam(projectInfo.Uri, teamName, teamDescription, null);
ICommonStructureService css = tpc.GetService<ICommonStructureService>();
foreach (NodeInfo ni in css.ListStructures(projectInfo.Uri))
{
//ProjectModelHierarchy is for areas
if (ni.StructureType.Equals("ProjectModelHierarchy"))
{
string n0Uri = ni.Uri;
//creates the team name area under the top level team project area.
string n1Uri = css.CreateNode(teamName, n0Uri);
}
}
//AND HERE'S WHERE I WANT TO SET THE DEFAULT AREA
//I have tried the following but it doesn't work
//team.SetProperty("defaultArea", "\\" + teamName);
I have tried many combinations of the property name but to no avail. And I assure you, this code above does create a team in my team project in TFS.

var tfv = new TeamFieldValue();
var ts = team.TeamSettings;
tfv.IncludeChildren = true;
tfv.Value = "\\" + teamName;
ts.TeamFieldValues = new []{tfv};

TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri("tfsuri"));
TfsTeamService teamService = ttpc.GetService<TfsTeamService>();
ICommonStructureService icss = ttpc.GetService<ICommonStructureService>();
ProjectInfo projectInfo = icss.GetProjectFromName("ProjectName");
var newteam = teamService.CreateTeam(projectInfo.Uri, "TeamName", null, null);
TeamSettingsConfigurationService tscs = ttpc.GetService<TeamSettingsConfigurationService>();
IEnumerable<Guid> teamsid = new Guid[] {newteam.Identity.TeamFoundationId };
var teamsconfig = tscs.GetTeamConfigurations(teamsid);
TeamConfiguration tc = teamsconfig.First();
TeamFieldValue tfv = new TeamFieldValue();
tfv.IncludeChildren = true;
tfv.Value = "AreaPath";
tc.TeamSettings.TeamFieldValues = new TeamFieldValue[] {tfv};
tc.TeamSettings.BacklogIterationPath = "IterationPath";
tscs.SetTeamSettings(tc.TeamId,tc.TeamSettings);

Related

"CSOMUnknownUser" It occurrs when I execute the draft project query

I am trying to create a new project in MS Project Server 2016 using PSI C#. It creates a new project along with the task but when I tried to set the values of some custom fields and try to load/execute the query, it returns "CSOMUnknownUser" error.
Can anyone help me out to sort out this problem. my sample code is here
worker = new Classes.ProjectServerWorker();
worker.projContext = new Microsoft.ProjectServer.Client.ProjectContext(SPContext.Current.Web.Url);
NetworkCredential cred = new NetworkCredential();
cred.Domain = "abc";
cred.UserName = "abc";
cred.Password = "abc";
worker.projContext.Credentials = cred;
ProjectCreationInformation newProj = new ProjectCreationInformation();
//ProjectContext projContext = new ProjectContext(SPContext.Current.Web.Url + "/sites/PWA");
try
{
newProj.Id = Guid.NewGuid();
string strGuidID = newProj.Id.ToString();
newProj.Name = "new project title";
newProj.Description = "new project requirement details";
PublishedProject newPublishedProj = worker.projContext.Projects.Add(newProj);
QueueJob qJob = worker.projContext.Projects.Update();
//jobState = worker.projContext.WaitForQueue(qJob, timeoutSeconds);
IsProjectCreated = true;
worker.projContext.Load(worker.projContext.Projects);
worker.projContext.ExecuteQuery();
var proj = worker.projContext.Projects.First(p => p.Name == newProj.Name);
worker.projContext.ExecuteQuery();
var draftProj = proj.CheckOut();
// Creating Task under project
TaskCreationInformation newtask = new TaskCreationInformation();
newtask.Name = "First Task";
newtask.Start = DateTime.Today;
newtask.Finish = DateTime.Today.AddDays(35);
newtask.Id = Guid.NewGuid();
newtask.IsManual = false;
DraftTask drafttask = draftProj.Tasks.Add(newtask);
draftProj.Update();
draftProj.Publish(true); // Publish and check-in the project
worker.projContext.ExecuteQuery();
// Setting Custom Fields data
var guidID = new Guid(strGuidID);
var projcs = worker.projContext.Projects.GetByGuid(guidID);
var draftProjCS = projcs.CheckOut().IncludeCustomFields;
worker.projContext.Load(draftProjCS);
worker.projContext.ExecuteQuery();
string WorkRequestTitle = "new project";
var field1 = worker.projContext.CustomFields.Where(a => a.InternalName== ProjectFields.WorkRequestTitle).FirstOrDefault();
draftProjCS.SetCustomFieldValue(field1.InternalName, WorkRequestTitle);

Get current iteration from TFS

I need to get current iteration's path from TFS project. I'm able to use REST API query <server>/<project>/_apis/work/teamsettings/iterations?$timeframe=current&api-version=v2.0-preview but I don't want to perform query and parse JSON response. I want to use appropriate API in .NET client libraries for VSTS (and TFS).
I have an instance of the VssConnection. How can I get the path of current iteration from this object?
You can get the current iteration using the WorkHttpClient without having to iterate:
var creds = new VssBasicCredential(string.Empty, "personalaccesstoken");
VssConnection connection = new VssConnection(new Uri("url"), creds);
var workClient = connection.GetClient<WorkHttpClient>();
var teamContext = new TeamContext(teamId);
teamContext.ProjectId = projectId;
var currentIteration = await workClient.GetTeamIterationsAsync(teamContext, "current");
The simplest way I've found to do it was by using ICommonStructureService4 and TeamSettingsConfigurationService methods:
static TfsTeamProjectCollection _tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection("<tfsUri>")
(...)
static string GetCurrentIterationPath()
{
var css = _tfs.GetService<ICommonStructureService4>();
var teamProjectName = "<teamProjectName>";
var project = css.GetProjectFromName(teamProjectName);
var teamName = "<teamName>";
var teamSettingsStore =
_tfs.GetService<TeamSettingsConfigurationService>();
var settings = teamSettingsStore
.GetTeamConfigurationsForUser(new[] { project.Uri })
.Where(c => c.TeamName == teamName)
.FirstOrDefault();
if (settings == null)
{
var currentUser = System.Threading.Thread.CurrentPrincipal.Identity.Name;
throw new InvalidOperationException(
$"User '{currentUser}' doesn't have access to '{teamName}' team project.");
}
return settings.TeamSettings.CurrentIterationPath;
}
And returning the TeamSettings.CurrentIterationPath property.
I found a solution using VssConnection:
var workClient = connection.GetClient<WorkHttpClient>();
var iterations = workClient.GetTeamIterationsAsync(new TeamContext("project-name")).Result;
var currentDate = DateTime.Now.Date;
var currentIterationPath = iterations
.Select(i => new { i.Path, i.Attributes })
.FirstOrDefault(i => currentDate >= i.Attributes.StartDate &&
currentDate <= i.Attributes.FinishDate)
?.Path;
Here is a case provides a solution: Get the current iteration path from TFS
private static XmlNode currentIterationNode;
TfsTeamProjectCollection tpc = TFSConncetion(#"http://tfs/url");
ICommonStructureService4 css = tpc.GetService<ICommonStructureService4>();;
WorkItemStore workItemStore = new WorkItemStore(tpc);
foreach (Project teamProject in workItemStore.Projects)
{
if (teamProject.Name.Equals("TeamProjectNameGoesHere"))
{
NodeInfo[] structures = css.ListStructures(teamProject.Uri.ToString());
NodeInfo iterations = structures.FirstOrDefault(n => n.StructureType.Equals("ProjectLifecycle"));
if (iterations != null)
{
XmlElement iterationsTree = css.GetNodesXml(new[] { iterations.Uri }, true);
XmlNodeList nodeList = iterationsTree.ChildNodes;
currentIterationNode = FindCurrentIteration(nodeList);
String currentIterationPath = currentIterationNode.Attributes["Path"].Value;
}
}
}

How do I use AWS SDK for .Net to create an image to an instance I have? (AMI)

I have an Amazon EC2 instance and I need to be able to create an AMI (image) from it programmatically. I'm trying the following:
CreateImageRequest rq = new CreateImageRequest();
rq.InstanceId = myInstanceID;
rq.Name = instance.KeyName;
rq.Description = "stam";
rq.NoReboot = true;
IAmazonEC2 ec2;
AmazonEC2Config ec2conf = new AmazonEC2Config();
ec2 = AWSClientFactory.CreateAmazonEC2Client(ec2conf);
// CreateImageResponse imageResp;
Amazon.EC2.Model.CreateImageResponse imageResp = null;
try
{
imageResp = ec2.CreateImage(rq);
}
catch (AmazonServiceException ase)
{
MessageBox.Show(ase.Message);
}
The result is always an AmazonServiceException saying that there is a NameResolutionFailure.
How do I overcome this? I tried different possible "name" possibilities but cannot find the right one.
string amiID = ConfigurationManager.AppSettings[AmazonConstants.AwsImageId];
string keyPairName = ConfigurationManager.AppSettings[AmazonConstants.AwsKeyPair];
List<string> groups = new List<string>() { ConfigurationManager.AppSettings[AmazonConstants.AwsSecurityGroupId] };
var launchRequest = new RunInstancesRequest()
{
ImageId = amiID,
InstanceType = ConfigurationManager.AppSettings[AmazonConstants.AwsInstanceType],
MinCount = 1,
MaxCount = 1,
KeyName = keyPairName,
SecurityGroupIds = groups,
SubnetId = ConfigurationManager.AppSettings[AmazonConstants.AwsSubnetId]
};
RunInstancesResponse runInstancesResponse = amazonEc2client.RunInstances(launchRequest);
RunInstancesResult runInstancesResult = runInstancesResponse.RunInstancesResult;
Reservation reservation = runInstancesResult.Reservation;
Problem eventually solved!
it turned out thyat some codelines were doing things which were already done already and removing this part:
IAmazonEC2 ec2;
AmazonEC2Config ec2conf = new AmazonEC2Config();
ec2 = AWSClientFactory.CreateAmazonEC2Client(ec2conf);
// CreateImageResponse imageResp;
Amazon.EC2.Model.CreateImageResponse imageResp = null;
Made things clearer and no wrong repetitions happened! Now it works!

Search user by profile property

How i can search by profile property? MSDN say use ProfileSearchManager, but it not working.
I want search users by MobilePhone property.
SPServiceContext serviceContext = SPServiceContext.GetContext(site);
UserProfileManager upm = new UserProfileManager(serviceContext);
ProfileSearchManager sp = ProfileSearchManager.GetProfileSearchManager(serviceContext);
string[] searchPattern = { "123" };
ProfileBase[] searchResults = sp.Search(searchPattern, ProfileSearchFlags.User);
foreach (ProfileBase profile in searchResults)
{
Console.WriteLine(profile.DisplayName);
}
using (SPSite site = new SPSite(siteUrl))
{
using (var qRequest = new KeywordQuery(site)
{
QueryText = "MobilePhone:*" +"123" ,
EnableQueryRules = true,
EnableSorting = false,
SourceId = new Guid("Enter here Result Source Guid"),
TrimDuplicates = false
})
{
//Get properties you want here
qRequest.SelectProperties.Add("FirstName");
qRequest.SelectProperties.Add("LastName");
SearchExecutor e = new SearchExecutor();
ResultTableCollection rt = e.ExecuteQuery(qRequest);
var tab = rt.Filter("TableType", KnownTableTypes.RelevantResults);
var result = tab.FirstOrDefault();
DataTable resultTable = result.Table;
}
}

How to Select feature and highlight in ArcGIS using C#

Hi I have the following code below for zooming into an arcGIS object based on the attribute now all I need is to be able to highlight that area with a select feature (The feature where you right-click on the area on the map and do select feature).
Currently I have an event which will do the zoom.I want to add this select to the same attribute as well.
Thank you in advance!!!
ESRI.ArcGIS.Carto.ILayer layer = GetLayersClass.GetFieldBoundaryLayer;
if (layer is ESRI.ArcGIS.Carto.IGroupLayer)
{
ESRI.ArcGIS.Carto.IGroupLayer groupLayer = layer as ESRI.ArcGIS.Carto.IGroupLayer;
ICompositeLayer pCompositeLayer = layer as ICompositeLayer;
int layers = pCompositeLayer.Count;
ILayer pLayer = pCompositeLayer.Layer[0];
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IQueryFilter pFilter = new QueryFilterClass();
pFilter.WhereClause = "RightID = '" + selectedRightID.ToString() + "'";
IFeatureCursor pFeatureCursor = pFeatureClass.Search(pFilter, false);
IFeature pFeature = pFeatureCursor.NextFeature();
if (pFeature == null)
{
System.Windows.Forms.MessageBox.Show("This section doesn't exist");
return;
}
IApplication m_application = ArcMap.Application;
IMxDocument pMxDoc = (IMxDocument)m_application.Document;
IActiveView pActiveView = (IActiveView)pMxDoc.FocusMap;
IEnvelope pEnv = pFeature.Shape.Envelope;
pEnv.Expand(1.1, 1.1, true);
pActiveView.Extent = pEnv;
pActiveView.Refresh();
I tried by adding this code which I think will add the particular feature to the selection.
but no luck with that as well.
IFeatureSelection pfeatSelect = pFeatureLayer as IFeatureSelection;
pfeatSelect.Add(pFeature);
If I understand you correctly, all you need is this:
IFeatureSelection featSelect = pFeatureLayer as IFeatureSelection;
featSelect.SelectFeatures(pFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
This will select all Features that match your filter.
This solution is working for me
IFeatureLayer PFeaLayer = (IFeatureLayer)pLayer;
IFeatureSelection PFeaSel = (IFeatureSelection)PFeaLayer;
int OIDIndex = PFeature.Fields.FindField("OBJECTID");
PFeaSel.SelectionSet.Add(Convert.ToInt32(PFeature.get_Value(OIDIndex)));
ISelectionSet PFeaSelSet = PFeaSel.SelectionSet;
IEnumGeometry pEnumGeom = new EnumFeatureGeometryClass();
IEnumGeometryBind pEnumGeomBind = (IEnumGeometryBind)pEnumGeom;
pEnumGeomBind.BindGeometrySource(null, PFeaSelSet);
IGeometryFactory pGeomFactory = new GeometryEnvironmentClass();
IGeometry pGeom = pGeomFactory.CreateGeometryFromEnumerator(pEnumGeom);
IMxDocument pMxDoc = ArcMap.Document as IMxDocument;
IActiveView activeView = pMxDoc.ActiveView;
double midX = (pGeom.Envelope.XMax + pGeom.Envelope.XMin) / 2;
double midY = (pGeom.Envelope.YMax + pGeom.Envelope.YMin) / 2;
IPoint pPoint = new PointClass();
pPoint.SpatialReference = pGeom.Envelope.SpatialReference;
pPoint.PutCoords(midX, midY);
pPoint.Project(activeView.Extent.SpatialReference);
IEnvelope pCurrentEnvelope = activeView.Extent;
pCurrentEnvelope.CenterAt(pPoint);
activeView.Extent = pCurrentEnvelope;
activeView.Refresh();

Categories