Good afternoon, I was scrolling here, reading questions and trying different code on how to get builds and all the definitions from them, however, whenever I try to execute code and get builds definitions it returns nothing, even though I for sure know there are both successful and unsuccessful builds in there. However I get nothing.
private static void Main(string[] args)
{
NetworkCredential credential = new NetworkCredential("MyUsername", "MyPassword");
VssBasicCredential basicCred = new VssBasicCredential(credential);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://tomheza.visualstudio.com/DefaultCollection"), basicCred);
tpc.Authenticate();
CatalogNode catalogNode = tpc.CatalogNode;
ReadOnlyCollection<CatalogNode> collectionNodes = tpc.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None);
foreach (CatalogNode collectionNode in collectionNodes)
{
Console.WriteLine(collectionNode.Resource.DisplayName);
}
var buildServer = (IBuildServer)tpc.GetService(typeof(IBuildServer));
var vcs = tpc.GetService<VersionControlServer>();
var teamProjects = vcs.GetAllTeamProjects(true);
foreach (TeamProject proj in teamProjects)
{
var defs = buildServer.QueryBuildDefinitions(proj.Name);
Console.WriteLine(string.Format("Team Project: {0}", proj.Name));
foreach (IBuildDefinition def in defs)
{
IBuildDetailSpec spec = buildServer.CreateBuildDetailSpec(proj.Name, def.Name);
spec.MaxBuildsPerDefinition = 1;
spec.QueryOrder = BuildQueryOrder.FinishTimeDescending;
var builds = buildServer.QueryBuilds(spec);
if (builds.Builds.Length > 0)
{
var buildDetail = builds.Builds[0];
Console.WriteLine(string.Format(" {0} - {1} - {2}", def.Name, buildDetail.Status.ToString(), buildDetail.FinishTime));
}
}
Console.WriteLine();
}
}
I am using VS2017 community version
Like the comment said above, the VNext build definition information couldn't be reached using the old version API. Install this TFS ExtendedClient Nuget package for your project, using the method below to get all build definitions.
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Operations;
public static void GetBuild()
{
var u = new Uri("http://servername:8080/tfs/MyCollection/");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(new NetworkCredential("v-tinmo", "123456.w", "fareast")));
VssConnection connection = new VssConnection(u, c);
BuildHttpClient buildServer = connection.GetClient<BuildHttpClient>();
//get all build definitions in your team projects
List<BuildDefinitionReference> builddefs = buildServer.GetDefinitionsAsync(project:"team project name").Result;
foreach (BuildDefinitionReference builddef in builddefs)
{
Console.WriteLine(builddef.Name);
...
}
//get all builds information in your team projects
var builds = buildServer.GetBuildsAsync(project: "team project name").Result;
foreach (var build in builds)
{
Console.WriteLine(build.Definition.Name + "--" + build.BuildNumber + "--" +build.Result);
}
}
You could also use this kind of REST API to get build definitions:
Http method: GET
http://v-tinmo-12r2:8080/tfs/DefaultCollection/teamprojectname/_apis/build/definitions?api-version=2.0
Related
I'm trying to convert Text To audio using Google.Cloud.TextToSpeech.V1. it works fine but I do not know how can I Specify an audio profile to use using c# while I found code in Node.js and python But Not anything in c# this is my code
static void Main(string[] args)
{
List<Word> lst = IntialData();
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", #"C:\Users\Admin\TextToSpeechApiDemo\key.json");
var client = TextToSpeechClient.Create();
// The input to be synthesized, can be provided as text or SSML.
foreach (Word item in lst)
{
var input = new SynthesisInput
{
Text = item.Name,
};
// Build the voice request.
var voiceSelection = new VoiceSelectionParams
{
LanguageCode = "ar",
//SsmlGender = SsmlVoiceGender.Female,
Name = "ar-XA-Wavenet-A"
};
// Specify the type of audio file.
var audioConfig = new AudioConfig
{
AudioEncoding = AudioEncoding.Linear16,
};
// Perform the text-to-speech request.
var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
// Write the response to the output file.
using (var output = File.Create(#"E:\Noursound\sim\ar-XA-Wavenet-A\" + item.Id.ToString() + ".wav"))
{
response.AudioContent.WriteTo(output);
}
}
}
I found this code in python he set effects_profile_id
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3,
effects_profile_id=[effects_profile_id],
How can i do that using c#
The problem was in the version on the NuGet package i used 1.0.0-beta01 , and it's not have the EffectsProfileId property but after update it to version to Google.Cloud.TextToSpeech.V1 version 2.3.0 i found the property.
using Google.Cloud.TextToSpeech.V1;
class Program
{
static void Main(string[] args)
{
var config = new AudioConfig
{
AudioEncoding = AudioEncoding.Mp3,
EffectsProfileId = { "your profile ID" }
};
}
}
i created git issue for that on github Here's a link!
We updated from TFS Version 2017 to Azure Devops. We see now that we have some build steps they are marked with DEPRECATED. The idea is now that we write a C# console application which generate a list with all DEPRECATED build steps. Finally we don't find a property in Microsoft.TeamFoundation.Build.WebApi.BuildDefinitionStep which we can check is this step marked as DEPRECATED or not.
We tried this with the code below written in C#. Variable step has not a property which we can check is the step deprecated or not.
static void Main(string[] args)
{
//For TFS :
var tfsUrl = "http://[serername]:[port]/[tfs]/[name]";
var buildClient = new BuildHttpClient(new Uri(tfsUrl), new VssAadCredential());
var definitions = buildClient.GetFullDefinitionsAsync(project: "Projects");
foreach (var definition in definitions.Result)
{
Console.WriteLine(string.Format("\n {0} - {1}:", definition.Id, definition.Name));
foreach(var phase in ((Microsoft.TeamFoundation.Build.WebApi.DesignerProcess)definition.Process).Phases)
{
foreach(var step in phase.Steps)
{
Console.WriteLine($"{step.DisplayName} has no property to check is this step marked as deprecated or not.");
}
}
}
Console.ReadLine();
}
What you try to achieve is not available in Microsoft.TeamFoundationServer.Client NuGet package.
But you can request your DevOps server with an HttpClient to "_apis/distributedTask/tasks/{id}" endpoint. You would get back a JSON object in the response where the deprecated field is available if your task definition is depracated. Finally you can serialize your JSON into a dynamic object to check the deprecated property.
static void Main(string[] args)
{
//For TFS :
var tfsUrl = "http://[serername]:[port]/[tfs]/[name]";
var buildClient = new BuildHttpClient(new Uri(tfsUrl), new VssAadCredential());
var definitions = buildClient.GetFullDefinitionsAsync(project: "Projects");
foreach (var definition in definitions.Result)
{
Console.WriteLine($"Check {definition.Id} - {definition.Name}...");
foreach (var phase in ((Microsoft.TeamFoundation.Build.WebApi.DesignerProcess)definition.Process).Phases)
{
foreach (var step in phase.Steps)
{
var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
var client = new HttpClient(handler);
client.BaseAddress = new Uri(tfsUrl);
var response = client.GetAsync($"_apis/distributedTask/tasks/{step.TaskDefinition.Id}").Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
dynamic d = JObject.Parse(jsonResponse);
if (d.Result != null && d.value[0].deprecated == true)
{
Console.WriteLine($"'{step.DisplayName}' is deprecated");
}
}
}
}
Console.WriteLine("Press any key to continue..");
Console.ReadLine();
}
I try to create a project automated with DTE this work perfect but i cannot add a nuget package...
Option1 (InstallNuGetPackage code below)
var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
//componentModel is always null
I have installed this nuget package
NuGet.VisualStudio 4.0.0
And add following framework references
Microsoft.VisualStudio.ComponentModelHost 15.0.0.0
Microsoft.VisualStudio.Shell.15.0 15.0.0.0
I have found this example but is not work
http://tylerhughes.info/archive/2015/05/06/installing-a-nuget-package-programmatically/
Option2 (Add a own package.config)
I have also try with creating the packages.config xml but then i have no references to this package and must edit the csproj...
public string GetPackagesConfig()
{
var sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<packages>");
sb.AppendLine("<package id=\"log4net\" version=\"2.0.8\" targetFramework=\"net461\" />");
sb.AppendLine("</packages>");
return sb.ToString();
//Add file to project
}
Visual Studio control
var type = Type.GetTypeFromProgID("VisualStudio.DTE.15.0");
var obj = Activator.CreateInstance(type, true);
this._applicationObject = (DTE2)obj;
InstallNuGetPackage
public bool InstallNuGetPackage(EnvDTE.Project project, string package)
{
bool installedPkg = true;
try
{
var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
IVsPackageInstallerServices installerServices = componentModel.GetService<IVsPackageInstallerServices>();
if (!installerServices.IsPackageInstalled(project, package))
{
var installer = componentModel.GetService<IVsPackageInstaller>();
installer.InstallPackage(null, project, package, (System.Version)null, false);
}
}
catch (Exception ex)
{
installedPkg = false;
}
return installedPkg;
}
Create Project
private void CreateProject(string projectSubFolder, string projectName)
{
Solution2 solution2;
string solutionFileFullName;
string solutionFolderFullName;
string projectFolderFullName;
try
{
solution2 = (Solution2)_applicationObject.Solution;
// Get the full name of the solution file
solutionFileFullName = solution2.FileName;
// Get the full name of the solution folder
solutionFolderFullName = Path.GetDirectoryName(solutionFileFullName);
// Compose the full name of the project folder
projectFolderFullName = Path.Combine(solutionFolderFullName, projectSubFolder);
if (!(projectFolderFullName.EndsWith("\\")))
{
projectFolderFullName += "\\";
}
var programfiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
var template = #"Microsoft Visual Studio\2017\Community\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\ClassLibrary\csClassLibrary.vstemplate";
var projectTemplateFileName = Path.Combine(programfiles, template);
// Add the project
solution2.AddFromTemplate(projectTemplateFileName, projectFolderFullName, projectName, false);
//Save
_applicationObject.Solution.SaveAs(_solutionFullFileName);
}
catch (Exception exception)
{
Log.Error(nameof(CreateProject), exception);
}
}
With this example you can open the package manager console window and send a install-package command.
var packageManagerConsoleGuid = "{0AD07096-BBA9-4900-A651-0598D26F6D24}";
var window = this._visualStudioInstance.Windows.Item(packageManagerConsoleGuid);
window.Activate();
var commandName = "View.PackageManagerConsole";
var nugetCommand = "install-package log4net -ProjectName DemoProject";
this._visualStudioInstance.ExecuteCommand(commandName, nugetCommand);
I develop a project to automate create solution with projects you can found it here
Nager.TemplateBuilder
This example create a Windows Desktop Application with two nuget packages
//Configure Project
var demoProject = new ProjectInfo($"DemoProject", ProjectTemplate.WindowsClassicDesktopWindowsFormsApp);
demoProject.NugetPackages = new List<string> { "System.ServiceModel.NetTcp", "System.Runtime.Serialization.Xml" };
//Configure Solution
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var solutionInfo = new SolutionInfo("Test", folder);
solutionInfo.ProjectInfos.Add(demoProject);
//Start building machine
var buildingMachine = new SolutionBuildingMachine();
buildingMachine.Build(solutionInfo);
buildingMachine.Dispose();
I am writing a small library which uses Google Drive API v3 Client Library for C#.
And for me it involves a lot of pain because I can't use TDD-style for that purpose.
The regular method for doing the job looks something like:
internal async Task<Google.Apis.Drive.v3.Data.FileList> ReadFileList(string parentId, string pageToken, int pageSize)
{
// Define parameters of request.
var listRequest = this.driveService.Files.List();
listRequest.PageSize = pageSize;
listRequest.Q = "mimeType='application/vnd.google-apps.folder' and ('" + parentId + "' in parents)";
listRequest.Fields = "nextPageToken, files(id, name)";
listRequest.PageToken = pageToken;
// List files.
return await listRequest.ExecuteAsync();
}
For Unit Testing it contains a couple of dependencies (probably it might be refactored using factory method pattern):
ListRequest
FileList
For Integrating Tests there are much more problems:
How should I authenticate such service?
Even after authentication it will pollute real Authenticated Drive Account.
How to share the tests between other people?
Test couldn't pass without an internet connection.
Is there something like "In-Memory" provider for Entity Framework Core?
What can be done to make Google Drives Unit and Integration Tests manageable?
So with Enterprise you're in luck.
Assuming a sample project like so:
Installed a nuget package Google.Apis.Drive.v3
Added a class with the following listing:
This is the actual program
public class Class1
{
public async Task<Google.Apis.Drive.v3.Data.FileList> ReadFileList(string parentId, string pageToken, int pageSize)
{
// get the service somehow.
var ds = new DriveService();
var listRequest = ds.Files.List();
listRequest.PageSize = pageSize;
listRequest.Q = "mimeType='application/vnd.google-apps.folder' and ('" + parentId + "' in parents)";
listRequest.Fields = "nextPageToken, files(id, name)";
listRequest.PageToken = pageToken;
// List files.
return await listRequest.ExecuteAsync();
}
}
We can utilize the power of Microsoft Fakes framework to unit test everything here without having any connection to the internet, google drive, accounts etc.
Add a Microsoft Test Project (note: just a dll wouldn't work here)
In the test project, install the same nuget package.
Generate the fakes assemblies for the libraries in which your classes live (in this case, Google.Apis.Drive.v3 and Google.Apis, you are using types from both):
Write the unit test:
like so
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
{
int? usedPageSize = 0;
var usedQ = string.Empty;
var usedFields = string.Empty;
var usedPageToken = string.Empty;
Google.Apis.Drive.v3.Fakes.ShimFilesResource.ShimListRequest.AllInstances.PageSizeSetNullableOfInt32 =
(request, i) => usedPageSize = i;
Google.Apis.Drive.v3.Fakes.ShimFilesResource.ShimListRequest.AllInstances.QSetString = (request, s) => usedQ = s;
Google.Apis.Drive.v3.Fakes.ShimDriveBaseServiceRequest<Google.Apis.Drive.v3.Data.FileList>.AllInstances
.FieldsSetString = (request, s) => usedFields = s;
Google.Apis.Drive.v3.Fakes.ShimFilesResource.ShimListRequest.AllInstances.PageTokenSetString = (request, s) => usedPageToken = s;
Google.Apis.Requests.Fakes.ShimClientServiceRequest<Google.Apis.Drive.v3.Data.FileList>.AllInstances
.ExecuteAsync =
request =>
Task.FromResult(
new FileList
{
ETag = "hello",
Files = new List<File> { new File { Name = "imafile" } },
IncompleteSearch = false,
Kind = "Somekind",
NextPageToken = null
});
Google.Apis.Drive.v3.Fakes.ShimFilesResource.AllInstances.List = resource => (FilesResource.ListRequest)FormatterServices.GetUninitializedObject(typeof(FilesResource.ListRequest));
Google.Apis.Drive.v3.Fakes.ShimDriveService.Constructor = service => { }; // do not init the class
Google.Apis.Drive.v3.Fakes.ShimDriveService.AllInstances.FilesGet = service => (FilesResource)FormatterServices.GetUninitializedObject(typeof(FilesResource));
var target = new Class1();
var result = target.ReadFileList("parent", "token", 42).Result;
Assert.AreEqual(42, usedPageSize);
Assert.AreEqual("mimeType='application/vnd.google-apps.folder' and ('parent' in parents)", usedQ);
Assert.AreEqual("nextPageToken, files(id, name)", usedFields);
Assert.AreEqual("token", usedPageToken);
Assert.AreEqual(1, result.Files.Count);
Assert.AreEqual("imafile", result.Files[0].Name);
Assert.AreEqual("hello", result.ETag);
Assert.IsFalse(result.IncompleteSearch.Value);
Assert.AreEqual("Somekind", result.Kind);
Assert.IsNull(result.NextPageToken);
}
}
}
We are a shop that uses C# , Team Foundation Server and Rally as our main item tracking.
We would like to use Rally Item ChangeSets to follow TFS Changesets. Using Rally's C# RestApi seems a little different than the one made in Java.
Is there a way to do the same thing as described in this article using the Rally C# RestApi?
Rally update Changeset data from Java using Java Toolkit for Rally REST API
You can definitely do the same in .NET. A perk is that it's a lot less verbose than the Java equivalent. Here's an example:
// System Libraries
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Web;
// Rally REST API Libraries
using Rally.RestApi;
using Rally.RestApi.Response;
namespace RestExample_AddChangesetToUserStory
{
class Program
{
static void Main(string[] args)
{
// Set user parameters
String userName = "user#company.com";
String userPassword = "topsecret";
// Set Rally parameters
String rallyURL = "https://rally1.rallydev.com";
String rallyWSAPIVersion = "1.40";
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi(userName,
userPassword,
rallyURL,
rallyWSAPIVersion);
// Changeset Owner Username
String changesetOwner = "scm_integration#company.com";
// SCM Repository Name
String scmRepositoryName = "MySCMRepo";
// FormattedID of Artifact to associate to
String storyFormattedID = "US14";
// Create Request for User
Request userRequest = new Request("user");
userRequest.Fetch = new List<string>()
{
"UserName",
"Subscription",
"DisplayName"
};
// Add a Query to the Request
userRequest.Query = new Query("UserName", Query.Operator.Equals, changesetOwner);
// Query Rally
QueryResult queryUserResults = restApi.Query(userRequest);
// Grab resulting User object and Ref
DynamicJsonObject myUser = new DynamicJsonObject();
myUser = queryUserResults.Results.First();
String myUserRef = myUser["_ref"];
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/12345678910";
String projectRef = "/project/12345678911";
bool projectScopingUp = false;
bool projectScopingDown = true;
// Get handle to SCM Repository
Request scmRequest = new Request("SCMRepository");
scmRequest.Fetch = new List<string>()
{
"ObjectID",
"Name",
"SCMType"
};
// Add query
scmRequest.Query = new Query("Name", Query.Operator.Equals, scmRepositoryName);
// Query Rally
QueryResult querySCMResults = restApi.Query(scmRequest);
DynamicJsonObject myRepository = new DynamicJsonObject();
myRepository = querySCMResults.Results.First();
// Find User Story that we want to add Changeset to
// Tee up Story Request
Request storyRequest = new Request("hierarchicalrequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.ProjectScopeUp = projectScopingUp;
// Fields to Fetch
storyRequest.Fetch = new List<string>()
{
"Name",
"FormattedID",
"Changesets"
};
// Add a query
storyRequest.Query = new Query("FormattedID", Query.Operator.Equals, storyFormattedID);
// Query Rally for the Story
QueryResult queryResult = restApi.Query(storyRequest);
// Pull reference off of Story fetch
var storyObject = queryResult.Results.First();
String storyReference = storyObject["_ref"];
// Pull existing Changesets off of Story
var existingChangesets = storyObject["Changesets"];
Console.WriteLine("Story: " + storyFormattedID);
Console.WriteLine("Number of Existing Changesets: " + existingChangesets.Count);
// DynamicJSONObject for New Changeset
DynamicJsonObject newChangeset = new DynamicJsonObject();
// Commit Time Stamp
String commitTimeStamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
// Populate Changeset Attributes
newChangeset["SCMRepository"] = myRepository;
newChangeset["Author"] = myUserRef;
newChangeset["Revision"] = "2451";
newChangeset["Uri"] = "https://svnrepo.company.com:8001";
newChangeset["CommitTimestamp"] = commitTimeStamp;
// Artifacts list
var changeSetArtifacts = new ArrayList();
changeSetArtifacts.Add(storyObject);
// Update attribute on Changeset
newChangeset["Artifacts"] = changeSetArtifacts;
try
{
// Create the Changeset
Console.WriteLine("Creating Rally Changeset...");
CreateResult myChangesetCreateResult = restApi.Create("ChangeSet", newChangeset);
String myChangesetRef = myChangesetCreateResult.Reference;
Console.WriteLine("Successfully Created Rally Changeset: " + myChangesetRef);
List<string> createWarnings = myChangesetCreateResult.Warnings;
for (int i = 0; i < createWarnings.Count; i++)
{
Console.WriteLine(createWarnings[i]);
}
List<string> createErrors = myChangesetCreateResult.Errors;
for (int i = 0; i < createErrors.Count; i++)
{
Console.WriteLine(createErrors[i]);
}
}
catch (Exception e)
{
Console.WriteLine("Exception occurred creating Rally Changeset: " + e.StackTrace);
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}