I've got some code that looks something like this.
var userStory = restApi.GetByReference (userStoryRef, "Name", "FormattedID");
for (int i = 0; i < (int) userStory["TotalResultCount"]; i++)
{
var name = userStory["Results"][i]["Name"];
...
Of course this fails if the GetByReference has more than 20 results (i.e. TotalResultCount > 20) since the default page size is 20.
So I need to page this but I can't work out how you set the page size, or request a second page from GetByReference.
I tried adding ?pagesize=100 to the reference but it doesn't appear to affect the result set.
e.g.
var userStory = restApi.GetByReference (userStoryRef + "?pagesize=100", "Name", "FormattedID");
I also tried giving up on this altogether and re-phrasing it as a query (which I do know how to page.)
e.g.
var request = new Request("HierarchicalRequirement")
{
Fetch = new List<string>()
{
"Name", "FormattedID"
}, Query = new Query("Parent.FormattedID", Query.Operator.Equals, featureId)
};
var result = myRestApi.Query(request);
But this query doesn't work for me either (featureId is a valid formatted id with associated User Stories). But that query returns no results.
(I appreciate that's a different question altogether - happy to get either working but understanding both would be fantastic!)
Grateful as ever for any help.
See code below. Notice storiesRequest.Limit = 1000 When this number is above default 20, it defaults to max 200, so there is no need to set storiesRequest.PageSize to 200
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
using Rally.RestApi.Json;
namespace GetByRefExample
{
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/123";
String projectRef = "/project/456";
Request request = new Request("PortfolioItem/Feature");
request.Fetch = new List<string>() { "Name", "FormattedID" };
request.Query = new Query("FormattedID", Query.Operator.Equals, "F2356");
QueryResult result = restApi.Query(request);
String featureRef = result.Results.First()._ref;
Console.WriteLine("found" + featureRef);
//create stories
try
{
for (int i = 1; i <= 25; i++)
{
DynamicJsonObject story = new DynamicJsonObject();
story["Name"] = "story " + i;
story["PlanEstimate"] = new Random().Next(2,10);
story["PortfolioItem"] = featureRef;
story["Project"] = projectRef;
CreateResult createResult = restApi.Create(workspaceRef, "HierarchicalRequirement", story);
story = restApi.GetByReference(createResult.Reference, "FormattedID");
Console.WriteLine("creating..." + story["FormattedID"]);
}
//read stories
DynamicJsonObject feature = restApi.GetByReference(featureRef, "UserStories");
Request storiesRequest = new Request(feature["UserStories"]);
storiesRequest.Fetch = new List<string>()
{
"FormattedID",
"PlanEstimate"
};
storiesRequest.Limit = 1000;
QueryResult storiesResult = restApi.Query(storiesRequest);
int storyCount = 0;
foreach (var userStory in storiesResult.Results)
{
Console.WriteLine(userStory["FormattedID"] + " " + userStory["PlanEstimate"]);
storyCount++;
}
Console.WriteLine(storyCount);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
Related
List<SearchResults> Searchresults = new List<SearchResults>();
// Specify the location where the index files are stored
string indexFileLocation = #"D:\Lucene.Net\Data\Persons";
Lucene.Net.Store.Directory dir = FSDirectory.Open(indexFileLocation);
// specify the search fields, lucene search in multiple fields
string[] searchfields = new string[] { "FirstName", "LastName", "DesigName", "CatagoryName" };
IndexSearcher indexSearcher = new IndexSearcher(dir);
// Making a boolean query for searching and get the searched hits
Query som = QueryMaker(searchString, searchfields);
int n = 1000;
TopDocs hits = indexSearcher.Search(som,null,n);
for (int i = 0; i <hits.TotalHits; i++)
{
SearchResults result = new SearchResults();
result.FirstName = hits.ScoreDocs.GetValue(i).ToString();
result.FirstName = hits.Doc.GetField("FirstName").StringValue();
result.LastName = hits.Doc(i).GetField("LastName").StringValue();
result.DesigName = hits.Doc(i).GetField("DesigName").StringValue();
result.Addres = hits.Doc(i).GetField("Addres").StringValue();
result.CatagoryName = hits.Doc(i).GetField("CatagoryName").StringValue();
Searchresults.Add(result);
}
i have table fields first name last name .... how can i process hit to get the values from the search result
i have an error that says TopDocs does not contain defination for doc
Lean on the compiler. There is no property or method called Doc in TopDocs class. In ScoreDocs property of TopDocs class you have list of hits with document number and score. You need to use this document number to get actual document. After that use method Doc which is in IndexSearcher to query for document with this number. And then you can get stored field data from that document.
You can process results like that:
foreach (var scoreDoc in hits.ScoreDocs)
{
var result = new SearchResults();
var doc = indexSearcher.Doc(scoreDoc.Doc);
result.FirstName = doc.GetField("FirstName").StringValue;
result.LastName = doc.GetField("LastName").StringValue;
result.DesigName = doc.GetField("DesigName").StringValue;
result.Addres = doc.GetField("Addres").StringValue;
result.CategoryName = doc.GetField("CategoryName").StringValue;
Searchresults.Add(result);
}
Or in more LINQ way:
var searchResults =
indexSearcher
.Search(som, null, n)
.ScoreDocs
.Select(scoreDoc => indexSearcher.Doc(scoreDoc))
.Select(doc =>
{
var result = new SearchResults();
result.FirstName = doc.GetField("FirstName").StringValue;
result.LastName = doc.GetField("LastName").StringValue;
result.DesigName = doc.GetField("DesigName").StringValue;
result.Addres = doc.GetField("Addres").StringValue;
result.CategoryName = doc.GetField("CategoryName").StringValue;
return result;
})
.ToList();
Separation of hits method will let you clear the matched documents and in future if you want to highlight the matched documents then you can easily embed the lucene.net highlighter in getMatchedHits method.
List<SearchResults> Searchresults = new List<SearchResults>();
// Specify the location where the index files are stored
string indexFileLocation = #"D:\Lucene.Net\Data\Persons";
Lucene.Net.Store.Directory dir = FSDirectory.Open(indexFileLocation);
// specify the search fields, lucene search in multiple fields
string[] searchfields = new string[] { "FirstName", "LastName", "DesigName", "CatagoryName" };
IndexSearcher indexSearcher = new IndexSearcher(dir);
// Making a boolean query for searching and get the searched hits
Query som = QueryMaker(searchString, searchfields);
int n = 1000;
var hits = indexSearcher.Search(som,null,n).ScoreDocs;
Searchresults = getMatchedHits(hits,indexSearcher);
getMatchedHits method code:
public static List<SearchResults> getMatchedHits(ScoreDoc[] hits, IndexSearcher searcher)
{
List<SearchResults> list = new List<SearchResults>();
SearchResults obj;
try
{
for (int i = 0; i < hits.Count(); i++)
{
// get the document from index
Document doc = searcher.Doc(hits[i].Doc);
string strFirstName = doc.Get("FirstName");
string strLastName = doc.Get("LastName");
string strDesigName = doc.Get("DesigName");
string strAddres = doc.Get("Addres");
string strCategoryName = doc.Get("CategoryName");
obj = new SearchResults();
obj.FirstName = strFirstName;
obj.LastName = strLastName;
obj.DesigName= strDesigName;
obj.Addres = strAddres;
obj.CategoryName = strCategoryName;
list.Add(obj);
}
return list;
}
catch (Exception ex)
{
return null; // or throw exception
}
}
Hope it Helps!
I need a way to retrieve a list of projects using C#.
Tried doing something like this:
DynamicJsonObject sub = restApi.GetSubscription("Projects");
//query the project collection
Request wRequest = new Request(sub["Projects"]);
QueryResult queryResult = restApi.Query(wRequest);
return queryResult.Results.Select(result => new Project()
{
Id = result["ObjectID"],
Name = result["Name"]
}).ToList();
unfortunately with no success.
Can anyone help please?
The code below should print workspaces and projects to which the user whose account is used to authenticate the code has access to.
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
wRequest.Limit = 1000;
QueryResult queryResult = restApi.Query(wRequest);
int allProjects = 0;
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine("Workspace: " + workspaceName);
Request projectsRequest = new Request(result["Projects"]);
projectsRequest.Fetch = new List<string>()
{
"Name"
};
projectsRequest.Limit = 10000; //project requests are made per workspace
QueryResult queryProjectResult = restApi.Query(projectsRequest);
int projectsPerWorkspace = 0;
foreach (var p in queryProjectResult.Results)
{
allProjects++;
projectsPerWorkspace++;
Console.WriteLine(projectsPerWorkspace + " Project: " + p["Name"] + " State: " + p["State"]);
}
}
Console.WriteLine("Returned " + allProjects + " projects in the subscription");
I am not able to add or update milestones field for the Features in the Rally. If anyone having the code available using C# to update the same, please share with me. I am searching and doing from last one week with no luck.
When I am trying to add/Update milestones in the Features. I am getting the error as "Could not read: Could not read referenced object null". My code is as follows:-
public DynamicJsonObject UpdateFeaturesbyName(string fea, string bFun)
{
//getting list of Feature.
Request feat = new Request("PortfolioItem/Feature");
feat.Query = new Query("Name", Query.Operator.Equals, fea);
QueryResult TCSResults = restApi.Query(feat);
foreach (var res in TCSResults.Results)
{
var steps = res["Milestones"];
Request tsteps = new Request(steps);
QueryResult tstepsResults = restApi.Query(tsteps);
foreach (var item in tstepsResults.Results)
{
}
if (res.Name == fea)
{
var targetFeature = TCSResults.Results.FirstOrDefault();
DynamicJsonObject toUpdate = new DynamicJsonObject();
//toUpdate["Milestones"] = "";
// CreateResult createResult = restApi.Create(steps._ref, toUpdate);
// String contentRef = steps._ref;
//String contentRef = createResult._ref;
string[] value = null;
string AccCri = string.Empty;
if (!string.IsNullOrWhiteSpace(bFun))
{
value = bFun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string item in value)
{
//if (string.IsNullOrWhiteSpace(AccCri))
// AccCri = item;
//else
// AccCri = AccCri + "<br/>" + item;
if (!string.IsNullOrWhiteSpace(item))
{
//Query for Milestone.
Request ms = new Request("Milestone");
ms.Fetch = new List<string>() { "Name", "ObjectID" };
ms.Query = new Query("Name", Query.Operator.Equals, item);
QueryResult msResults = restApi.Query(ms);
var targetMLResult = msResults.Results.FirstOrDefault();
long MLOID = targetMLResult["ObjectID"];
DynamicJsonObject tarML = restApi.GetByReference("Milestone", MLOID, "Name", "_ref", "DisplayColor");
DynamicJsonObject targetML = new DynamicJsonObject();
targetML["Name"] = tarML["Name"];
//targetML["_ref"] = tarML["_ref"];
targetML["_ref"] = "/milestone/" + Convert.ToString(MLOID);
targetML["DisplayColor"] = tarML["DisplayColor"];
// Grab collection of existing Milestones.
var existingMilestones = targetFeature["Milestones"];
long targetOID = targetFeature["ObjectID"];
// Milestones collection on object is expected to be a System.Collections.ArrayList.
var targetMLArray = existingMilestones;
var tagList2 = targetMLArray["_tagsNameArray"];
tagList2.Add(targetML);//
//targetMLArray.Add(targetML);
targetMLArray["_tagsNameArray"] = tagList2;
toUpdate["Milestones"] = targetMLArray;
OperationResult updateResult = restApi.Update(res._ref, toUpdate);
bool resp = updateResult.Success;
}
}
}
//toUpdate["c_AcceptanceCriteria"] = AccCri;
//OperationResult updateResult = restApi.Update(res._ref, toUpdate);
}
}
var features = TCSResults.Results.Where(p => p.Name == fea).FirstOrDefault();
var featuresref = features._ref;
return features;
}
Now that v3.1.1 of the toolkit has been released you can use the AddToCollection method to do this.
Otherwise, you can still always just update the full collection. The value should be an arraylist of objects with _ref properties.
Check out this example (which adds tasks to defects, but should be very similar to what you're doing): https://github.com/RallyCommunity/rally-dot-net-rest-apps/blob/master/UpdateTaskCollectionOnDefect/addTaskOnDefect.cs
I try to import data from my POS System to Quickbooks to create General Journal entries. When i add some static(hard coded) data all saved successfully. But when I try to add data from my app QB add data to dataService but when i sync QB data didn't come. Please could you help with my problem. Here is my code.
//main code to add General Journal Entry to QB
var header = GenerateReportHeader(model);
var creditInfo = GenerateJournalEntryLines(model.CreditInformation, PostingTypeEnum.Credit);
var debitInfo = GenerateJournalEntryLines(model.DebitInformation, PostingTypeEnum.Debit);
var allLines = creditInfo.Concat(debitInfo).ToArray();
var result = new JournalEntry();
result.Header = header;
result.Line = allLines;
dataService.Add(result);
//Add Header
private JournalEntryHeader GenerateReportHeader(GeneralJournalModel model)
{
var result = new JournalEntryHeader
{
TxnDate = new DateTime(2013,7,1),
Status = "Payable",
Adjustment = false,
TxnDateSpecified = true
};
if (!String.IsNullOrEmpty(model.EntryNo))
{
result.DocNumber = model.EntryNo;
}
return result;
}
//Add Line
private JournalEntryLine[] GenerateJournalEntryLines(List<GeneralJournalEntryModel> model, PostingTypeEnum postType)
{
var result = new JournalEntryLine[model.Count];
for (int i = 0; i < model.Count; i++)
{
var journalEntryLine = model[i];
var account = GetAccountByNumber(journalEntryLine.AccountNumber);
var toAdd = new JournalEntryLine
{
AccountId = account.Id,
AccountType = account.Type,
AccountName = account.Name,
Amount = Convert.ToDecimal(journalEntryLine.Amount),
AmountSpecified = true,
PostingType = postType,
AccountTypeSpecified = true,
Id = new IdType(),
PostingTypeSpecified = true
};
if (journalEntryLine.EntityId != null)
{
toAdd.EntityId = GetEntityId(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityType = GetEntityType(journalEntryLine.EntityType);
toAdd.EntityName = GetEntityName(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityTypeSpecified = true;
}
result[i] = toAdd;
}
return result;
}
Did you check the SyncStatus, and find out why not?
This should be where you start:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/syncstatus
It will give you more detail about specifically why the data failed to sync over.
I'm trying to send a mail chimp campaign using asp.net, actually i created successfully the campaign and i can see it through my profile but also i want to send it through my code here is my code so if any one can help!!
private static void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 0;
string campaignID = string.Empty;
// compaign Create Options
var campaignCreateOpt = new campaignCreateOptions
{
list_id = listID,
subject = "subject",
from_email = "cbx#abc.com",
from_name = "abc",
template_id = TemplateID
};
// Content
var content = new Dictionary<string, string>
{
{"html", "Lots of cool stuff here."}
};
// Conditions
var csCondition = new List<campaignSegmentCondition>();
var csC = new campaignSegmentCondition {field = "interests-" + 123, op = "all", value = ""};
csCondition.Add(csC);
// Options
var csOptions = new campaignSegmentOptions {match = "all"};
// Type Options
var typeOptions = new Dictionary<string, string>
{
{"offset-units", "days"},
{"offset-time", "0"},
{"offset-dir", "after"}
};
// Create Campaigns
var campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
campaignSendNow c=new campaignSendNow();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}