static void Main(string[] args) { RallyRestApi restApi; restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0"); String projectRef = "/project/123456"; //use valid OID of your project Request userRequest = new Request("User"); userRequest.Query = new Query("UserName", Query.Operator.Equals, "*****@*****.**"); QueryResult userResults = restApi.Query(userRequest); String userRef = userResults.Results.First()._ref; Console.WriteLine(userRef); DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "a new story"; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createResult = restApi.Create("HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createResult.Reference, "FormattedID", "Owner", "Project"); Console.WriteLine(myStory["FormattedID"] + " " + myStory["Owner"]._refObjectName + " " + myStory["Project"]._refObjectName); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return(true); } var dictionary = result as IDictionary <string, object>; if (dictionary != null) { result = new DynamicJsonObject(dictionary); return(true); } var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { if (arrayList[0] is IDictionary <string, object> ) { result = new List <object>(arrayList.Cast <IDictionary <string, object> >().Select(x => new DynamicJsonObject(x))); } else { result = new List <object>(arrayList.Cast <object>()); } } return(true); }
/// <summary> /// Gets a cacheable response. /// </summary> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> internal DynamicJsonObject GetCacheable(Uri target, out bool isCachedResult, IDictionary <string, string> headers = null) { DynamicJsonObject response = null; DateTime startTime = DateTime.Now; String requestHeaders = ""; String responseHeaders = ""; try { using (var webClient = GetWebClient(headers, true)) { requestHeaders = webClient.Headers.ToString(); CookieAwareCacheableWebClient cacheableWeb = webClient as CookieAwareCacheableWebClient; if (cacheableWeb != null) { response = cacheableWeb.DownloadCacheableResult(target, out isCachedResult); } else { throw new InvalidOperationException("GetWebClient failed to create a CookieAwareCacheableWebClient"); } responseHeaders = webClient.ResponseHeaders.ToString(); return(response); } } finally { TraceHelper.TraceHttpMessage("GET", startTime, target, requestHeaders, response, responseHeaders); } }
public void RemoveFromCollection2x() { RallyRestApi restApi = GetRallyRestApi2x(); DynamicJsonObject newStory = new DynamicJsonObject(); newStory["Name"] = "Test Story"; var itemRef = restApi.Create("hierarchicalrequirement", newStory).Reference; DynamicJsonObject newDefect = new DynamicJsonObject(); newDefect["Name"] = "New Defect Added via collection"; newDefect["Requirement"] = itemRef; CreateResult newTaskResult = restApi.Create("defect", newDefect); DynamicJsonObject story = restApi.GetByReference(itemRef, "Defects"); Assert.AreEqual(1, story["Defects"]["Count"]); DynamicJsonObject taskToRemove = new DynamicJsonObject(); taskToRemove["_ref"] = newTaskResult.Reference; OperationResult result = restApi.RemoveFromCollection(itemRef, "Defects", new List <DynamicJsonObject>() { taskToRemove }, new NameValueCollection()); Assert.IsTrue(result.Success); Assert.AreEqual(0, result.Results.Count); story = restApi.GetByReference(itemRef, "Defects"); Assert.AreEqual(0, story["Defects"]["Count"]); // Now delete the defect and story TestHelperDeleteItem(restApi, newTaskResult.Reference); TestHelperDeleteItem(restApi, itemRef); }
/// <summary> /// 取值 /// </summary> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { //找不到键的值时为null(以免抛出异常,在用到可能会不存在的属性时要注意检查值是否为null) if (!_dictionary.TryGetValue(binder.Name, out result)) { result = null; return(true); } //如果在上面的字典中找到值那么尝试转为字典类型 var dictionary = result as IDictionary <string, object>; if (dictionary != null) { result = new DynamicJsonObject(dictionary); //将结果进行递归 return(true); } //不能转为字典时,将结果转为数组(如果数组中的第一个元素是字典型那就进行递归,不是时转为对像数组) var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { if (arrayList[0] is IDictionary <string, object> ) { result = new List <object>( arrayList.Cast <IDictionary <string, object> >().Select(x => new DynamicJsonObject(x))); } else { result = new List <object>(arrayList.Cast <object>()); } } //不能转为数组时将结果result 直接返回 return(true); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { result = this.Dictionary[binder.Name]; if (result is IDictionary <string, object> ) { result = new DynamicJsonObject(result as IDictionary <string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary <string, object> ) { result = new List <DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary <string, object>))); } else if (result is ArrayList) { result = new List <object>((result as ArrayList).ToArray()); } else if (result is ArrayList) { var list = new List <object>(); foreach (var o in (result as ArrayList).ToArray()) { if (o is IDictionary <string, object> ) { list.Add(new DynamicJsonObject(o as IDictionary <string, object>)); } else { list.Add(o); } } result = list; } return(this.Dictionary.ContainsKey(binder.Name)); }
protected static unsafe void AssertComplexEmployee(string str, BlittableJsonReaderObject doc, JsonOperationContext blittableContext) { dynamic dynamicRavenJObject = new DynamicJsonObject(RavenJObject.Parse(str)); dynamic dynamicBlittableJObject = new DynamicBlittableJson(doc); Assert.Equal(dynamicRavenJObject.Age, dynamicBlittableJObject.Age); Assert.Equal(dynamicRavenJObject.Name, dynamicBlittableJObject.Name); Assert.Equal(dynamicRavenJObject.Dogs.Count, dynamicBlittableJObject.Dogs.Count); for (var i = 0; i < dynamicBlittableJObject.Dogs.Length; i++) { Assert.Equal(dynamicRavenJObject.Dogs[i], dynamicBlittableJObject.Dogs[i]); } Assert.Equal(dynamicRavenJObject.Office.Name, dynamicRavenJObject.Office.Name); Assert.Equal(dynamicRavenJObject.Office.Street, dynamicRavenJObject.Office.Street); Assert.Equal(dynamicRavenJObject.Office.City, dynamicRavenJObject.Office.City); Assert.Equal(dynamicRavenJObject.Office.Manager.Name, dynamicRavenJObject.Office.Manager.Name); Assert.Equal(dynamicRavenJObject.Office.Manager.Id, dynamicRavenJObject.Office.Manager.Id); Assert.Equal(dynamicRavenJObject.MegaDevices.Count, dynamicBlittableJObject.MegaDevices.Count); for (var i = 0; i < dynamicBlittableJObject.MegaDevices.Length; i++) { Assert.Equal(dynamicRavenJObject.MegaDevices[i].Name, dynamicBlittableJObject.MegaDevices[i].Name); Assert.Equal(dynamicRavenJObject.MegaDevices[i].Usages, dynamicBlittableJObject.MegaDevices[i].Usages); } var ms = new MemoryStream(); blittableContext.Write(ms, doc); Assert.Equal(str, Encoding.UTF8.GetString(ms.ToArray())); }
private static IDictionary <string, object> GetDictonary(string json) { IDictionary <string, object> result = null; JavaScriptSerializer serializer = new JavaScriptSerializer(); if (serializer != null) { // Register the converter serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); object tempObject = serializer.Deserialize(json, typeof(object)); if (tempObject != null) { DynamicJsonObject holder = (DynamicJsonObject)tempObject; if (holder != null && holder.Dictionary != null) { result = holder.Dictionary; } } } return(result); }
public static Story UpdateStoryPredecessors(string formattedID, IEnumerable <string> list) { Story story = QueryStory(formattedID); if (story == null) { return(null); } System.Collections.ArrayList stories = new System.Collections.ArrayList(); foreach (string entry in list) { var predecessor = QueryStory(entry); if (predecessor != null) { stories.Add(predecessor.Object); } } DynamicJsonObject update = new DynamicJsonObject(); update["Predecessors"] = stories; OperationResult updateResult = _rally.Update("HierarchicalRequirement", story.ObjectID, update); if (updateResult.Errors.Count > 0) { return(null); } story = QueryStory(formattedID); return(story); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { var name = binder.Name; if (string.Compare(binder.Name, "MinusOne", StringComparison.OrdinalIgnoreCase) == 0 && Dictionary.ContainsKey("-1")) { name = "-1"; } else if (String.Compare(binder.Name, "MinusTwo", StringComparison.OrdinalIgnoreCase) == 0 && Dictionary.ContainsKey("-2")) { name = "-2"; } result = Dictionary[name]; if (result is IDictionary <string, object> ) { result = new DynamicJsonObject(result as IDictionary <string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary <string, object> ) { result = new List <DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary <string, object>))); } else if (result is ArrayList) { result = new List <object>((result as ArrayList).ToArray()); } return(Dictionary.ContainsKey(name)); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0"); String workspaceRef = "/workspace/1111"; String projectRef = "/project/2222"; Request dRequest = new Request("Defect"); dRequest.Workspace = workspaceRef; dRequest.Project = projectRef; dRequest.Fetch = new List<string>() { "Name", "FormattedID", }; var fid = "DE1"; dRequest.Query = new Query("FormattedID", Query.Operator.Equals, fid); QueryResult queryResults = restApi.Query(dRequest); DynamicJsonObject defect = queryResults.Results.First(); String defectRef = defect["_ref"]; Console.WriteLine(defectRef); Console.WriteLine("FormattedID: " + defect["FormattedID"] + " Name: " + defect["Name"]);
/// <summary> /// Retreives all the scrum teams within the Rally Enviornment /// </summary> public void GetScrumTeams() { this.EnsureRallyIsAuthenticated(); DynamicJsonObject dObj = _rallyRestApi.GetSubscription(RALLYQUERY.Workspaces); try { Request workspaceRequest = new Request(dObj[RALLYQUERY.Workspaces]); QueryResult workSpaceQuery = _rallyRestApi.Query(workspaceRequest); foreach (var workspace in workSpaceQuery.Results) { Request projectRequest = new Request(workspace[RALLYQUERY.Projects]); projectRequest.Fetch = new List <string> { RALLY.Name }; //Query for the projects QueryResult projectQuery = _rallyRestApi.Query(projectRequest); foreach (var project in projectQuery.Results) { Console.WriteLine(project[RALLY.Name]); } } } catch (WebException) { Console.WriteLine(RALLYQUERY.WebExceptionMessage); } }
/// <summary> /// Returns all the existing workspaces in Rally /// </summary> public void GetWorkspaces() { //Authenticate this.EnsureRallyIsAuthenticated(); //instantiate a DynamicJsonObject obj DynamicJsonObject djo = _rallyRestApi.GetSubscription(RALLYQUERY.Workspaces); Request workspaceRequest = new Request(djo[RALLYQUERY.Workspaces]); try { //query for the workspaces QueryResult returnWorkspaces = _rallyRestApi.Query(workspaceRequest); //iterate through the list and return the list of workspaces foreach (var value in returnWorkspaces.Results) { var workspaceReference = value[RALLYQUERY.Reference]; var workspaceName = value[RALLY.Name]; Console.WriteLine(RALLYQUERY.WorkspaceMessage + workspaceName); } } catch (WebException) { Console.WriteLine(RALLYQUERY.WebExceptionMessage); } }
/// <summary> /// Creates the userstory with a feature or iteration /// Both feature and iteration are read only fields /// </summary> /// <param name="workspace"></param> /// <param name="project"></param> /// <param name="userstory"></param> /// <param name="userstoryDescription"></param> /// <param name="userstoryOwner"></param> public void CreateUserStory(string workspace, string project, string userstory, string userstoryDescription, string userstoryOwner) { //authenticate this.EnsureRallyIsAuthenticated(); //DynamicJsonObject DynamicJsonObject toCreate = new DynamicJsonObject(); toCreate[RALLY.WorkSpace] = workspace; toCreate[RALLY.Project] = project; toCreate[RALLY.Name] = userstory; toCreate[RALLY.Description] = userstoryDescription; toCreate[RALLY.Owner] = userstoryOwner; toCreate[RALLY.PlanEstimate] = "1"; toCreate[RALLY.PortfolioItem] = RALLYQUERY.FeatureShareProject; //toCreate[RALLY.Iteration] = usIteration; try { CreateResult createUserStory = _rallyRestApi.Create(RALLY.HierarchicalRequirement, toCreate); Console.WriteLine("Created Userstory: " + createUserStory.Reference); } catch (WebException e) { Console.WriteLine(e.Message); } }
public override bool TryGetMember( GetMemberBinder binder, out object result ) { result = Dictionary[binder.Name]; if (result is IDictionary <string, object> ) { result = new DynamicJsonObject( result as IDictionary <string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary <string, object> ) { result = new List <DynamicJsonObject>( (result as ArrayList).ToArray().Select( x => new DynamicJsonObject( x as IDictionary <string, object>))); } else if (result is ArrayList) { result = new List <object>((result as ArrayList).ToArray()); } return(Dictionary.ContainsKey(binder.Name)); }
public void LinqQueryWithStaticCallOnEnumerableIsCanBeCompiledAndRun() { var indexDefinition = new IndexDefinition <Page> { Map = pages => from p in pages from coAuthor in p.CoAuthors.DefaultIfEmpty() select new { p.Id, CoAuthorUserID = coAuthor != null ? coAuthor.UserId : -1 } }.ToIndexDefinition(new DocumentConvention()); var mapInstance = new DynamicViewCompiler("testView", indexDefinition, new AbstractDynamicCompilationExtension[] { }). GenerateInstance(); var conventions = new DocumentConvention(); var o = JObject.FromObject(page, conventions.CreateSerializer()); o["@metadata"] = new JObject( new JProperty("Raven-Entity-Name", "Pages") ); dynamic dynamicObject = new DynamicJsonObject(o); var result = mapInstance.MapDefinition(new[] { dynamicObject }).ToList <object>(); Assert.Equal("{ Id = 0, CoAuthorUserID = 1, __document_id = }", result[0].ToString()); Assert.Equal("{ Id = 0, CoAuthorUserID = 2, __document_id = }", result[1].ToString()); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = RavenJToken.ReadFrom(reader); var val = token as RavenJValue; if(val != null) return val.Value; var array = token as RavenJArray; if (array != null) { var dynamicJsonObject = new DynamicJsonObject(new RavenJObject()); return new DynamicList(array.Select(dynamicJsonObject.TransformToValue).ToArray()); } var typeName = token.Value<string>("$type"); if(typeName != null) { var type = Type.GetType(typeName, false); if(type != null) { return serializer.Deserialize(new RavenJTokenReader(token), type); } } return new DynamicJsonObject((RavenJObject)((RavenJObject)token).CloneToken()); }
public override List <string> GetALMDomains() { List <string> domains = new List <string>(); try { if (!string.IsNullOrEmpty(ALMCore.DefaultAlmConfig.ALMUserName) && !string.IsNullOrEmpty(ALMCore.DefaultAlmConfig.ALMPassword) && !string.IsNullOrEmpty(ALMCore.DefaultAlmConfig.ALMServerURL)) { if (restApi.AuthenticationState != RallyRestApi.AuthenticationResult.Authenticated) { restApi.Authenticate(ALMCore.DefaultAlmConfig.ALMUserName, ALMCore.DefaultAlmConfig.ALMPassword, ALMCore.DefaultAlmConfig.ALMServerURL, proxy: null, allowSSO: false); } DynamicJsonObject sub = restApi.GetSubscription("Workspaces"); Request wRequest = new Request(sub["Workspaces"]); wRequest.Limit = 1000; QueryResult queryResult = restApi.Query(wRequest); foreach (var result in queryResult.Results) { domains.Add(Convert.ToString(result["Name"])); } } } catch (Exception ex) { throw ex; } return(domains); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!Dictionary.TryGetValue(binder.Name, out result)) { return(false); } if (result is IDictionary <string, object> ) { result = new DynamicJsonObject(result as IDictionary <string, object>); return(true); } var arrayList = result as ArrayList; if (arrayList != null) { if (arrayList is IDictionary <string, object> ) { result = new List <DynamicJsonObject>(arrayList.ToArray().Select(x => new DynamicJsonObject(x as IDictionary <string, object>))); } else { result = new List <object>(arrayList.ToArray()); } } return(true); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } var dict = result as IDictionary<string, object>; if (dict != null) { result = new DynamicJsonObject(dict); return true; } var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { if (arrayList[0] is IDictionary<string, object>) result = new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))); else result = new List<object>(arrayList.Cast<object>()); } return true; }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0"); String apiKey = "_abc777"; restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false); String workspaceRef = "/workspace/123"; String projectRef = "/project/134"; DynamicJsonObject badDefect = new DynamicJsonObject(); badDefect["Name"] = "bad defect 2" + DateTime.Now; badDefect["Project"] = projectRef; CreateResult createRequest = restApi.Create(workspaceRef, "Defect", badDefect); badDefect = restApi.GetByReference(createRequest.Reference, "FormattedID", "Project", "State"); Console.WriteLine(badDefect["FormattedID"] + " " + badDefect["Project"]._refObjectName + " " + badDefect["State"]); badDefect["State"] = "Open"; OperationResult updateRequest = restApi.Update(badDefect["_ref"], badDefect); Console.WriteLine("Success? " + updateRequest.Success); Console.WriteLine("updated State: " + badDefect["State"]); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!this.storage.TryGetValue(binder.Name, out result)) { result = null; return(true); } var dictionary = result as IDictionary <string, object>; if (dictionary != null) { result = new DynamicJsonObject(dictionary); return(true); } var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { if (arrayList[0] is IDictionary <string, object> ) { result = new List <object>(arrayList.Cast <IDictionary <string, object> >().Select(x => new DynamicJsonObject(x))); } else { result = new List <object>(arrayList.Cast <object>()); } } return(true); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { object retVal = null; bool containsKey = false; if (_dictionary.ContainsKey(binder.Name)) { retVal = _dictionary[binder.Name]; if (retVal is IDictionary <string, object> ) { retVal = new DynamicJsonObject(retVal as IDictionary <string, object>); } else if (retVal is ArrayList) { var resultList = (retVal as ArrayList); if (resultList.Count > 0 && resultList[0] is IDictionary <string, object> ) { retVal = new List <DynamicJsonObject>((retVal as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary <string, object>))); } else { retVal = new List <object>((retVal as ArrayList).ToArray()); } } containsKey = true; } result = retVal; return(containsKey); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = RavenJToken.ReadFrom(reader); var val = token as RavenJValue; if (val != null) { return(val.Value); } var array = token as RavenJArray; if (array != null) { var dynamicJsonObject = new DynamicJsonObject(new RavenJObject()); return(new DynamicList(array.Select(dynamicJsonObject.TransformToValue).ToArray())); } var typeName = token.Value <string>("$type"); if (typeName != null) { var type = Type.GetType(typeName, false); if (type != null) { return(serializer.Deserialize(new RavenJTokenReader(token), type)); } } return(new DynamicJsonObject((RavenJObject)((RavenJObject)token).CloneToken())); }
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); } }
/// <summary> /// Gives all work spaces present in the env /// </summary> /// <returns></returns> public QueryResult GetAllWorkSpaces() { DynamicJsonObject sub = restApi.GetSubscription("Workspaces"); Request wRequest = new Request(sub["Workspaces"]); wRequest.Limit = 1000; return(restApi.Query(wRequest)); }
public DynamicJsonObject ToJson() { dynamic json = new DynamicJsonObject(); json.realTime = RealTime.ToString(); json.gameTime = GameTime.ToString(); return(json); }
public void TestEndpointCollection() { DynamicJsonObject collection = new DynamicJsonObject(); collection["_ref"] = "https://rally1.rallydev.com/slm/webservice/v2.0/defect/12345/tasks"; var request = new Request(collection); Assert.AreEqual("/defect/12345/tasks", request.Endpoint); }
public void SerializeTestArray() { var value = new DynamicJsonObject(); (value as dynamic).array = new object[] { "arrayValue1", 8 }; var target = new DynamicJsonSerializer(); const string expected = "{\"array\":[\"arrayValue1\",8]}"; var actual = target.Serialize(value); Assert.AreEqual(expected, actual); }
static DynamicJsonObject ConvertJson(string json) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); DynamicJsonObject dy = jss.Deserialize(json, typeof(object)) as dynamic; return(dy); }
public void SerializeTestSimpleObject() { var value = new DynamicJsonObject(); var target = new DynamicJsonSerializer(); const string expected = "{}"; var actual = target.Serialize(value); Assert.AreEqual(expected, actual); }
static void Main(string[] args) { RallyRestApi restApi; restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0"); String projectRef = "/project/222"; Request testSetRequest = new Request("TestSet"); testSetRequest.Project = projectRef; testSetRequest.Fetch = new List <string>() { "Name", "FormattedID", "TestCases" }; testSetRequest.Query = new Query("FormattedID", Query.Operator.Equals, "TS22"); QueryResult queryTestSetResults = restApi.Query(testSetRequest); String tsRef = queryTestSetResults.Results.First()._ref; String tsName = queryTestSetResults.Results.First().Name; Console.WriteLine(tsName + " " + tsRef); DynamicJsonObject testSet = restApi.GetByReference(tsRef, "FormattedID", "TestCases"); String testCasesCollectionRef = testSet["TestCases"]._ref; Console.WriteLine(testCasesCollectionRef); ArrayList testCasesList = new ArrayList(); foreach (var ts in queryTestSetResults.Results) { Request tcRequest = new Request(ts["TestCases"]); QueryResult queryTestCasesResult = restApi.Query(tcRequest); foreach (var tc in queryTestCasesResult.Results) { var tName = tc["Name"]; var tFormattedID = tc["FormattedID"]; Console.WriteLine("Test Case: " + tName + " " + tFormattedID); DynamicJsonObject aTC = new DynamicJsonObject(); aTC["_ref"] = tc["_ref"]; testCasesList.Add(aTC); //add each test case in the collection to array 'testCasesList' } } Console.WriteLine("count of elements in the array before adding a new tc:" + testCasesList.Count); DynamicJsonObject anotherTC = new DynamicJsonObject(); anotherTC["_ref"] = "/testcase/123456789"; //any existing test to add to the collection testCasesList.Add(anotherTC); Console.WriteLine("count of elements in the array:" + testCasesList.Count); testSet["TestCases"] = testCasesList; OperationResult updateResult = restApi.Update(tsRef, testSet); }
public static DynamicJsonObject ToJson(this IIndexedTime indexedTime) { dynamic coolObject = new DynamicJsonObject(); coolObject.id = indexedTime.Index; coolObject.realTime = indexedTime.Time.RealTime; coolObject.gameTime = indexedTime.Time.GameTime; return(coolObject); }
static void Main(string[] args) { string data = "{ 'test': 42, 'test2': 'test2\"', 'structure' : { 'field1': 'field1', 'field2': 44 } }"; dynamic x = new DynamicJsonObject(JsonMaker.ParseJSON(data)); Console.WriteLine(x.test2); Console.WriteLine(x.structure.field1); Console.ReadLine(); }
public void SerializeTestArrayWithObjects() { var value = new DynamicJsonObject(); var inner = new DynamicJsonObject(); (inner as dynamic).objVal = 90; (value as dynamic).array = new object[] { "arrayValue1", inner }; var target = new DynamicJsonSerializer(); const string expected = "{\"array\":[\"arrayValue1\",{\"objVal\":90}]}"; var actual = target.Serialize(value); Assert.AreEqual(expected, actual); }
private void AssertCanCreate(RallyRestApi restApi) { var dynamicJson = new DynamicJsonObject(); dynamicJson["Name"] = "C# Json Rest Toolkit Test Defect"; CreateResult response = restApi.Create("defect", dynamicJson); Assert.AreEqual(0, response.Errors.Count); Assert.IsTrue(response.Reference.ToLower().Contains("defect")); dynamic testDefect = restApi.GetByReference(response.Reference); Assert.AreEqual(dynamicJson["Name"], testDefect.Name); defectOid = Ref.GetOidFromRef(response.Reference); }
public void ShouldGetValueFromCurrentElement() { // carlos.mendonca: Json.Net doesn't seen to be compatible with '<node>.Value' notation; maybe I // should change DynamicXmlObject to always demmand that the root element be // specified in order to access the hierarchy (e.g.: <root>.Order.Book instead of // <root>.Book). const string json = "{ 'a': 'value' }"; dynamic dynamicObject = new DynamicJsonObject(JObject.Parse(json).Root); Assert.AreEqual("value", dynamicObject.ToString()); }
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); } }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/11111"; //use valid workspace OID in your Rally String projectRef = "/project/12345"; //use valid project OID in your Rally DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story"; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createResult = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createResult.Reference, "FormattedID", "Owner", "Project"); Console.WriteLine(myStory["FormattedID"] + " " + myStory["Owner"]._refObjectName + " " + myStory["Project"]._refObjectName); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0"); String apiKey = "_abc777"; restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false); String workspaceRef = "/workspace/123"; String projectRef = "/project/134"; DynamicJsonObject badDefect = new DynamicJsonObject(); badDefect["Name"] = "bad defect " + DateTime.Now; badDefect["Project"] = projectRef; CreateResult createRequest = restApi.Create(workspaceRef, "Defect", badDefect); badDefect = restApi.GetByReference(createRequest.Reference, "FormattedID", "Project"); Console.WriteLine(badDefect["FormattedID"] + " " + badDefect["Project"]._refObjectName); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://sandbox.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/12352608129"; //use valid workspace OID in your Rally String projectRef = "/project/14018981229"; //use valid project OID in your Rally System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener("log.log", "myListener"); try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story " + DateTime.Now; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Owner", "Project"); myListener.WriteLine(DateTime.Now + "___________\r\n" + myStory["FormattedID"] + " Owner: " + myStory["Owner"]._refObjectName + " Project: " + myStory["Project"]._refObjectName); //update story myStory["Description"] = "updated " + DateTime.Now; //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["Owner"] = userRef; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); myListener.WriteLine(myTask["FormattedID"] + " State: " + myTask["StateX"]); } } catch(Exception e) { myListener.WriteLine(e); } myListener.Flush(); }
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/1011574887"; //non-default workspace of the user String projectRef = "/project/1791269111"; //a non-default project of the user (inside the workspace above) try { //create testset DynamicJsonObject myTestSet = new DynamicJsonObject(); myTestSet["Name"] = "important set " + DateTime.Now; myTestSet["Project"] = projectRef; CreateResult createTestSet = restApi.Create(workspaceRef, "TestSet", myTestSet); myTestSet = restApi.GetByReference(createTestSet.Reference, "FormattedID", "Project"); Console.WriteLine(myTestSet["FormattedID"] + " " + myTestSet["Project"]._refObjectName); //find current iteration Request iterationRequest = new Request("Iteration"); iterationRequest.Project = projectRef; iterationRequest.ProjectScopeDown = false; iterationRequest.ProjectScopeUp = false; iterationRequest.Fetch = new List<string>() { "ObjectID", "Name" }; iterationRequest.Query = new Query("(StartDate <= Today)").And(new Query("(EndDate >= Today)")); QueryResult queryResults = restApi.Query(iterationRequest); if (queryResults.TotalResultCount > 0) { Console.WriteLine(queryResults.Results.First()["Name"] + " " + queryResults.Results.First()["ObjectID"]); myTestSet["Iteration"] = queryResults.Results.First()._ref; OperationResult updateResult = restApi.Update(myTestSet["_ref"], myTestSet); } else { Console.WriteLine("No current iterations"); } } catch (Exception e) { Console.WriteLine(e); } }
public override bool TryGetMember(GetMemberBinder binder, out object result) { result = this.Dictionary[binder.Name]; if (result is IDictionary<string, object>) { result = new DynamicJsonObject(result as IDictionary<string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.Name); }
public void DeserializeTest() { dynamic expected = new DynamicJsonObject(); expected.int1 = -19; expected.decimal1 = 1.21M; expected.string1 = "hi"; dynamic obj1 = new DynamicJsonObject(); obj1.int1 = 19; obj1.string1 = "hi"; obj1.decimal1 = -1.21M; obj1.array1 = new int[0]; obj1.array2 = new[] { "arrayValue1", "arrayValue1" }; expected.obj1 = obj1; var target = new DynamicJsonSerializer(); const string json = "{\"int1\":-19,\"decimal1\":1.21,\"string1\":\"hi\",\"obj1\":{\"int1\":19,\"string1\":\"hi\",\"decimal1\":-1.21,\"array1\":[],\"array2\":[\"arrayValue1\", \"arrayValue1\"]}}"; var actual = target.Deserialize(json); Assert.AreEqual<DynamicJsonObject>(expected, actual); }
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/32904827032"; try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "another story " + DateTime.Now; myStory["Project"] = projectRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Project"); //update story myStory["Description"] = "updated " + DateTime.Now; myStory["c_CustomString"] = "abc123"; Console.WriteLine("--------------------"); Console.WriteLine(myStory["FormattedID"]); OperationResult updateResult = restApi.Update(myStory["_ref"], myStory); //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); Console.WriteLine(myTask["FormattedID"]); } } catch (Exception e) { Console.WriteLine(e); } }
/// <summary> /// Performs a post action. /// </summary> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> private DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data, bool retry = true) { var response = serializer.Deserialize(httpService.Post(GetSecuredUri(uri), serializer.Serialize(data), GetProcessedHeaders())); if (retry && ConnectionInfo.SecurityToken != null && response[response.Fields.First()].Errors.Count > 0) { ConnectionInfo.SecurityToken = null; return DoPost(uri, data, false); } return response; }
/// <summary> /// Update the item described by the specified type and object id with /// the fields of the specified object /// </summary> /// <param name="typePath">the type of the item to be updated</param> /// <param name="oid">the object id of the item to be updated</param> /// <param name="obj">the object fields to update</param> /// <returns>An <see cref="OperationResult"/> describing the status of the request</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// DynamicJsonObject toUpdate = new DynamicJsonObject(); /// toUpdate["Description"] = "This is my defect."; /// OperationResult updateResult = restApi.Update("defect", "12345", toUpdate); /// </code> /// </example> public OperationResult Update(string typePath, string oid, DynamicJsonObject obj) { if (ConnectionInfo == null) throw new InvalidOperationException(AUTH_ERROR); var result = new OperationResult(); var data = new DynamicJsonObject(); data[typePath] = obj; dynamic response = DoPost(FormatUpdateUri(typePath, oid), data); if (response.OperationResult["Object"] != null) result.Object = response.OperationResult.Object; result.Errors.AddRange(DecodeArrayList(response.OperationResult.Errors)); result.Warnings.AddRange(DecodeArrayList(response.OperationResult.Warnings)); return result; }
/// <summary> /// Update the item described by the specified reference with /// the fields of the specified object /// </summary> /// <param name="reference">the reference to be updated</param> /// <param name="obj">the object fields to update</param> /// <returns>An <see cref="OperationResult"/> describing the status of the request</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// string rallyRef = "https://preview.rallydev.com/slm/webservice/1.40/defect/12345.js"; /// DynamicJsonObject toUpdate = new DynamicJsonObject(); /// toUpdate["Description"] = "This is my defect."; /// OperationResult updateResult = restApi.Update(rallyRef, toUpdate); /// </code> /// </example> public OperationResult Update(string reference, DynamicJsonObject obj) { return Update(Ref.GetTypeFromRef(reference), Ref.GetOidFromRef(reference), obj); }
/// <summary> /// Create an object of the specified type from the specified object /// </summary> /// <param name="workspaceRef">the workspace into which the object should be created. Null means that the server will pick a workspace.</param> /// <param name="typePath">the type to be created</param> /// <param name="obj">the object to be created</param> /// <returns>A <see cref="CreateResult"/> with information on the status of the request</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// string workspaceRef = "/workspace/12345678910"; /// DynamicJsonObject toCreate = new DynamicJsonObject(); /// toCreate["Name"] = "My Defect"; /// CreateResult createResult = restApi.Create(workspaceRef, "defect", toCreate); /// </code> /// </example> public CreateResult Create(string workspaceRef, string typePath, DynamicJsonObject obj) { if (ConnectionInfo == null) throw new InvalidOperationException(AUTH_ERROR); var data = new DynamicJsonObject(); data[typePath] = obj; DynamicJsonObject response = DoPost(FormatCreateUri(workspaceRef, typePath), data); DynamicJsonObject createResult = response["CreateResult"]; var createResponse = new CreateResult(); if (createResult.HasMember("Object")) { createResponse.Object = createResult["Object"]; createResponse.Reference = createResponse.Object["_ref"] as string; } createResponse.Errors.AddRange(DecodeArrayList(createResult["Errors"])); createResponse.Warnings.AddRange(DecodeArrayList(createResult["Warnings"])); return createResponse; }
/// <summary> /// Create an object of the specified type from the specified object /// </summary> /// <param name="typePath">the type to be created</param> /// <param name="obj">the object to be created</param> /// <returns>A <see cref="CreateResult"/> with information on the status of the request</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// DynamicJsonObject toCreate = new DynamicJsonObject(); /// toCreate["Name"] = "My Defect"; /// CreateResult createResult = restApi.Create("defect", toCreate); /// </code> /// </example> public CreateResult Create(string typePath, DynamicJsonObject obj) { return Create(null, typePath, obj); }
/// <summary> /// Performs a post of data to the provided URI. /// </summary> /// <param name="relativeUri">The relative URI to post the data to.</param> /// <param name="data">The data to submit to Rally.</param> /// <returns>A <see cref="DynamicJsonObject"/> with information on the response from Rally.</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// DynamicJsonObject data = objectToPost; /// restApi.Post("defect/12345", data) /// </code> /// </example> public DynamicJsonObject Post(String relativeUri, DynamicJsonObject data) { if (ConnectionInfo == null) throw new InvalidOperationException(AUTH_ERROR); Uri uri = new Uri(String.Format("{0}slm/webservice/{1}/{2}", httpService.Server.AbsoluteUri, WsapiVersion, relativeUri)); string postData = serializer.Serialize(data); return serializer.Deserialize(httpService.Post(uri, postData, GetProcessedHeaders())); }
/// <summary> /// Performs a post action. If first action fails there will occur up to 10 retries each backing off an incrementing number of seconds (wait 1 second, retry, wait 2 seconds, retry, etc). /// /// </summary> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> private DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data, bool retry = true, int retryCounter = 1) { int retrySleepTime = 1000; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.Expect100Continue = true; Dictionary<string, string> processedHeaders = GetProcessedHeaders(); var response = serializer.Deserialize(httpService.Post(GetSecuredUri(uri), serializer.Serialize(data), processedHeaders)); if (retry && response[response.Fields.First()].Errors.Count > 0 && retryCounter < 10) { ConnectionInfo.SecurityToken = GetSecurityToken(); httpService = new HttpService(authManger, ConnectionInfo); Thread.Sleep(retrySleepTime * retryCounter); return DoPost(uri, data, true, retryCounter++); } return response; } catch (Exception) { if (retryCounter < 10) { Thread.Sleep(retrySleepTime * retryCounter); return DoPost(uri, data, true, retryCounter++); } throw; } }
public void ShouldWork() { dynamic doc = new DynamicJsonObject(new RavenJObject()); Assert.True(string.IsNullOrEmpty(doc.Name)); }
/// <summary> /// 取值 /// </summary> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { //找不到键的值时为null(以免抛出异常,在用到可能会不存在的属性时要注意检查值是否为null) if (!_dictionary.TryGetValue(binder.Name, out result)) { result = null; return true; } //如果在上面的字典中找到值那么尝试转为字典类型 var dictionary = result as IDictionary<string, object>; if (dictionary != null) { result = new DynamicJsonObject(dictionary); //将结果进行递归 return true; } //不能转为字典时,将结果转为数组(如果数组中的第一个元素是字典型那就进行递归,不是时转为对像数组) var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { if (arrayList[0] is IDictionary<string, object>) result = new List<object>( arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))); else result = new List<object>(arrayList.Cast<object>()); } //不能转为数组时将结果result 直接返回 return true; }
public async Task<dynamic> GetGuess() { dynamic json = await Call_xiami_api("Recommend.getSongList"); //DailySongs var res = new DynamicJsonObject(new Dictionary<string, object> { { "songs", json } }); return res; }
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/1011574887"; String projectRef = "/project/1791269111"; String userName = "******"; try { Request storyRequest = new Request("hierarchicalrequirement"); storyRequest.Workspace = workspaceRef; storyRequest.Project = projectRef; storyRequest.Fetch = new List<string>() { "FormattedID" }; storyRequest.Query = new Query("FormattedID", Query.Operator.Equals, "US2917"); QueryResult queryResult = restApi.Query(storyRequest); var storyObject = queryResult.Results.First(); String storyReference = storyObject["_ref"]; Request userRequest = new Request("user"); userRequest.Fetch = new List<string>() { "UserName" }; userRequest.Query = new Query("UserName", Query.Operator.Equals, userName); QueryResult queryUserResults = restApi.Query(userRequest); DynamicJsonObject user = new DynamicJsonObject(); user = queryUserResults.Results.First(); String userRef = user["_ref"]; String imageFilePath = "C:\\images\\"; String imageFileName = "rally.png"; String fullImageFile = imageFilePath + imageFileName; Image myImage = Image.FromFile(fullImageFile); string imageBase64String = ImageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png); var imageNumberBytes = Convert.FromBase64String(imageBase64String).Length; Console.WriteLine("Image size: " + imageNumberBytes); DynamicJsonObject myAttachmentContent = new DynamicJsonObject(); myAttachmentContent["Content"] = imageBase64String; CreateResult myAttachmentContentCreateResult = restApi.Create(workspaceRef,"AttachmentContent", myAttachmentContent); String myAttachmentContentRef = myAttachmentContentCreateResult.Reference; Console.WriteLine(myAttachmentContentRef); DynamicJsonObject myAttachment = new DynamicJsonObject(); myAttachment["Artifact"] = storyReference; myAttachment["Content"] = myAttachmentContentRef; myAttachment["Name"] = "rally.png"; myAttachment["Description"] = "Attachment Desc"; myAttachment["ContentType"] = "image/png"; myAttachment["Size"] = imageNumberBytes; myAttachment["User"] = userRef; CreateResult myAttachmentCreateResult = restApi.Create(workspaceRef, "Attachment", myAttachment); List<string> createErrors = myAttachmentContentCreateResult.Errors; for (int i = 0; i < createErrors.Count; i++) { Console.WriteLine(createErrors[i]); } String myAttachmentRef = myAttachmentCreateResult.Reference; Console.WriteLine(myAttachmentRef); } catch (Exception e) { Console.WriteLine(e); } }
public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!this.dictionary.TryGetValue(binder.Name, out result)) { result = null; return true; } var dictionary = result as IDictionary<string, object>; if (dictionary != null) { result = new DynamicJsonObject(dictionary); return true; } var arrayList = result as ArrayList; if (arrayList != null) { if (arrayList.Count > 0 && arrayList[0] is IDictionary<string, object>) result = new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))); else result = new List<object>(arrayList.Cast<object>()); } return true; }
/// <summary> /// Performs a post of data to the provided URI. /// </summary> /// <param name="relativeUri">The relative URI to post the data to.</param> /// <param name="data">The data to submit to Rally.</param> /// <returns>A <see cref="DynamicJsonObject"/> with information on the response from Rally.</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// DynamicJsonObject data = objectToPost; /// restApi.Post("defect/12345", data) /// </code> /// </example> public DynamicJsonObject Post(String relativeUri, DynamicJsonObject data) { if (ConnectionInfo == null) throw new InvalidOperationException("You must authenticate against Rally prior to performing any data operations."); Uri uri = new Uri(String.Format("{0}slm/webservice/{1}/{2}", httpService.Server.AbsoluteUri, WsapiVersion, relativeUri)); string postData = serializer.Serialize(data); return serializer.Deserialize(httpService.Post(uri, postData, GetProcessedHeaders())); }
/// <summary> /// Update the item described by the specified type and object id with /// the fields of the specified object /// </summary> /// <param name="typePath">the type of the item to be updated</param> /// <param name="oid">the object id of the item to be updated</param> /// <param name="obj">the object fields to update</param> /// <returns>An <see cref="OperationResult"/> describing the status of the request</returns> /// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception> /// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception> /// <example> /// <code language="C#"> /// DynamicJsonObject toUpdate = new DynamicJsonObject(); /// toUpdate["Description"] = "This is my defect."; /// OperationResult updateResult = restApi.Update("defect", "12345", toUpdate); /// </code> /// </example> public OperationResult Update(string typePath, string oid, DynamicJsonObject obj) { if (ConnectionInfo == null) throw new InvalidOperationException("You must authenticate against Rally prior to performing any data operations."); var result = new OperationResult(); var data = new DynamicJsonObject(); data[typePath] = obj; dynamic response = DoPost(FormatUpdateUri(typePath, oid), data); if (response.OperationResult["Object"] != null) result.Object = response.OperationResult.Object; result.Errors.AddRange(DecodeArrayList(response.OperationResult.Errors)); result.Warnings.AddRange(DecodeArrayList(response.OperationResult.Warnings)); return result; }
public dynamic LoadDocument(string key) { if (key == null) return new DynamicNullObject(); var source = Source; if (source == null) throw new ArgumentException( "LoadDocument can only be called as part of the Map stage of the index, but was called with " + key + " without a source."); var id = source.__document_id as string; if (string.IsNullOrEmpty(id)) throw new ArgumentException( "LoadDocument can only be called as part of the Map stage of the index, but was called with " + key + " without a document. Current source: " + source); if (string.Equals(key, id)) return source; HashSet<string> set; if(ReferencedDocuments.TryGetValue(id, out set) == false) ReferencedDocuments.Add(id, set = new HashSet<string>(StringComparer.OrdinalIgnoreCase)); set.Add(key); dynamic value; if (docsCache.TryGetValue(key, out value)) return value; LoadDocumentDuration.Start(); var doc = database.Documents.Get(key, null); LoadDocumentDuration.Stop(); LoadDocumentCount++; if (doc == null) { log.Debug("Loaded document {0} by document {1} for index {2} could not be found", key, id, index); ReferencesEtags.Add(key, Etag.Empty); value = new DynamicNullObject(); } else { log.Debug("Loaded document {0} with etag {3} by document {1} for index {2}\r\n{4}", key, id, index, doc.Etag, doc.ToJson()); ReferencesEtags.Add(key, doc.Etag); value = new DynamicJsonObject(doc.ToJson()); } docsCache[key] = value; return value; }