Permissions error creating rally milestone when using API Key - permissions

I'm trying to create rally milestones from an external app using an API Key for credential authorization, but I get the warning "Not authorized to create: Milestone" whenever I run the following code:
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["Name"] = "test";
CreateResult createResult = restApi.Create("milestone", toCreate);
I ran the same code with defects and other rally objects without any issues, and I am able to update existing milestones. However, I still can't figure out how to create new milestones.

Assuming that ApiKey belongs to a user that has write access to the intended workspace, this code using v3.0.1 of .NET toolkit creates a Milestone in a default project of that workspace:
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
String apiKey = "_abc123";
restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false);
String workspaceRef = "/workspace/1234";
try
{
DynamicJsonObject m = new DynamicJsonObject();
m["Name"] = "some milestone";
CreateResult result = restApi.Create(workspaceRef, "Milestone",m);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
UPDATE:
The issue can be related to the request's scope. See how this error is replicated and resolved using a browser rest client here.
An equivalent C# code:
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
String apiKey = "_abc123";
restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false);
String projectRef = "/project/2222";
String workspaceRef = "/workspace/1111";
try
{
DynamicJsonObject m = new DynamicJsonObject();
m["Name"] = "some milestone xxxt";
m["TargetProject"] = projectRef;
CreateResult result = restApi.Create(workspaceRef, "Milestone",m);
m = restApi.GetByReference(result.Reference, "FormattedID");
Console.WriteLine(m["FormattedID"]);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

Related

How to use the continuationtoken in TFS 2015 Object Model: GetBuildsAsync?

I am using the following code
BuildHttpClient service = new BuildHttpClient(tfsCollectionUri,
new Microsoft.VisualStudio.Services.Common.VssCredentials(true));
var asyncResult = service.GetBuildsAsync(project: tfsTeamProject);
var queryResult = asyncResult.Result;
This returns only the first 199 builds.
Looks like in need to use the continuationtoken but am not sure how to do this. The docs say that the REST API will return the token. I am using the Object Model, and am looking for how to retrieve the token!
I am using Microsoft.TeamFoundationServer.Client v 14.102.0; Microsoft.TeamFoundationServer.ExtendedClient v 14.102.0, Microsoft.VisualStudio.Service.Client v 14.102.0 and Microsoft.VisualStudio.Services.InteractiveClient v 14.102.0
Question
How do I use the continuation token **when using the TFS Object model?
The continuationToken is in the response header after the first call to the API:
x-ms-continuationtoken: xxxx
It can not be retrieved from .net client library. You have to use the rest api to retrieve the header information. Here is an example for your reference:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace GetBuilds
{
class Program
{
public static void Main()
{
Task t = GetBuilds();
Task.WaitAll(new Task[] { t });
}
private static async Task GetBuilds()
{
try
{
var username = "xxxxx";
var password = "******";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
using (HttpResponseMessage response = client.GetAsync(
"http://tfs2015:8080/tfs/DefaultCollection/teamproject/_apis/build/builds?api-version=2.2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You have to use 'GetBuildsAsync2', which returns an IPagedList. You can retrieve the ContinuationToken from the IPagedList:
// Iterate to get the full set of builds
string continuationToken = null;
List<Build> builds = new List<Build>();
do
{
IPagedList<Build> buildsPage = service.GetBuildsAsync2(tfsTeamProject, continuationToken: continuationToken).Result;
//add the builds
builds.AddRange(buildsPage);
//get the continuationToken for the next loop
continuationToken = buildsPage.ContinuationToken;
}
while (continuationToken != null);

Rally: How to Map test cases with user stories using REST API?

I am writing code to create new test cases using rally restAPI.
Able to create the test cases under Test Plan & Test folder.
Now, want to map those test cases to Rally user stories.
Work product is the field to map it. But how to get the reference of user story using restAPI?
Please let me know if anyone has done in past.
In WS API user story is HierarchicalRequirement object. Query on the story, which you want to be a workproduct, and get its _ref. Then update the test case, e.g.
testCaseUpdate.addProperty("WorkProduct", storyRef);
Here is a Java example using Rally Rest toolkit for Java, but the approach is the same regardless of your choice of language or toolkit:
public class UpdateTestCase {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String workspaceRef = "/workspace/123456";
String applicationName = "RestExample_updateWorkProductOnTestCase";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
try {
String testid = "TC12";
String storyid = "US34";
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setWorkspace(workspaceRef);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "WorkProduct"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testid));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);;
if (testCaseQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test case : " + testid);
return;
}
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
System.out.println(testCaseRef);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
storyRequest.setFetch(new Fetch("FormattedID", "Name"));
storyRequest.setQueryFilter(new QueryFilter("FormattedID", "=", storyid));
QueryResponse storyQueryResponse = restApi.query(storyRequest);;
if (storyQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test story : " + storyid);
return;
}
JsonObject storyJsonObject = storyQueryResponse.getResults().get(0).getAsJsonObject();
String storyRef = storyJsonObject.get("_ref").getAsString();
System.out.println(storyRef);
JsonObject testCaseUpdate = new JsonObject();
testCaseUpdate.addProperty("WorkProduct", storyRef);
UpdateRequest updateTestCaseRequest = new UpdateRequest(testCaseRef,testCaseUpdate);
UpdateResponse updateTestCaseResponse = restApi.update(updateTestCaseRequest);
if (updateTestCaseResponse.wasSuccessful()) {
System.out.println("Successfully updated : " + testid + " WorkProduct after update: " + testCaseUpdate.get("WorkProduct"));
}
} finally {
restApi.close();
}
}
}

KeyNotFoundException in DynamicJson

Using the create defect example from the .NET toolkit page here.
I get the following error when trying to use the DynamicJsonObject -
toCreate["Name"] 'toCreate["Name"]' threw an exception of type 'System.Collections.Generic.KeyNotFoundException' dynamic {System.Collections.Generic.KeyNotFoundException}
The code I am using is just as the example states:
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["Name"] = "My Defect";
CreateResult createResult = restApi.Create(workspaceRef, "defect", toCreate);
Is this a problem on my end or is there a defect in the API?
Below is the full example that works. When we create a defect:
CreateResult createResult = restApi.Create(workspaceRef, "defect", myDefect);
and immediately try to print its FormattedID:
Console.WriteLine(myDefect["FormattedID"]);
the same System.Collections.Generic.KeyNotFoundException is generated. Is it possible you have something similar in your code?
On the other hand, if we create a defect, and then get by reference,we can print the FormattedID, and there is no KeyNotFoundException:
DynamicJsonObject d = restApi.GetByReference(createResult.Reference, "FormattedID");
Console.WriteLine(d["FormattedID"]);
Here is the code. I made some changes to the example. Delete requires workspace reference parameter.
Since in the end the defect is deleted, you may find it in the recycle bin.
namespace CreateDefectFromExample
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi = new RallyRestApi("user#co.com", "TopSecret1984", "https://rally1.rallydev.com", "1.40");
String workspaceRef = "/workspace/111111111"; //use your workspace OID
//Create an item
DynamicJsonObject myDefect = new DynamicJsonObject();
myDefect["Name"] = "worst defect ever";
CreateResult createResult = restApi.Create(workspaceRef, "defect", myDefect);
//Console.WriteLine(myDefect["FormattedID"]); //this line causes System.Collections.Generic.KeyNotFoundException
DynamicJsonObject d = restApi.GetByReference(createResult.Reference, "FormattedID");
Console.WriteLine(d["FormattedID"]);
//Update the item DynamicJsonObject toUpdate = new DynamicJsonObject();
myDefect["Description"] = "This is my defect.";
OperationResult updateResult = restApi.Update(createResult.Reference, myDefect);
//Get the item
DynamicJsonObject item = restApi.GetByReference(createResult.Reference, "Name");
string name = item["Name"];
//Query for items
Request request = new Request("defect");
request.Fetch = new List<string>()
{
"Name",
"Description",
"FormattedID"
};
request.Query = new Query("Name", Query.Operator.Equals, "My Defect");
QueryResult queryResult = restApi.Query(request);
foreach (var result in queryResult.Results)
{
//Process item
string formattedID = result["FormattedID"];
}
//Delete the item
OperationResult deleteResult = restApi.Delete(workspaceRef, createResult.Reference);
}
}
}

how can I query for releases / iterations via rally c# api?

I am trying to query on both Release and Iteration so I can fill out a drop down list with these various values. I'm not quite sure how to do this, however. What are the members of the object that come back via the query if we are able to do this? (Name, FormattedID, CreationDate, etc). Do we just create a new request of type "Release" and "Iteration" ?
Thanks!
Here is a code that queries on releases based on a project reference. If this project is not in a default workspace of the user that runs the code we either need to hardcode the workspace reference or get it from the project.
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "TopSecret1984", "https://rally1.rallydev.com", "1.40");
var projectRef = "/project/22222222"; //use your project OID
DynamicJsonObject itemWorkspace = restApi.GetByReference(projectRef, "Workspace");
var workspaceRef = itemWorkspace["Workspace"]["_ref"];
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
Request request = new Request("Release");
request.ProjectScopeDown = false;
request.ProjectScopeUp = false;
request.Workspace = workspaceRef;
request.Fetch = new List<string>()
{
"Name"
};
// request.Query = new Query("Project.ObjectID", Query.Operator.Equals, "22222222"); //also works
request.Query = new Query("Project", Query.Operator.Equals, projectRef);
QueryResult queryResult = restApi.Query(request);
foreach (var r in queryResult.Results)
{
Console.WriteLine("Name: " + r["Name"]);
}
}
catch
{
Console.WriteLine("problem!");
}
}
}
}

Solr 4 with basic authentication

I am trying to connect to solr using solrj. My solr instance runs in jetty and is protected with basic authentication. I found these links that contain relevant information.
http://grokbase.com/t/lucene/solr-user/1288xjjbwx/http-basic-authentication-with-httpsolrserver
Preemptive Basic authentication with Apache HttpClient 4
However, I still get the following exception:
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:822)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:352)
... 5 more
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:625)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:464)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
... 8 more
I have also attached a snippet of the code I am using.
public static void main(String[] args) throws SolrServerException, IOException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
DefaultHttpClient m_client =(DefaultHttpClient)server.getHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
m_client.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
(((DefaultHttpClient)m_client).getCredentialsProvider()).setCredentials(new AuthScope("localhost",8983), credentials);
SolrInputDocument document = new SolrInputDocument();
document.addField("id",123213);
server.add(document);
server.commit();
}
}
class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}
}
Can anyone point me in the right direction? Thanks !!
i had the same problem when implementing partial documents update. i solved the problem by implementing PreemptiveAuthInterceptor. see below code
PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
SchemeRegistryFactory.createDefault());
cxMgr.setMaxTotal(100);
cxMgr.setDefaultMaxPerRoute(20);
DefaultHttpClient httpclient = new DefaultHttpClient(cxMgr);
httpclient.addRequestInterceptor(
new PreemptiveAuthInterceptor(), 0);
httpclient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(solrDto.getUsername(),
solrDto.getPassword()));
HttpSolrServer solrServerInstance = new HttpSolrServer(solrDto.getUrl(),
httpclient);
solrServerInstance.setRequestWriter(new BinaryRequestWriter());
solrServerInstance.setAllowCompression(true);
You also need:
private class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
Credentials creds = credsProvider.getCredentials(new AuthScope(
targetHost.getHostName(), targetHost.getPort()));
if (creds == null)
throw new HttpException(
"No credentials for preemptive authentication");
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
According to the Solr Security - SolrJ section on Solr Wiki you should be able to do the following:
public static void main(String[] args) throws SolrServerException, IOException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
HttpClientUtil.setBasicAuth(server.getHttpClient(), USERNAME, PASSWORD);
SolrInputDocument document = new SolrInputDocument();
document.addField("id",123213);
server.add(document);
server.commit();
}
You need to add the JAR solr-solrj-4.0.0.jar for HttpClientUtil.
Then use the below code:
HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/"+url);
HttpClientUtil.setBasicAuth((DefaultHttpClient) solrServer.getHttpClient(), "USERNAME", "PASSWORD");
That worked for me on Jdk 1.6 and tomcat 6