Access the Source Control Explorer in TFS from C#.net code - c#

Here is the code which I have written to access the Projects and the team, but it shows some error. I want to access the project and then the Source Code present in the Source Control Explorer in the Project/Team.
Uri _serverUri = new Uri("MyURI");
string _teamProjectName = "MyProject";
TfsTeamProjectCollection collection =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(_serverUri);
// Retrieve the project URI. Needed to enumerate teams.
var css4 = collection.GetService<ICommonStructureService>();
ProjectInfo projectInfo = css4.GetProjectFromName(_teamProjectName);
// Retrieve a list of all teams on the project.
TfsTeamService teamService = collection.GetService<TfsTeamService>();
var allTeams = teamService.QueryTeams(projectInfo.Uri);
allTeams.ToList().ForEach
(
allteams => { Console.WriteLine(allteams); });
The error which it shows is "The type or namespace 'Core' does not exist in the namespace Microsoft.TeamFoundation.Server
I also want to access the source control, so if anyone can help me with both of my issues.

Related

create proxmox Vm using c#

I am totally new to proxmox VE and i want to create a Vitual Machine inside proxmox using C# console application.
I have search a lot and i only found an API program which has all the functionality but i don't know how to use it. https://github.com/EnterpriseVE/eve2pve-api-dotnet
Can someone help me how to create and delete a vm in proxmox using this API in detail or anyone have any different approach to do this
Usage:
var client = new Client("10.92.90.91");
if (client.Login("root", "password"))
{
var vm = client.Nodes["pve1"].Qemu[100];
//config vm
var config = vm.Config.VmConfig();
Console.WriteLine(Client.ObjectToJson(config.Response));
//create snapshot
var response = vm.Snapshot.Snapshot("pippo2311");
//update snapshot description
vm.Snapshot["pippo2311"].Config.UpdateSnapshotConfig("descr");
//delete snapshot
vm.Snapshot["pippo2311"].Delsnapshot();
//list of snapshot
foreach (var snapshot in vm.Snapshot.SnapshotList().Response.data)
{
Console.WriteLine(Client.ObjectToJson(snapshot));
Console.WriteLine(snapshot.name);
}
client.ResponseType = "png";
var dataImg = client.Nodes["pve1"].Rrd.Rrd("cpu", "day").Response;
Console.WriteLine("<img src=\"{dataImg}\" \>");
}
Get the project from github
Compile the project
Add reference to the project's dll
Use it just like the example above

Sharepoint2013 Site - CSOM - Update Navigation Settings

We need to update Global and Current Navigation Settings for the site.
Below is our code
var publishingWeb = PublishingWeb.GetPublishingWeb(this.CC, subWeb);
// WebNavigationSettings
var webNavigationSettings = new WebNavigationSettings(this.CC, subWeb);
webNavigationSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;
webNavigationSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;
// CSOM don't have: publishingWeb.Navigation.GlobalIncludeSubSites.
subWeb.AllProperties["__GlobalIncludeSubSites"] = "True"; //TODO: Verify why it is not working.
subWeb.AllProperties["__GlobalIncludePages"] = "True"; //TODO: Verify why it is not working.
subWeb.Update();
webNavigationSettings.Update(tSession);
CC.Load(subWeb, WEB_INCLUDES);
// Apply the load
CC.ExecuteQuery();
As we are using CSOM, we did not have
publishingWeb.Navigation.GlobalIncludeSubSites
.
So we tried to set using AllProperties to set GlobalIncludeSubSites and GlobalIncludePages.
But those properties are not getting set.
Is there any way to fix this problem.
I went throught article http://discoveringsharepoint.wordpress.com/2013/03/19/programmatically-set-navigation-settings-in-sharepoint-2013/
But it uses namespace : Microsoft.SharePoint.Publishing.Navigation
But our's namespace is : Microsoft.SharePoint.Client.Publishing.Navigation
As we are doing from client server object model.
Is there any way to solve this ?
Thanks
In SharePoint 2013 was introduced a new Microsoft.SharePoint.Client.Publishing and Microsoft.SharePoint.Client.Publishing.Navigation namespaces in CSOM API. But unfortunately it is not supported to modify navigation settings using WebNavigationSettings class since properties are exposes as a read-only.
You could utilize the following approach for that purpose. ClientPortalNavigation.cs represents a CSOM counterpart for SSOM PortalNavigation Class.
The following example demonstrates how to utilize that class and update Navigation settings:
using (var ctx = new ClientContext(webUri))
{
var navigation = new ClientPortalNavigation(ctx.Web);
navigation.CurrentIncludePages = true;
navigation.GlobalIncludePages = false;
navigation.SaveChanges();
}
ClientPortalNavigation.cs is compatible with SharePoint 2010/2013
CSOM APIs.
References
Access and Manipulate Navigation Settings via SharePoint Client Object Model
ClientPortalNavigation.cs

get specific projects that a user is a part of

Here I am using IIdentityManagementService to retrieve a specified user by name. Now I want to retrieve only those team projects which they are a member of and can create tasks/workitems for in TFS. My program allows a user to create a task in TFS and I only want them to be able to see a list of the projects which they have access to for creating tasks/work items.
var tfsTpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://dotnettfs:8080/tfs/"));
identityService = tfsTpc.GetService<IIdentityManagementService>();
userId = identityService.ReadIdentity(
IdentitySearchFactor.DisplayName,
strOutlookUser,
MembershipQuery.Direct,
ReadIdentityOptions.None
);
userTpc = new TfsTeamProjectCollection(tfsTpc.Uri, userId.Descriptor);
cssService = (ICommonStructureService4)userTpc.GetService(typeof(ICommonStructureService4));
wis = userTpc.GetService<WorkItemStore>();
lstAllProjects.AddRange(cssService.ListAllProjects().ToList());
List<string> lstViewProjectNames = lstAllProjects.Select(a => a.Name).ToList();
Right now, the list shows all projects within that software collection when I want it to show only those projects which the retrieved user has access to.
then they are able to create a task and specify the iteration and area for one of those projects.
var store = wis.Projects[0]; //should be a specified project, not the first element.
WorkItem pbi = new WorkItem(store.WorkItemTypes["Product Backlog Item"]);
pbi.IterationPath = lstIterations.Where(a => a.Name == selectedIteration.ToString())
.Select(a => a.Path).First().ToString();
pbi.AreaPath = lstAreas.Where(a => a.Name == selectedArea.ToString())
.Select(a => a.Path).First().ToString();
I only want them to be able to see a list of the projects which they
have access to for creating tasks/work items.
Work items are tied to areas and areas are tied to team projects.
The basic steps are:
1) Connect to TFS as the user in question
2) Retrieve the team project in question
3) Get the areas for the team project in question
4) Check each one for the ability to create work items (you can probably get away with doing the recursive check on just the root area node)
The usings you will need (might not need all):
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
IIdentityManagementService identityManagementService = tpc.GetService<IIdentityManagementService>();
TfsTeamProjectCollection tpc = GetTfsCollection();
TeamFoundationIdentity identity = identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, #"Domain\username", MembershipQuery.None, ReadIdentityOptions.None);
TfsTeamProjectCollection impersonatedTPC = new TfsTeamProjectCollection(new Uri(this._tfsUri, this._tfsCollectionName), identity.Descriptor);
WorkItemStore impersonatedWIS = impersonatedTPC.GetService<WorkItemStore>();
ProjectCollection impersonatedProjects = impersonatedWIS.Projects;
foreach (Project p in impersonatedProjects)
{
if (p.Name == "My Team Project")
{
NodeCollection areas = p.AreaRootNodes;
foreach (Node area in areas)
{
if (area.HasWorkItemWriteRightsRecursive)
{
//They do have rights
}
}
}
}
Note that I call GetTfsCollection() which my own user defined function (this is just the class that I constructed with, passing in the root tfs uri and the collection name as string). I also didn't put in any exception handling, just showing the basics:
private TfsTeamProjectCollection GetTfsCollection()
{
return TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(this._tfsUri, this._tfsCollectionName));
}

How to get Workspace object in new TeamFoundation 2013 Templates

In new version of TeamFoundation 2013 default build templates, the Workspace variable is missing. It is needed as intput parameter for few key activities like ConvertWorkspaceItem. How do I get current workspace for TfvcTemplate.12.xaml templates? I've tried to use this msdn thread but it's not working for me (returns null workspace name). Any suggestions?
There's a new activity in 2013 called GetLocalPath that replaces ConvertWorkspaceItem.
The activity is under the Microsoft.TeamFoundation.Build.Activities.Core namespace in the Microsoft.TeamFoundation.Build.Activities assembly.
It uses the LocalPathProvider class that aggregates all workspaces used in the build and exposes path translation for all of them in one place. This basically removes the dependency of knowing the workspace in order to translate server paths to local paths and allows you to use as many workspaces as you want without worrying about breaking something down the line.
When MS takes something away, it's usually for a good reason. "hacking" is really not necessary.
I went with a hack using internal classes from Microsoft.TeamFoundation.Build.Activities.dll (used by microsoft to create workspace name). You need to create custom activity with following code:
public sealed class GetDefaultWorkspace : BaseActivity<Workspace>
{
public override Activity CreateBody()
{
var type = typeof(TfGetSources).Assembly.GetType("Microsoft.TeamFoundation.Build.Activities.TeamFoundation.TfGetSources+GetDefaultWorkspaceName");
var activity = (CodeActivity<string>)Activator.CreateInstance(type);
var sequence = new Sequence();
var workspaceName = new Variable<string>();
sequence.Variables.Add(workspaceName);
sequence.Activities.Add(activity);
activity.Result = (OutArgument<string>) workspaceName;
sequence.Activities.Add(new GetWorkspace
{
Name = workspaceName,
Result = new LambdaReference<Workspace>(ctx => Result.Get(ctx))
});
return sequence;
}
}
This answer might work better for some people. ghord's answer works well, and passes the Workspace back where it can be used in the XAML. However, for my purposes I only want the workspace in my custom TFS activities, so I ended up with this alternative...
public sealed class CustomActivity : CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
// get workspace
var buildDetail = context.GetExtension<IBuildDetail>();
var buildAgent = context.GetExtension<IBuildAgent>();
var buildDirectory = buildAgent.GetExpandedBuildDirectory(buildDetail.BuildDefinition);
var workspacePath = Path.Combine(buildDirectory, "src");
var wsInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(wsInfo.ServerUri);
tfs.Connect(ConnectOptions.None);
var vcs = tfs.GetService<VersionControlServer>();
// finally can get to the workspace here
var workspace = vcs.GetWorkspace(workspacePath);
}
}
Using this method, I don't have to have an activity that just returns the workspace, and then have to pass the workspace into other TFS activities. I just get the workspace from within my own activity while it runs.
I believe the method employed here will use the already downloaded workspace. Keep in mind, that this approach will only work within the scope of "Run on agent" sequence after "Initialize Environment" and before ResetEnvironment within the finally statement of Try Compile, Test, Publish. Else, the workflow will have no knowledge of a sources directory.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/420ba073-bdf5-4ab4-88da-c84561d1a1ba/creating-dynamic-working-folder-in-tfs2013-defaulttemplate?forum=tfsbuild

sharepoint 2013 result source api

i am trying to create new result source with c# in a console application and get error each time,
i succeed updating exist result source but can't create new one
here is my code :
using (SPSite oSPsite = new SPSite("http://XXXXXXX/sites/SearchAdministration"))
{
Microsoft.SharePoint.SPServiceContext context = SPServiceContext.GetContext(oSPsite);
// Get the search service application proxy
SearchServiceApplicationProxy searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;
// Get the search service application info object so we can find the Id of our Search Service App
SearchServiceApplicationInfo ssai = searchProxy.GetSearchServiceApplicationInfo();
// Get the application itself
SearchServiceApplication application = Microsoft.Office.Server.Search.Administration.SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);
FederationManager fedManager = new FederationManager(application);
SearchObjectOwner owner = new SearchObjectOwner(SearchObjectLevel.SPSite, oSPsite.RootWeb);
Source currentResultSource = fedManager.CreateSource(owner);
currentResultSource.Commit();
}
the error is in the commit function -
"The operation you are attempting violates an enforced dependency between objects,
such as depending on an object that does not exist or deleting an object that other objects depend on."
i have noticed that after the creation of the result source, the currentResultSource.id is all zero's
Try to assign to the result source at least one property. Your code works if I assign for example a Name and the Provider Id to the currentResultSource;
using (SPSite oSPsite = new SPSite("http://hostsite.host/sites/SearchAdministration"))
{
SPServiceContext context = SPServiceContext.GetContext(oSPsite);
// Get the search service application proxy
SearchServiceApplicationProxy searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;
// Get the search service application info object so we can find the Id of our Search Service App
SearchServiceApplicationInfo ssai = searchProxy.GetSearchServiceApplicationInfo();
// Get the application itself
SearchServiceApplication application = Microsoft.Office.Server.Search.Administration.SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);
//Microsoft.Office.Server.Search.Administration.SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);
Microsoft.Office.Server.Search.Administration.Query.FederationManager fedManager = new Microsoft.Office.Server.Search.Administration.Query.FederationManager(application);
SearchObjectOwner owner = new SearchObjectOwner(SearchObjectLevel.SPSite, oSPsite.RootWeb);
Source currentResultSource = fedManager.CreateSource(owner);
currentResultSource.Name = "Test Result Source ";
currentResultSource.ProviderId = fedManager.ListProviders()["Local SharePoint Provider"].Id;
currentResultSource.Commit();
}

Categories

Resources