static void Main(string[] args)
        {
            RallyRestApi restApi;
            restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0");

            String projectRef = "/project/12352608219";
            Request defectRequest = new Request("Defect");
            defectRequest.Project = projectRef;
            defectRequest.Fetch = new List<string>()
                {
                    "Name",
            "FormattedID",
                    "Tasks"
                };

            defectRequest.Query = new Query("FormattedID", Query.Operator.Equals, "DE8");
            QueryResult defectResults = restApi.Query(defectRequest);
            String defRef = defectResults.Results.First()._ref;
            String defName = defectResults.Results.First().Name;
            Console.WriteLine(defName + " " + defRef);
            DynamicJsonObject defect = restApi.GetByReference(defRef, "Name", "FormattedID", "Tasks");
            String taskCollectionRef = defect["Tasks"]._ref;
            Console.WriteLine(taskCollectionRef);

            ArrayList taskList = new ArrayList();

            foreach (var d in defectResults.Results)
            {
                Request tasksRequest = new Request(d["Tasks"]);
                QueryResult tasksResult = restApi.Query(tasksRequest);
                foreach (var t in tasksResult.Results)
                {
                    var tName = t["Name"];
                    var tFormattedID = t["FormattedID"];
                    Console.WriteLine("Task: " + tName + " " + tFormattedID);
                    DynamicJsonObject task = new DynamicJsonObject();
                    task["_ref"] = t["_ref"];
                    taskList.Add(task);
                }
            }

            Console.WriteLine("Count of elements in the collection before adding a new task: " + taskList.Count);

            DynamicJsonObject newTask = new DynamicJsonObject();
            newTask["Name"] = "another last task";
            newTask["WorkProduct"] = defRef;
            CreateResult createResult = restApi.Create(projectRef, "Task", newTask);
            newTask = restApi.GetByReference(createResult.Reference, "FormattedID", "Name", "WorkProduct");
            Console.WriteLine(newTask["FormattedID"] + " " + newTask["Name"] + " WorkProduct:" + newTask["WorkProduct"]["FormattedID"]);
            taskList.Add(newTask);

            Console.WriteLine("Count of elements in the array after adding a new task: " + taskList.Count);
            defect["Tasks"] = taskList;
            OperationResult updateResult = restApi.Update(defRef, defect);
        }
        /// <summary>
        /// Get the value of the specified member
        /// Equivalent to using [name].
        /// </summary>
        /// <param name="name">The specified member</param>
        /// <returns>The value of the specified member</returns>
        protected dynamic GetMember(string name)
        {
            var result = Dictionary[name];

            if (result is IDictionary <string, object> )
            {
                result = new DynamicJsonObject(result as IDictionary <string, object>);
            }
            else if (result is ArrayList)
            {
                var list = new ArrayList();
                foreach (var i in result as ArrayList)
                {
                    if (i is IDictionary <string, object> )
                    {
                        list.Add(new DynamicJsonObject(i as IDictionary <string, object>));
                    }
                    else
                    {
                        list.Add(i);
                    }
                }
                result = list;
            }

            return(result);
        }
Esempio n. 3
0
        public DynamicJsonObject post(String relativeUri, DynamicJsonObject data)
        {
            Uri    uri      = new Uri(String.Format("{0}slm/webservice/{1}/{2}", Service.Server.AbsoluteUri, wsapiVersion, relativeUri));
            string postData = serializer.Serialize(data);

            return(serializer.Deserialize(Service.Post(uri, postData, GetProcessedHeaders())));
        }
Esempio n. 4
0
        int DoSign(IEnumerable<Artifact> artifacts, SynchronizationContext sc)
        {
            var restApi = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword
                //, proxy: new WebProxy("localhost:8888", false)
                );

            foreach (var tagArt in artifacts)
            {
                var toCreate = new DynamicJsonObject();
                toCreate["Text"] = "%FIX_CODE_REVIEW_PASSED%";
                toCreate["Artifact"] = tagArt.Reference;
                var createResult = restApi.Create("ConversationPost", toCreate);

                // update status
                sc.Post(_ => {
                    var lvi = listViewArtifacts.Items.Cast<ListViewItem>().FirstOrDefault(l => l.Tag == tagArt);
                    if (!createResult.Success)
                    {
                        lvi.BackColor = Color.Tomato;

                        if (createResult.Errors.Count > 0)
                            lvi.SubItems[1].Text = createResult.Errors[0];
                        else
                            lvi.SubItems[1].Text = "Unexpected error";
                    }
                    else
                    {
                        lvi.BackColor = Color.LightGreen;
                        lvi.SubItems[3].Text = "✔";
                    }
                }, null);
            }

            return 0;
        }
Esempio n. 5
0
        /// <summary>
        /// Get the value of the specified member
        /// Equivalent to using [name].
        /// </summary>
        /// <param name="name">The specified member</param>
        /// <returns>The value of the specified member</returns>
        protected dynamic GetMember(string name)
        {
            // Prevent exceptions
            if (!Dictionary.ContainsKey(name))
            {
                return(null);
            }

            var result = Dictionary[name];

            if (result is IDictionary <string, object> )
            {
                result = new DynamicJsonObject(result as IDictionary <string, object>);
            }
            else if (result is ArrayList)
            {
                var list = new ArrayList();
                foreach (var i in result as ArrayList)
                {
                    if (i is IDictionary <string, object> )
                    {
                        list.Add(new DynamicJsonObject(i as IDictionary <string, object>));
                    }
                    else
                    {
                        list.Add(i);
                    }
                }
                result = list;
            }

            return(result);
        }
        /// <summary>
        /// Get the value of the specified member
        /// Equivalent to using [name].
        /// </summary>
        /// <param name="name">The specified member</param>
        /// <returns>The value of the specified member</returns>
        protected dynamic GetMember(string name)
        {
            var result = Dictionary[name];

            if (result is IDictionary<string, object>)
            {
                result = new DynamicJsonObject(result as IDictionary<string, object>);
            }
            else if (result is ArrayList)
            {
                var list = new ArrayList();
                foreach (var i in result as ArrayList)
                {
                    if (i is IDictionary<string, object>)
                    {
                        list.Add(new DynamicJsonObject(i as IDictionary<string, object>));
                    }
                    else
                        list.Add(i);
                }
                result = list;
            }

            return result;
        }
Esempio n. 7
0
 private void Configure(string artifactName = null, DynamicJsonObject collection = null)
 {
     ArtifactName = artifactName;
     _collection  = collection;
     Parameters   = new Dictionary <string, dynamic>();
     Fetch        = new List <string>();
     PageSize     = MaxPageSize;
     Start        = 1;
     Limit        = PageSize;
 }
Esempio n. 8
0
        DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data, bool retry)
        {
            var response = serializer.Deserialize(Service.Post(GetSecuredUri(uri), serializer.Serialize(data), GetProcessedHeaders()));

            if (retry && securityToken != null && response[response.Fields.First()].Errors.Count > 0)
            {
                securityToken = null;
                return(DoPost(uri, data, false));
            }
            return(response);
        }
Esempio n. 9
0
 string GetSecurityToken()
 {
     try
     {
         DynamicJsonObject securityTokenResponse = DoGet(new Uri(GetFullyQualifiedRef("/security/authorize")));
         return(securityTokenResponse["OperationResult"]["SecurityToken"]);
     }
     catch
     {
         return(null);
     }
 }
Esempio n. 10
0
        /// <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 OperationResult describing the status of the request</returns>
        public OperationResult Update(string typePath, string oid, DynamicJsonObject obj)
        {
            var result = new OperationResult();
            var data   = new DynamicJsonObject();

            data[typePath] = obj;
            dynamic response = DoPost(FormatUpdateUri(typePath, oid), data);

            result.Errors.AddRange(DecodeArrayList(response.OperationResult.Errors));
            result.Warnings.AddRange(DecodeArrayList(response.OperationResult.Warnings));
            return(result);
        }
        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 IterationArtifact(DynamicJsonObject artifact = null)
            : base(artifact)
        {
            if (artifact == null)
                return;

            var sd = TryGetMember<string>(artifact, "StartDate");
            if (sd != null)
                DateTimeOffset.TryParse(sd, out StartDate);

            var ed = TryGetMember<string>(artifact, "EndDate");
            if(ed != null)
                DateTimeOffset.TryParse(ed, out EndDate);
        }
Esempio n. 13
0
        /// <summary>
        /// Get the object described by the specified reference.
        /// </summary>
        /// <param name="aRef">the reference</param>
        /// <param name="fetchedFields">the list of object fields to be fetched</param>
        /// <returns>The requested object</returns>
        public dynamic GetByReference(string aRef, params string[] fetchedFields)
        {
            if (fetchedFields.Length == 0)
            {
                fetchedFields = new string[] { "true" };
            }

            if (!aRef.Contains(".js"))
            {
                aRef = aRef + ".js";
            }

            DynamicJsonObject wrappedReponse = DoGet(GetFullyQualifiedUri(aRef + "?fetch=" + string.Join(",", fetchedFields)));

            return(string.Equals(wrappedReponse.Fields.FirstOrDefault(), "OperationResult", StringComparison.CurrentCultureIgnoreCase) ? null : wrappedReponse[wrappedReponse.Fields.First()]);
        }
Esempio n. 14
0
        /// <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></returns>
        public CreateResult Create(string workspaceRef, string typePath, DynamicJsonObject obj)
        {
            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);
        }
Esempio n. 15
0
        /// <summary>
        /// Get the object described by the specified reference.
        /// </summary>
        /// <param name="aRef">the reference</param>
        /// <param name="fetchedFields">the list of object fields to be fetched</param>
        /// <returns>The requested object</returns>
        public dynamic GetByReference(string aRef, params string[] fetchedFields)
        {
            if (fetchedFields.Length == 0)
            {
                fetchedFields = new string[] { "true" };
            }

            if (!aRef.Contains(".js"))
            {
                aRef = aRef + ".js";
            }
            string type = Ref.GetTypeFromRef(aRef) ??
                          //Handle case for things like user, subscription
                          aRef.Split(new[] { '.', '/' }, StringSplitOptions.RemoveEmptyEntries)[0];

            DynamicJsonObject wrappedReponse = DoGet(GetFullyQualifiedUri(aRef + "?fetch=" + string.Join(",", fetchedFields)));

            return(type.Equals(wrappedReponse.Fields.FirstOrDefault(), StringComparison.CurrentCultureIgnoreCase) ? wrappedReponse[wrappedReponse.Fields.First()] : null);
        }
        static void Main(string[] args)
        {
            RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://rally1.rallydev.com", "v2.0");
            String workspaceRef = "/workspace/11111"; //use valid workspace OID in your Rally
            String projectRef = "/project/12345";         //use valid project OID in your Rally
            String userRef = "/user/777";
            DynamicJsonObject d = new DynamicJsonObject();
            d["Name"] = "some bug";
            d["Project"] = projectRef;
            d["Owner"] = userRef;

            CreateResult createResult = restApi.Create(workspaceRef, "Defect", d);
            DynamicJsonObject defect = restApi.GetByReference(createResult.Reference, "FormattedID");
            Console.WriteLine(defect["FormattedID"]);

            //update defect
            defect["Description"] = "bad bug";
            OperationResult updateResult = restApi.Update(defect["_ref"], defect);
        }
Esempio n. 17
0
        public 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
            {
                Trace.TraceInformation("Get ({0}):\r\n{1}\r\nRequest Headers:\r\n{2}Response Headers:\r\n{3}Response Data\r\n{4}",
                                       DateTime.Now.Subtract(startTime).ToString(),
                                       target.ToString(),
                                       requestHeaders,
                                       responseHeaders,
                                       response);
            }
        }
        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);
        }
        private CachedResult CacheResult(string userName, string sourceUrl, string redirectUrl, DynamicJsonObject responseData)
        {
            string       cacheKey     = GetCacheKey(userName, sourceUrl);
            CachedResult cachedResult = new CachedResult(redirectUrl, responseData);

            lock (dataLock)
            {
                if (cachedResults.ContainsKey(cacheKey))
                {
                    cachedResults[cacheKey] = cachedResult;
                }
                else
                {
                    cachedResults.Add(cacheKey, cachedResult);
                }
            }

            return(cachedResult);
        }
 public CachedResult(string redirectUrl, DynamicJsonObject responseData)
 {
     Url          = redirectUrl;
     ResponseData = responseData;
 }
 /// <summary>
 /// Create a new Request for the specified collection. (ie Defect.Tasks)
 /// The collection should have a _ref property.
 /// </summary>
 /// <param name="collection">The object containing the collection ref</param>
 public Request(DynamicJsonObject collection)
     : this()
 {
     this.collection = collection;
 }
Esempio n. 22
0
 public string Serialize(DynamicJsonObject value)
 {
     return(SerializeDictionary(value.Dictionary));
 }
Esempio n. 23
0
 DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data)
 {
     return(DoPost(uri, data, true));
 }
Esempio n. 24
0
        //Creates the test case
        public static void CreateTestCaseWork(string testcase)
        {
            Console.WriteLine("CreateTestCaseWork method");
            string rallyUser = System.Configuration.ConfigurationManager.AppSettings["rallyUser"];
            string rallyPassword = System.Configuration.ConfigurationManager.AppSettings["rallyPassword"];
            string workspaceRef = "https://rally1.rallydev.com/slm/webservice/1.40/workspace/144782102.js";
            //Log into rally
            RallyRestApi restApi = new RallyRestApi(rallyUser, rallyPassword, "https://rally1.rallydev.com", "1.40");

            try
            {
                //Search to see if this test case already exists, if it does, we don't want to create another one so do nothing

                Request request = new Request("testcase");
                request.Fetch = new List<string>
                {
                    "Name",
                    "ObjectID",
                };

                request.Query = new Query("Name", Query.Operator.Equals, testcase);
                QueryResult queryResult = restApi.Query(request);

                var result = queryResult.Results.First();
                var objectID = result["ObjectID"];
                Console.WriteLine("Found the test case: " + result["Name"] + " " + result["ObjectID"]);
            }

            catch (InvalidOperationException e)
            {
                //If the test case doesn't exist, then we need to create it
                DynamicJsonObject toCreate = new DynamicJsonObject();
                toCreate["Name"] = testcase;
                toCreate["Method"] = "Automated";
                CreateResult createResult = restApi.Create(workspaceRef, "testcase", toCreate);

                Console.WriteLine("Created testcase: " + testcase);

            }
        }
 /// <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 OperationResult describing the status of the request</returns>
 public OperationResult Update(string typePath, string oid, DynamicJsonObject obj)
 {
     var result = new OperationResult();
     var data = new DynamicJsonObject();
     data[typePath] = obj;
     dynamic response = DoPost(FormatUpdateUri(typePath, oid), data);
     result.Errors.AddRange(DecodeArrayList(response.OperationResult.Errors));
     result.Warnings.AddRange(DecodeArrayList(response.OperationResult.Warnings));
     return result;
 }
 public string Serialize(DynamicJsonObject value)
 {
     return SerializeDictionary(value.Dictionary);
 }
 /// <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></returns>
 public CreateResult Create(string workspaceRef, string typePath, DynamicJsonObject obj)
 {
     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;
 }
Esempio n. 28
0
 /// <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></returns>
 public CreateResult Create(string typePath, DynamicJsonObject obj)
 {
     return(Create(null, typePath, obj));
 }
 DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data, bool retry)
 {
     var response = serializer.Deserialize(Service.Post(GetSecuredUri(uri), serializer.Serialize(data), GetProcessedHeaders()));
     if (retry && securityToken != null && response[response.Fields.First()].Errors.Count > 0)
     {
         securityToken = null;
         return DoPost(uri, data, false);
     }
     return response;
 }
 public DynamicJsonObject post(String relativeUri, DynamicJsonObject data)
 {
     Uri uri = new Uri(String.Format("{0}slm/webservice/{1}/{2}", Service.Server.AbsoluteUri, wsapiVersion, relativeUri));
     string postData = serializer.Serialize(data);
     return serializer.Deserialize(Service.Post(uri, postData, GetProcessedHeaders()));
 }
        void buttonPostFDP_Click(object sender, EventArgs e)
        {
            UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.CommitToolPostFDP);

            var t = CancellableWait.Wait("Resolve URL...", _resolveRallyUrlsTask);
            if(t.IsFaulted)
            {
                MessageBoxEx.ShowError("Resolve URL failed");
                return;
            }

            if (t.IsCanceled)
                return;

            try
            {
                buttonPostFDP.Enabled = false;

                UseWaitCursor = true;

                var restApi = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword
                    //, proxy: new WebProxy("localhost:8888", false)
                );

                var textLines = File.ReadAllText(_fdpFilePath)
                    .Split('\n')
                    .Select(l => l.Replace("\r", ""))
                ;

                var text = string.Join("<br/>", textLines.Select(HttpUtility.HtmlEncode).Select(l => l.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")));

                var art = _issues[0].RallyArtifact;

                var toCreate = new DynamicJsonObject();
                toCreate["Text"] = text;
                toCreate["Artifact"] = art.Reference;
                var createResult = restApi.Create("ConversationPost", toCreate);

                if (!createResult.Success)
                {
                    MessageBoxEx.ShowError(string.Join("\n", createResult.Errors.DefaultIfEmpty("Unexpected")));
                    return;
                }

                if (MessageBox.Show("Discussion post added.\nOpen discussion in browser?", "Success", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    Process.Start(_issues[0].RallyUrl + "/discussion");
            }
            finally
            {
                buttonPostFDP.Enabled = true;
                UseWaitCursor = false;
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Create a new Request for the specified collection. (ie Defect.Tasks)
 /// The collection should have a _ref property.
 /// </summary>
 /// <param name="collection">The object containing the collection ref</param>
 /// <example>
 /// <code>
 /// DynamicJsonObject collection = new DynamicJsonObject();
 /// collection["_ref"] = "/hierarchicalrequirement/12345/defect.js";
 /// Request request = new Request(collection);
 /// </code>
 /// </example>
 public Request(DynamicJsonObject collection)
 {
     Configure(collection: collection);
 }
Esempio n. 33
0
        /// <summary>
        /// Create a request object from a url string.
        /// </summary>
        /// <param name="url">the url we are creating from</param>
        /// <returns>A request object that represents the reference string.</returns>
        public static Request CreateFromUrl(string url)
        {
            Request request = new Request();
            int     index   = url.IndexOf("?");
            string  primaryUrl;

            if (index <= 0)
            {
                primaryUrl = url;
            }
            else
            {
                primaryUrl = url.Substring(0, index);
                string   parameters     = url.Substring(index + 1);
                string[] parameterParts = parameters.Split(new char[] { '&' });
                foreach (string paramPart in parameterParts)
                {
                    string[] paramParts = paramPart.Split(new char[] { '=' });
                    if (paramParts.Length != 2)
                    {
                        continue;
                    }

                    string valueString = HttpUtility.UrlDecode(paramParts[1]);
                    if (paramParts[0].Equals("pagesize", StringComparison.InvariantCultureIgnoreCase))
                    {
                        int pageSize;
                        if (Int32.TryParse(valueString, out pageSize))
                        {
                            request.PageSize = pageSize;
                        }
                    }
                    else if (paramParts[0].Equals("start", StringComparison.InvariantCultureIgnoreCase))
                    {
                        int start;
                        if (Int32.TryParse(valueString, out start))
                        {
                            request.Start = start;
                        }
                    }
                    else if (paramParts[0].Equals("fetch", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!valueString.Equals("true", StringComparison.InvariantCultureIgnoreCase))
                        {
                            string[]      fetchParts  = valueString.Split(new string[] { "," }, StringSplitOptions.None);
                            List <string> fetchString = new List <string>();
                            fetchString.AddRange(fetchParts);
                            request.Fetch = fetchString;
                        }
                    }
                    else if (paramParts[0].Equals("order", StringComparison.InvariantCultureIgnoreCase))
                    {
                        request.Order = valueString;
                    }
                    else
                    {
                        if (request.Parameters.ContainsKey(paramParts[0]))
                        {
                            request.Parameters[paramParts[0]] = valueString;
                        }
                        else
                        {
                            request.Parameters.Add(paramParts[0], valueString);
                        }
                    }
                }
            }

            string primaryUrlStringToFind = "webservice/";

            primaryUrl = primaryUrl.Replace(".js", String.Empty);
            index      = primaryUrl.IndexOf(primaryUrlStringToFind);
            string rightUrl = primaryUrl.Substring(index + primaryUrlStringToFind.Length + 1);

            index = rightUrl.IndexOf("/");
            string artifactUrl = rightUrl.Substring(index + 1);

            if (artifactUrl.Contains("/"))
            {
                DynamicJsonObject collection = new DynamicJsonObject();
                collection["_ref"] = primaryUrl;
                request.collection = collection;
            }
            else
            {
                request.ArtifactName = artifactUrl;
            }

            return(request);
        }
Esempio n. 34
0
        public static void CreateTestCaseResultWork(string testcase, string result, string notes)
        {
            string rallyUser = System.Configuration.ConfigurationManager.AppSettings["rallyUser"];
            string rallyPassword = System.Configuration.ConfigurationManager.AppSettings["rallyPassword"];
            string build = System.Configuration.ConfigurationManager.AppSettings["build"];
            string workspaceRef = "https://rally1.rallydev.com/slm/webservice/1.40/workspace/144782102.js";
            //Log into rally
            RallyRestApi restApi = new RallyRestApi(rallyUser, rallyPassword, "https://rally1.rallydev.com", "1.40");

            try
            {
                //Search to see if this test case exists

                Request request = new Request("testcase");
                request.Fetch = new List<string>
                {
                    "Name",
                    "ObjectID",
                };

                request.Query = new Query("Name", Query.Operator.Equals, testcase);
                QueryResult queryResult = restApi.Query(request);

                var result2 = queryResult.Results.First();
                var objectID = result2["ObjectID"];
                Console.WriteLine("Found the test case: " + result2["Name"] + " " + result2["ObjectID"]);

                //Create the test case result object
                DynamicJsonObject newTCResult = new DynamicJsonObject();
                newTCResult["Date"] = DateTime.UtcNow.ToString("o");
                newTCResult["TestCase"] = objectID;
                newTCResult["Notes"] = notes;
                newTCResult["Build"] = build;
                newTCResult["Verdict"] = result;

                CreateResult cr = restApi.Create(workspaceRef, "TestCaseResult", newTCResult);
                Console.WriteLine("Created test case result");
            }

            catch (InvalidOperationException e)
            {
                //If the test case doesn't exist, then we need to create it
                Console.WriteLine("Cannot find the test case: " + testcase);

            }
        }
 /// <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 OperationResult describing the status of the request</returns>
 public OperationResult Update(string reference, DynamicJsonObject obj)
 {
     return Update(Ref.GetTypeFromRef(reference), Ref.GetOidFromRef(reference), obj);
 }
Esempio n. 36
0
 /// <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 OperationResult describing the status of the request</returns>
 public OperationResult Update(string reference, DynamicJsonObject obj)
 {
     return(Update(Ref.GetTypeFromRef(reference), Ref.GetOidFromRef(reference), obj));
 }
 DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data)
 {
     return DoPost(uri, data, true);
 }
Esempio n. 38
0
 void textBoxUser_TextChanged(object sender, EventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(textBoxUser.Text))
         _currentUser = null;
 }
Esempio n. 39
0
        List<ChangedArtifact> LoadChanges(DateTime fromTime, DateTime toTime, CancellationToken ct)
        {
            var toS = toTime.ToString("yyyy-MM-ddTHH:mm:ss");
            var fromS = fromTime.ToString("yyyy-MM-ddTHH:mm:ss");

            var client = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword, cancellationToken: ct);

            if (_currentUser == null)
            {
                backgroundOperation.SetProgress("Get current user ...");
                if (string.IsNullOrWhiteSpace(textBoxUser.Text) || textBoxUser.Tag != null)
                {
                    _currentUser = client.GetCurrentUser();
                }
                else
                {
                    var query = new Query("(UserName = "******")");
                    var resp = client.Query(new Request("user") { Query = query });
                    _currentUser = resp.Results.First();
                }
            }

            // retrieve revisions
            var requestRevs = new Request("revision");
            requestRevs.Limit = Int32.MaxValue;
            requestRevs.Fetch = new List<string> { "Description", "RevisionHistory", "CreationDate" };
            requestRevs.Query = new Query("User", Query.Operator.Equals, _currentUser["UserName"])
                .And(new Query("CreationDate", Query.Operator.GreaterThanOrEqualTo, fromS))
                .And(new Query("CreationDate", Query.Operator.LessThanOrEqualTo, toS))
            ;

            backgroundOperation.SetProgress("Load revisions ...");

            var resultRevs = client.Query(requestRevs);

            var revHists = resultRevs.Results.Cast<DynamicJsonObject>()
                .GroupBy(r => (string)r["RevisionHistory"]["_refObjectUUID"])
                .ToDictionary(g => g.Key, g => g.Select(r => (DynamicJsonObject)r).ToList())
            ;

            // check cancellation
            ct.ThrowIfCancellationRequested();

            // query artifacts
            var requestArtifacts = new Request("artifact");
            requestArtifacts.Limit = Int32.MaxValue;
            requestArtifacts.Fetch = new List<string> { "FormattedID", "Name", "RevisionHistory", "LastUpdateDate", "Requirement", "WorkProduct", "ObjectID", "Owner", "Project" };
            requestArtifacts.Query = new Query("LastUpdateDate", Query.Operator.GreaterThanOrEqualTo, fromS)
                .And(new Query("LastUpdateDate", Query.Operator.LessThanOrEqualTo, toS))
            ;

            var artUuid2Revs = new Dictionary<string, List<DynamicJsonObject>>();
            var artUuid2Art = new Dictionary<string, DynamicJsonObject>();

            backgroundOperation.SetProgress("Load artifacts ...");

            var resultArts = client.Query(requestArtifacts);

            foreach (var art in resultArts.Results)
            {
                // can't inject in Query ....
                var type = (string)art["_type"];
                if (type != "Task" && type != "Defect")
                    continue;

                var histUuid = (string)art["RevisionHistory"]["_refObjectUUID"];
                if (!revHists.ContainsKey(histUuid))
                    continue;

                List<DynamicJsonObject> artifactRevs;
                if (!artUuid2Revs.TryGetValue((string)art["_refObjectUUID"], out artifactRevs))
                {
                    artifactRevs = new List<DynamicJsonObject>();
                    artUuid2Revs[(string)art["_refObjectUUID"]] = artifactRevs;
                }

                artifactRevs.AddRange(revHists[histUuid]);
                artUuid2Art[(string)art["_refObjectUUID"]] = art;
            }

            foreach (var group in artUuid2Art.GroupBy(kvp => new Artifact(kvp.Value).Type).ToArray())
            {
                ct.ThrowIfCancellationRequested();

                backgroundOperation.SetProgress(string.Format("Loading group of '{0}' ...", group.Key));

                var allIds = group.Select(a => new Artifact(a.Value).ObjectID.ToString(CultureInfo.InvariantCulture)).ToArray();
                var query = allIds
                    .Skip(1)
                    .Aggregate(new Query("ObjectId", Query.Operator.Equals, allIds.First()), (current, id) => current.Or(new Query("ObjectId", Query.Operator.Equals, id)))
                ;

                var r = new Request(group.First().Value["_type"]);
                r.Limit = Int32.MaxValue;
                r.Query = query;
                var qr = client.Query(r);

                foreach (var result in qr.Results)
                {
                    if (result["_type"] == "Task")
                    {
                        artUuid2Art[result["_refObjectUUID"]]["Estimate"] = (double)result["Estimate"];
                        artUuid2Art[result["_refObjectUUID"]]["ToDo"] = (double)result["ToDo"];
                        artUuid2Art[result["_refObjectUUID"]]["State"] = (string)result["State"];
                    }
                    else if (result["_type"] == "Defect")
                    {
                        //var additionalInfo = client.GetByReference(art.Reference);

                        //artUuid2Art[kvp.Key]["Estimate"] = additionalInfo["Estimate"];
                        //artUuid2Art["ToDo"] = additionalInfo["ToDo"];
                    }
                }
            }

            var changes = artUuid2Revs
                .Select(kvp => new ChangedArtifact { Artifact = artUuid2Art[kvp.Key], Revisions = kvp.Value, WorkItem = new Artifact(artUuid2Art[kvp.Key]) })
                .ToList()
            ;

            UpdateCache(changes);

            return changes;
        }
Esempio n. 40
0
 /// <summary>
 /// Create a new Request for the specified collection. (ie Defect.Tasks)
 /// The collection should have a _ref property.
 /// </summary>
 /// <param name="collection">The object containing the collection ref</param>
 public Request(DynamicJsonObject collection)
     : this()
 {
     this.collection = collection;
 }
 /// <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></returns>
 public CreateResult Create(string typePath, DynamicJsonObject obj)
 {
     return Create(null, typePath, obj);
 }