コード例 #1
0
        /// <summary>Generates a RemoteSort to be used on client calls.</summary>
        /// <returns>RemoteSort</returns>
        public static RemoteSort GenerateSort()
        {
            RemoteSort sort = new RemoteSort();

            sort.PropertyName  = "UserId";
            sort.SortAscending = true;

            return(sort);
        }
コード例 #2
0
ファイル: SpiraConnect.cs プロジェクト: Inflectra/spira-sdk
        /// <summary>
        /// Returns the list of documents attached to a test case
        /// </summary>
        /// <param name="projectId">The id of the project</param>
        /// <param name="testCaseId">The id of the test case</param>
        /// <returns>The list of documents</returns>
        public List <AttachedDocument> GetAttachedDocuments(int projectId, int testCaseId)
        {
            List <AttachedDocument> attachedDocs = new List <AttachedDocument>();

            //Connect to the project.
            if (this._client.Connection_ConnectToProject(projectId))
            {
                try
                {
                    RemoteSort remoteSort = new RemoteSort();
                    remoteSort.PropertyName  = "Filename";
                    remoteSort.SortAscending = true;
                    RemoteDocument[] remoteDocuments = this._client.Document_RetrieveForArtifact((int)ArtifactType.TestCase, testCaseId, null, remoteSort);

                    //Iterate through each document and download the physical file if it is a file
                    foreach (RemoteDocument remoteDocument in remoteDocuments)
                    {
                        //Populate the internal object class
                        AttachedDocument attachedDoc = new AttachedDocument();
                        attachedDocs.Add(attachedDoc);
                        attachedDoc.Type                      = (AttachedDocument.AttachmentType)remoteDocument.AttachmentTypeId;
                        attachedDoc.FilenameOrUrl             = remoteDocument.FilenameOrUrl;
                        attachedDoc.TestCaseId                = remoteDocument.ArtifactId.Value;
                        attachedDoc.ProjectAttachmentTypeId   = remoteDocument.ProjectAttachmentTypeId.Value;
                        attachedDoc.ProjectAttachmentFolderId = remoteDocument.ProjectAttachmentFolderId.Value;
                        attachedDoc.Size                      = remoteDocument.Size;
                        attachedDoc.Tags                      = remoteDocument.Tags;
                        attachedDoc.UploadDate                = remoteDocument.UploadDate;
                        attachedDoc.EditedDate                = remoteDocument.EditedDate;
                        attachedDoc.CurrentVersion            = remoteDocument.CurrentVersion;

                        if (remoteDocument.AttachmentTypeId == (int)AttachedDocument.AttachmentType.File)
                        {
                            byte[] binaryData = this._client.Document_OpenFile(remoteDocument.AttachmentId.Value);
                            attachedDoc.BinaryData = binaryData;
                        }
                    }
                }
                catch (Exception exception)
                {
                    string strMessage = "Error getting attachments for test case TC:" + testCaseId + " in project PR:" + projectId + " (" + exception.Message + ")";
                    Logger.LogMessage(strMessage, System.Diagnostics.EventLogEntryType.Error);
                    return(null);
                }
            }
            else
            {
                string strMessage = "Could not connect to project PR:" + projectId + ".";
                Logger.LogMessage(strMessage, System.Diagnostics.EventLogEntryType.Error);
                return(null);
            }

            return(attachedDocs);
        }
        /// <summary>Hit when the client is finished getting a list of Tasks for the user.</summary>
        /// <param name="sender">The client that caused the event.</param>
        /// <param name="evt">Event Args.</param>
        private void client_FinishTask(object sender, Task_RetrieveCompletedEventArgs evt)
        {
            try
            {
                ImportExport client = (ImportExport)sender;
                ObjectState  evtObj = (ObjectState)evt.UserState;

                //Make the current node and the existing parent node.
                TreeViewItem tskItemNode = new TreeViewItem();
                TreeViewItem tskNode     = (TreeViewItem)((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items[NODE_TASKNUM];

                //Get the label.
                string nodeLabel = ((evtObj.curSearchIsMine) ? "My" : "Unassigned") + " " + this._resources.GetString("strTasks");

                if (evt.Error == null)
                {
                    //Set the image & change text.
                    if (evt.Result.Length > 0)
                    {
                        tskItemNode.Header = createNodeHeader("imgFolderTask", nodeLabel + " (" + evt.Result.Length + ")");
                    }
                    else
                    {
                        tskItemNode.Header = createNodeHeader("imgFolderTask", nodeLabel);
                    }

                    //Add child nodes.
                    foreach (RemoteTask Tsk in evt.Result)
                    {
                        TreeViewItem taskNode = new TreeViewItem();
                        taskNode.Header            = createNodeHeader("imgTask", Tsk.Name);
                        taskNode.MouseDoubleClick += new MouseButtonEventHandler(tree_NodeDoubleClick);
                        taskNode.Tag = Connect.SpiraProject.GenerateToString(evtObj.Project) + Connect.SpiraProject.CHAR_RECORD + "TK:" + Tsk.TaskId.ToString();

                        tskItemNode.Items.Add(taskNode);
                    }

                    tskNode.Items.Add(tskItemNode);

                    //Fire the next step.
                    if (evtObj.curSearchIsMine)
                    {
                        evtObj.curSearchIsMine = false;
                        RemoteFilter[] filters = this.GenerateFilter(-999, this.btnShowClosed.IsChecked.Value, "TK");
                        RemoteSort     sort    = this.GenerateSort();
                        client.Task_RetrieveAsync(filters, sort, 1, 9999999, evtObj);
                    }
                    else
                    {
                        evtObj.curSearchIsMine = true;
                        RemoteFilter[] filters = this.GenerateFilter(evtObj.Project.UserID, this.btnShowClosed.IsChecked.Value, "RQ");
                        RemoteSort     sort    = this.GenerateSort();
                        client.Requirement_RetrieveAsync(filters, 1, 9999999, evtObj);
                    }
                }
                else
                {
                    //Set error flag on node.
                    tskItemNode = changeNodeImage(tskItemNode, "imgError");
                    tskItemNode.Items.Clear();
                    tskItemNode.ToolTip = new TextBlock()
                    {
                        Text = evt.Error.Message
                    };

                    //Add it to our projectnode.
                    tskNode.Items.Add(tskItemNode);

                    //Error, clean up.
                    removeClient(client);
                }
            }
            catch (Exception ex)
            {
                Connect.logEventMessage("wpfProjectTree::client_FinishTask", ex, System.Diagnostics.EventLogEntryType.Error);
            }
        }
コード例 #4
0
        static void Main(string[] args)
        {
            _options = new Settings();
            if (Parser.Default.ParseArguments(args, _options))
            {
                //Make sure that the Spira string is a URL.
                Uri    serverUrl   = null;
                string servicePath = _options.SpiraServer +
                                     ((_options.SpiraServer.EndsWith("/") ? "" : "/")) +
                                     "Services/v5_0/SoapService.svc";
                if (!Uri.TryCreate(servicePath, UriKind.Absolute, out serverUrl))
                {
                    //Throw error: URL given not a URL.
                    return;
                }

                //See if we have a mappings file specified, if so, make sure it exists
                List <ArtifactMapping> artifactMappings = null;
                string customPropertyField = null;
                if (!String.IsNullOrWhiteSpace(_options.SpiraMappingsFile))
                {
                    if (!File.Exists(_options.SpiraMappingsFile))
                    {
                        //Throw error: Bad path.
                        ConsoleLog(LogLevelEnum.Normal, "Cannot access the mapping file, please check the location and try again!");
                        Environment.Exit(-1);
                    }
                    artifactMappings = new List <ArtifactMapping>();

                    //Read in the lines, the first column should contain:
                    //Filename,ArtifactTypeId,Custom_03
                    //where the number in the third column is the name of the custom property that the IDs will be using
                    using (StreamReader streamReader = File.OpenText(_options.SpiraMappingsFile))
                    {
                        string   firstLine = streamReader.ReadLine();
                        string[] headings  = firstLine.Split(',');

                        //See if we have a match on the custom property number
                        if (headings.Length > 2 && !String.IsNullOrWhiteSpace(headings[2]))
                        {
                            customPropertyField = headings[2].Trim();

                            //Now read in the rows of mappings
                            while (!streamReader.EndOfStream)
                            {
                                string          mappingLine     = streamReader.ReadLine();
                                ArtifactMapping artifactMapping = new ArtifactMapping();
                                string[]        components      = mappingLine.Split(',');
                                artifactMapping.Filename       = components[0];
                                artifactMapping.ArtifactTypeId = Int32.Parse(components[1]);
                                artifactMapping.ExternalKey    = components[2];
                                artifactMappings.Add(artifactMapping);
                            }
                            streamReader.Close();
                        }
                    }
                }

                //Make sure the path given is a real path..
                try
                {
                    Directory.GetCreationTime(_options.ImportPath);
                }
                catch
                {
                    //Throw error: Bad path.
                    ConsoleLog(LogLevelEnum.Normal, "Cannot access the import path, please check the location and try again!");
                    Environment.Exit(-1);
                }

                //Tell user we're operating.
                ConsoleLog(LogLevelEnum.Normal, "Importing files in " + _options.ImportPath);

                //Now run through connecting procedures.
                ConsoleLog(LogLevelEnum.Verbose, "Connecting to Spira server...");
                SoapServiceClient client = CreateClient_Spira5(serverUrl);
                client.Open();

                if (client.Connection_Authenticate2(_options.SpiraLogin, _options.SpiraPass, "DocumentImporter"))
                {
                    ConsoleLog(LogLevelEnum.Verbose, "Selecting Spira project...");
                    var           Projects = client.Project_Retrieve();
                    RemoteProject proj     = Projects.FirstOrDefault(p => p.ProjectId == _options.SpiraProject);

                    if (proj != null)
                    {
                        //Connect to the project.
                        if (client.Connection_ConnectToProject((int)_options.SpiraProject))
                        {
                            ConsoleLog(LogLevelEnum.Normal, "Uploading files...");

                            //Now let's get a list of all the files..
                            SearchOption  opt   = ((_options.PathRecursive) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                            List <string> files = Directory.EnumerateFiles(_options.ImportPath, _options.ImportFilter, opt).ToList();

                            //Loop through each file and upload it.
                            ConsoleLog(LogLevelEnum.Verbose, "Files:");
                            foreach (string file in files)
                            {
                                string conLog = Path.GetFileName(file);
                                try
                                {
                                    //Get the file details..
                                    FileInfo fileInf = new FileInfo(file);
                                    string   size    = "";
                                    if (fileInf.Length >= 1000000000)
                                    {
                                        size = (fileInf.Length / 1000000000).ToString() + "Gb";
                                    }
                                    else if (fileInf.Length >= 1000000)
                                    {
                                        size = (fileInf.Length / 1000000).ToString() + "Mb";
                                    }
                                    else if (fileInf.Length >= 1000)
                                    {
                                        size = (fileInf.Length / 1000).ToString() + "Kb";
                                    }
                                    else
                                    {
                                        size = fileInf.Length.ToString() + "b";
                                    }
                                    conLog += " (" + size + ")";

                                    //Generate the RemoteDocument object.
                                    RemoteDocument newFile = new RemoteDocument();
                                    newFile.AttachmentTypeId = 1;
                                    newFile.FilenameOrUrl    = Path.GetFileName(file);
                                    newFile.Size             = (int)fileInf.Length;
                                    newFile.UploadDate       = DateTime.UtcNow;

                                    //Now we see if have mapped artifact
                                    ArtifactMapping mappedArtifact = artifactMappings.FirstOrDefault(m => m.Filename.ToLowerInvariant() == newFile.FilenameOrUrl.ToLowerInvariant());
                                    if (mappedArtifact != null && !String.IsNullOrEmpty(customPropertyField))
                                    {
                                        //We have to lookup the artifact, currently only incidents are supported
                                        if (mappedArtifact.ArtifactTypeId == 3)
                                        {
                                            //Retrieve the incident
                                            RemoteSort sort = new RemoteSort();
                                            sort.PropertyName  = "IncidentId";
                                            sort.SortAscending = true;
                                            List <RemoteFilter> filters = new List <RemoteFilter>();
                                            RemoteFilter        filter  = new RemoteFilter();
                                            filter.PropertyName = customPropertyField;
                                            filter.StringValue  = mappedArtifact.ExternalKey;
                                            filters.Add(filter);
                                            RemoteIncident remoteIncident = client.Incident_Retrieve(filters, sort, 1, 1).FirstOrDefault();

                                            if (remoteIncident != null)
                                            {
                                                RemoteLinkedArtifact remoteLinkedArtifact = new SpiraService.RemoteLinkedArtifact();
                                                remoteLinkedArtifact.ArtifactTypeId = mappedArtifact.ArtifactTypeId;
                                                remoteLinkedArtifact.ArtifactId     = remoteIncident.IncidentId.Value;
                                                newFile.AttachedArtifacts           = new List <RemoteLinkedArtifact>();
                                                newFile.AttachedArtifacts.Add(remoteLinkedArtifact);
                                            }
                                        }
                                        else
                                        {
                                            ConsoleLog(LogLevelEnum.Normal, "Warning: Only incident mapped artifacts currently supported, so ignoring the mapped artifacts of type: " + mappedArtifact.ArtifactTypeId);
                                        }
                                    }

                                    //Read the file contents. (Into memory! Beware, large files!)
                                    byte[] fileContents = null;
                                    fileContents = File.ReadAllBytes(file);

                                    ConsoleLog(LogLevelEnum.Verbose, conLog);
                                    if (fileContents != null && fileContents.Length > 1)
                                    {
                                        newFile.AttachmentId = client.Document_AddFile(newFile, fileContents).AttachmentId.Value;
                                    }
                                    else
                                    {
                                        throw new FileEmptyException();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    conLog += " - Error. (" + ex.GetType().ToString() + ")";
                                    ConsoleLog(LogLevelEnum.Normal, conLog);
                                }
                            }
                        }
                        else
                        {
                            ConsoleLog(LogLevelEnum.Normal, "Cannot connect to project. Verify your Project Role.");
                            Environment.Exit(-1);
                        }
                    }
                    else
                    {
                        ConsoleLog(LogLevelEnum.Normal, "Cannot connect to project. Project #" + _options.SpiraProject.ToString() + " does not exist.");
                        Environment.Exit(-1);
                    }
                }
                else
                {
                    ConsoleLog(LogLevelEnum.Normal, "Cannot log in. Check username and password.");
                    Environment.Exit(-1);
                }
            }
            else
            {
                Environment.Exit(-1);
            }
        }
        /// <summary>Hit when the client is finished connecting and logging in.</summary>
        /// <param name="sender">The client that called it.</param>
        /// <param name="e">Event Args.</param>
        private void client_FinishConnecting(object sender, EventArgs e)
        {
            try
            {
                ImportExport client = (ImportExport)sender;
                string       eType  = e.GetType().ToString();
                eType = eType.Substring(eType.LastIndexOf('.') + 1);

                switch (eType)
                {
                case "Connection_Authenticate2CompletedEventArgs":
                {
                    //Connect finished.
                    Connection_Authenticate2CompletedEventArgs evt = (Connection_Authenticate2CompletedEventArgs)e;
                    ObjectState evtObj = (ObjectState)evt.UserState;
                    if (evt.Error == null)
                    {
                        client.System_GetProductVersionAsync(evtObj);
                    }
                    else
                    {
                        //Set error to node.
                        TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber];
                        this.trvProject.Items.RemoveAt(evtObj.NodeNumber);
                        this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError"));
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock()
                        {
                            Text = evt.Error.Message
                        };
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear();
                        //Error, clean up.
                        removeClient(client);
                    }
                }
                break;

                case "System_GetProductVersionCompletedEventArgs":
                {
                    //Connect finished.
                    System_GetProductVersionCompletedEventArgs evt = (System_GetProductVersionCompletedEventArgs)e;
                    ObjectState evtObj = (ObjectState)evt.UserState;
                    if (evt.Error == null)
                    {
                        evtObj.ClientVersion = evt.Result;
                        client.Connection_ConnectToProjectAsync(evtObj.Project.ProjectID, evtObj);
                    }
                    else
                    {
                        //Set error to node.
                        TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber];
                        this.trvProject.Items.RemoveAt(evtObj.NodeNumber);
                        this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError"));
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock()
                        {
                            Text = evt.Error.Message
                        };
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear();
                        //Error, clean up.
                        removeClient(client);
                    }
                }
                break;

                case "Connection_ConnectToProjectCompletedEventArgs":
                {
                    //Connect finished.
                    Connection_ConnectToProjectCompletedEventArgs evt = (Connection_ConnectToProjectCompletedEventArgs)e;
                    ObjectState evtObj = (ObjectState)evt.UserState;
                    if (evt.Error == null)
                    {
                        evtObj.curSearchIsMine = true;
                        RemoteFilter[] filters = GenerateFilter(evtObj.Project.UserID, this.btnShowClosed.IsChecked.Value, "IN");
                        RemoteSort     sort    = GenerateSort();
                        client.Incident_RetrieveAsync(filters, sort, 1, 9999999, evtObj);
                    }
                    else
                    {
                        //Set error to node.
                        TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber];
                        this.trvProject.Items.RemoveAt(evtObj.NodeNumber);
                        this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError"));
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock()
                        {
                            Text = evt.Error.Message
                        };
                        ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear();
                        //Error, clean up.
                        removeClient(client);
                    }
                }
                break;
                }
            }
            catch (Exception ex)
            {
                Connect.logEventMessage("wpfProjectTree::client_FinishConnecting", ex, System.Diagnostics.EventLogEntryType.Error);
            }
        }