public async Task Dispatch_Stream_Success()
        {
            using (MemoryStream payloadValue = new MemoryStream())
                using (StreamWriter writer = new StreamWriter(payloadValue))
                {
                    // arrange
                    ObjectAttachment attachment    = null;
                    AttachmentId     correlationId = AttachmentId.NewId();
                    string           payloadName   = "Name-919";

                    await writer.WriteAsync("Value-919");

                    await writer.FlushAsync();

                    // act
                    Action verify = () => attachment = AttachmentFactory
                                                       .Create <ObjectAttachment>(correlationId, payloadName, payloadValue);

                    // assert
                    Assert.Null(Record.Exception(verify));
                    Assert.NotNull(attachment);
                    Assert.IsType <ObjectAttachment>(attachment);
                    Assert.Equal("\"Value-919\"", Encoding.UTF8.GetString(attachment.Value));
                }
        }
Beispiel #2
0
 /// <summary>
 /// 转换为附件实体
 /// </summary>
 /// <param name="dto">附件数据传输对象</param>
 public static Attachment ToEntity3(this AttachmentDto dto)
 {
     if (dto == null)
     {
         return(new Attachment());
     }
     return(AttachmentFactory.Create(
                attachmentId: dto.Id.ToGuid(),
                fileName: dto.FileName,
                fileType: dto.FileType,
                size: dto.Size,
                remoteUrl: dto.RemoteUrl,
                localUrl: dto.LocalUrl,
                width: dto.Width,
                height: dto.Height,
                merchantId: dto.MerchantId,
                module: dto.Module,
                creationTime: dto.CreationTime,
                creatorId: dto.CreatorId,
                lastModificationTime: dto.LastModificationTime,
                lastModifierId: dto.LastModifierId,
                isDeleted: dto.IsDeleted,
                version: dto.Version
                ));
 }
Beispiel #3
0
        public async Task OneInitialAttachment_TwoAdded_ThreeAttachmentsInDraft()
        {
            //Arrange
            var initialAttachment = new List <Attachment> {
                AttachmentFactory.Create()
            };
            var addedAttachment = new List <FileData> {
                FileDataFactory.Create(), FileDataFactory.Create()
            };
            var initialSuspiciousEmployees = new List <EmployeeId> {
                this._suspiciousEmployee
            };

            var useCase =
                await this._testFixture.PrepareUseCaseWithTestData(this._applicant, initialSuspiciousEmployees,
                                                                   addedAttachment, null, initialAttachment);

            //Act
            var useCaseOutput =
                (UpdateDraftApplicationUseCaseOutputPort)await this._module.ExecuteUseCase(useCase);

            //Assert
            var draftApplicationFromContext = await this._testFixture.GetDraftFromContext(useCase.DraftApplicationId);

            Assert.AreEqual(OutputPortInvokedMethod.Standard, useCaseOutput.InvokedOutputMethod);
            Assert.AreEqual(3, draftApplicationFromContext.Attachments.Count);
        }
Beispiel #4
0
        public void OnResolverError(
            string message,
            HotChocolateRequest request,
            IEnumerable <HotChocolateError> errors)
        {
            if (IsEnabled())
            {
                AttachmentId attachmentId = AttachmentId.NewId();

                IAttachment requestAttachment = AttachmentFactory
                                                .Create <HotChocolateRequestAttachment, HotChocolateRequest>(
                    attachmentId, nameof(request), request);

                HotChocolateErrorsAttachment errorAttachments = AttachmentFactory
                                                                .Create <HotChocolateErrorsAttachment, IEnumerable <HotChocolateError> >(
                    attachmentId, nameof(errors), errors);

                AttachmentDispatcher.Instance.Dispatch(
                    errorAttachments, requestAttachment);

                OnResolverError(
                    Application.Id, ActivityStack.Id,
                    attachmentId, message);
            }
        }
Beispiel #5
0
 internal bool Add(Run therun)
 {
     try {
         StepFactory runstepF = therun.StepFactory as StepFactory;
         Step        thestep  = runstepF.AddItem(_stepName) as Step;
         thestep.Status            = _status;
         thestep["ST_ACTUAL"]      = _actual; //add actual field
         thestep["ST_DESCRIPTION"] = _Description;
         thestep["ST_EXPECTED"]    = _Expected;
         thestep.Post(); //add step
         if (File.Exists(_attachmentPath + "\\" + _attachmentName))
         {
             AttachmentFactory attachFact = thestep.Attachments as AttachmentFactory;
             Attachment        attachfile;
             IExtendedStorage  extStor;
             attachfile = attachFact.AddItem(_attachmentName) as Attachment;
             attachfile.Post();
             extStor            = attachfile.AttachmentStorage as IExtendedStorage;
             extStor.ClientPath = _attachmentPath;
             extStor.Save(_attachmentName, true);
         }
     } catch (Exception) {
         return(false);
     }
     return(true);
 }
Beispiel #6
0
        protected void changeSignText(object sender, EventArgs e)
        {
            Session.Remove("signTextFormat");
            Session.Remove("attachment");
            var signTextType = Request["signTextType"];

            if ("xml".Equals(signTextType))
            {
                Session.Add("signTextFormat", "xml");
            }
            else if ("txt".Equals(signTextType))
            {
                Session.Add("signTextFormat", "txt");
            }
            else if ("pdf".Equals(signTextType))
            {
                Session.Add("signTextFormat", "pdf");
                Session.Add("signTextUri", "/extras/attachment/sample.pdf?jsessionid=" + Session.SessionID);
            }
            else if ("pdf_w_attachment".Equals(signTextType))
            {
                Session.Add("signTextFormat", "pdf_w_attachment");
                Session.Add("signTextUri", "/extras/attachment/sample.pdf?jsessionid=" + Session.SessionID);
                Attachment attachment = new AttachmentFactory("SHA256").Create("GIF-dokument-til-bilag.gif", "/extras/attachment/GIF-dokument-til-bilag.gif", "extras.attachment.GIF-dokument-til-bilag.gif", "image/gif", true);
                Session.Add("attachment", attachment);
            }
            else
            {
                Session.Add("signTextFormat", "html");
            }
            Response.Redirect("/extras/");
        }
Beispiel #7
0
        private Attachment getAttachment(XmlNode fromPost)
        {
            if (fromPost != null)
            {
                Attachment attachment     = new Attachment();
                string     attachmentType = fromPost.SelectSingleNode("type").InnerText;
                switch (attachmentType)
                {
                case "app": attachment.Type = AttachmentType.Application; break;

                case "graffiti": attachment.Type = AttachmentType.Graffiti; break;

                case "video": attachment.Type = AttachmentType.Video; break;

                case "audio": attachment.Type = AttachmentType.Audio; break;

                case "photo": attachment.Type = AttachmentType.Photo; break;

                case "posted_photo": attachment.Type = AttachmentType.PostedPhoto; break;

                case "note": attachment.Type = AttachmentType.Note; break;

                case "poll": attachment.Type = AttachmentType.Poll; break;

                case "link": attachment.Type = AttachmentType.Url; break;

                case "checkin": attachment.Type = AttachmentType.Checkin; break;

                case "share": attachment.Type = AttachmentType.Share; break;
                }
                XmlNode attachmentData = fromPost.SelectSingleNode(attachmentType);
                if (attachmentData != null)
                {
                    attachment.Data = AttachmentFactory.GetAttachment(attachment.Type, attachmentData);
                }
                else
                {
                    attachment.Data = null;
                }
                //attachment.ItemId = Convert.ToInt32(fromPost.SelectSingleNode("item_id").InnerText);
                //if (attachment.Type != AttachmentType.Graffiti)
                //{
                //    attachment.OwnerId = Convert.ToInt32(fromPost.SelectSingleNode("owner_id").InnerText);
                //}
                //if (attachment.Type == AttachmentType.Application)
                //{
                //    attachment.ApplicationId = Convert.ToInt32(fromPost.SelectSingleNode("app_id").InnerText);
                //}
                //if (fromPost.SelectSingleNode("thumb_src") != null)
                //{
                //    attachment.ThumbnailUrl = fromPost.SelectSingleNode("thumb_src").InnerText;
                //}
                return(attachment);
            }
            return(null);
        }
Beispiel #8
0
        /// <summary>
        /// Exports a <see cref="NonBehaviourDependency"/> for the network client.
        /// Enabling it for scene persistence.
        /// </summary>
        public void ExportmanagedClient()
        {
            GameObject exportClientObject = new GameObject(@"[ExportedNetClient]");

            AttachmentFactory
            .AddTo <ExportedClientDependencyRegisterModule>(exportClientObject);

            //We don't want this client to be destroyed
            DontDestroyOnLoad(exportClientObject);
            isClientExported = true;
        }
        public void InternalServerErrorOccurred(Exception exception)
        {
            if (IsEnabled())
            {
                AttachmentId        attachmentId = AttachmentId.NewId();
                ExceptionAttachment attachment   = AttachmentFactory.Create(attachmentId,
                                                                            nameof(exception), exception);

                AttachmentDispatcher.Instance.Dispatch(attachment);
                InternalServerErrorOccurred(Application.Id, ActivityStack.Id, attachmentId);
            }
        }
Beispiel #10
0
        /// <summary>
        /// This method will download an attachment from a folder in Quality Center
        /// </summary>
        /// <param name="qcFolderLocation">Folder Location from where attachment needs to be downloaded</param>
        /// <param name="strFileName">Name of the file that needs to be downloaded from specified location.
        /// Name should be specified along with extenstion </param>
        /// <returns>Location of local (usually temp) path where file has been downloaded. Returns empty string if file could not be downloaded.</returns>
        public string DownloadAttachment(string qcFolderLocation, string strFileName)
        {
            //Connect with Quality Center
            TDConnection qctd = new TDConnection();

            qctd.InitConnectionEx(qcServer);
            qctd.ConnectProjectEx(strDomainName, strProjectName, strQCUserName, strQCUserPassword);

            if (qctd.Connected)
            {
                //Define objects that will be used to download files
                SubjectNode       otaSysTreeNode       = new SubjectNode();
                AttachmentFactory otaAttachmentFactory = new AttachmentFactory();
                TDFilter          otaAttachmentFilter  = new TDFilter();
                List            otaAttachmentList      = new List();
                ExtendedStorage attStorage             = new ExtendedStorage();

                otaSysTreeNode       = qctd.TreeManager.NodeByPath(qcFolderLocation); //Returns node object from test plan in Quality Center
                otaAttachmentFactory = otaSysTreeNode.Attachments();                  //Returns all attachments for the folder in QC
                otaAttachmentFilter  = otaAttachmentFactory.Filter();                 //Can be used to filter list of attachments
                otaAttachmentList    = otaAttachmentFilter.NewList();                 //Creates list of attached files

                //Check if there is any attachment available for the specified folder
                if (otaAttachmentList.Count > 0)
                {
                    foreach (Attachment otaAttachment in otaAttachmentList)
                    {
                        //Check if file names are same
                        if (otaAttachment.FileName.ToLower() == strFileName.ToLower())
                        {
                            attStorage         = otaAttachment.AttachmentStorage();
                            _localFileLocation = otaAttachment.DirectLink;

                            //Load method will download file to local workstation. true to used for synchronised download.
                            attStorage.Load(_localFileLocation, true);

                            //Client path refers to local path where file has been downloaded
                            _localFileLocation = attStorage.ClientPath;
                            break;
                        }
                    }
                }
            }

            //Return empty string if connection to QC was not successfull.
            else
            {
                _localFileLocation = string.Empty;
            }

            return(_localFileLocation);
        }
Beispiel #11
0
        public async Task <MemoryAttachment?> DownloadAttachment(InAttachment inAttachment)
        {
            var file = await _api.GetFileAsync(inAttachment.Id).ConfigureAwait(false);

            var url      = $"https://api.telegram.org/file/bot{_options.Token}/{file.FilePath}";
            var response = await _client.GetByteArrayAsync(url).ConfigureAwait(false);

            // Todo Refactor this.
            int index    = file.FilePath.LastIndexOf('/');
            var fullName = file.FilePath.Substring(index + 1);

            return(AttachmentFactory.CreateMemoryAttachment(fullName, response, inAttachment.Type));
        }
Beispiel #12
0
        public void Start(Guid activityId, HotChocolateRequest request)
        {
            if (IsEnabled())
            {
                AttachmentId attachmentId = AttachmentId.NewId();
                IAttachment  attachment   = AttachmentFactory
                                            .Create <HotChocolateRequestAttachment, HotChocolateRequest>(
                    attachmentId, nameof(request), request);

                AttachmentDispatcher.Instance.Dispatch(attachment);
                Start(Application.Id, activityId, attachmentId);
            }
        }
        public void RetrieveObjectInfo(int id, RequestInformation info)
        {
            if (IsEnabled())
            {
                var attachmentId = AttachmentId.NewId();

                RetrieveObjectInfo(Application.Id, ActivityStack.Id, attachmentId, id);

                AttachmentDispatcher.Instance.Dispatch(
                    AttachmentFactory.Create(attachmentId, "info", info)
                    );
            }
        }
Beispiel #14
0
        /// <summary>
        /// This method will download an attachment from a folder in Quality Center
        /// </summary>
        /// <param name="qcFolderLocation">Folder Location from where attachment needs to be downloaded</param>
        /// <param name="strFileName">Name of the file that needs to be downloaded from specified location. 
        /// Name should be specified along with extenstion </param>
        /// <returns>Location of local (usually temp) path where file has been downloaded. Returns empty string if file could not be downloaded.</returns>
        public string DownloadAttachment(string qcFolderLocation, string strFileName)
        {
            //Connect with Quality Center
            TDConnection qctd = new TDConnection();
            qctd.InitConnectionEx(qcServer);
            qctd.ConnectProjectEx(strDomainName, strProjectName, strQCUserName, strQCUserPassword);

            if (qctd.Connected)
            {
                //Define objects that will be used to download files
                SubjectNode otaSysTreeNode = new SubjectNode();
                AttachmentFactory otaAttachmentFactory = new AttachmentFactory();
                TDFilter otaAttachmentFilter = new TDFilter();
                List otaAttachmentList = new List();
                ExtendedStorage attStorage = new ExtendedStorage();

                otaSysTreeNode = qctd.TreeManager.NodeByPath(qcFolderLocation);     //Returns node object from test plan in Quality Center
                otaAttachmentFactory = otaSysTreeNode.Attachments();                //Returns all attachments for the folder in QC
                otaAttachmentFilter = otaAttachmentFactory.Filter();                //Can be used to filter list of attachments
                otaAttachmentList = otaAttachmentFilter.NewList();                  //Creates list of attached files

                //Check if there is any attachment available for the specified folder
                if (otaAttachmentList.Count > 0)
                {
                    foreach (Attachment otaAttachment in otaAttachmentList)
                    {
                        //Check if file names are same
                        if (otaAttachment.FileName.ToLower() == strFileName.ToLower())
                        {
                            attStorage = otaAttachment.AttachmentStorage();
                            _localFileLocation = otaAttachment.DirectLink;

                            //Load method will download file to local workstation. true to used for synchronised download.
                            attStorage.Load(_localFileLocation, true);

                            //Client path refers to local path where file has been downloaded
                            _localFileLocation = attStorage.ClientPath;
                            break;
                        }
                    }
                }
            }

            //Return empty string if connection to QC was not successfull.
            else
            {
                _localFileLocation = string.Empty;
            }

            return _localFileLocation;
        }
        /// <summary>
        /// Exports a <see cref="NonBehaviourDependency"/> for the network client.
        /// Enabling it for scene persistence.
        /// </summary>
        public void ExportmanagedClient()
        {
            //We should cancel the networking
            //since we're going to export this.
            CancelTokenSource.Cancel();

            GameObject exportClientObject = new GameObject(@"[ExportedNetClient]");

            AttachmentFactory
            .AddTo <ExportedClientDependencyRegisterModule>(exportClientObject);

            //We don't want this client to be destroyed
            DontDestroyOnLoad(exportClientObject);
            isClientExported = true;
        }
        public void Dispatch_Stream_PayloadValueNull()
        {
            // arrange
            ObjectAttachment attachment    = null;
            AttachmentId     correlationId = AttachmentId.NewId();
            string           payloadName   = "Name-881";
            Stream           payloadValue  = null;

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create <ObjectAttachment>(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.Null(attachment);
        }
        public void Dispatch_Exception_PayloadValueNull()
        {
            // arrange
            ExceptionAttachment attachment    = null;
            AttachmentId        correlationId = AttachmentId.NewId();
            string    payloadName             = "Name-567";
            Exception payloadValue            = null;

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.Null(attachment);
        }
        public void Create_Exception_PayloadNameNull()
        {
            // arrange
            ExceptionAttachment attachment    = null;
            AttachmentId        correlationId = AttachmentId.NewId();
            string    payloadName             = null;
            Exception payloadValue            = new ArgumentNullException("Value-426");

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.Null(attachment);
        }
        public void Create_Object_CorrelationIdNull()
        {
            // arrange
            ObjectAttachment attachment    = null;
            AttachmentId     correlationId = AttachmentId.Empty;
            string           payloadName   = "Name-627";
            object           payloadValue  = "Value-627";

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.Null(attachment);
        }
Beispiel #20
0
        public void OnQueryError(Exception exception)
        {
            if (IsEnabled())
            {
                AttachmentId attachmentId = AttachmentId.NewId();

                ExceptionAttachment attachment = AttachmentFactory
                                                 .Create(attachmentId, nameof(exception), exception);

                AttachmentDispatcher.Instance.Dispatch(attachment);

                OnQueryError(
                    Application.Id, ActivityStack.Id,
                    attachmentId, exception.Message);
            }
        }
        public void Dispatch_Object_Success()
        {
            // arrange
            ObjectAttachment attachment    = null;
            AttachmentId     correlationId = AttachmentId.NewId();
            string           payloadName   = "Name-123";
            object           payloadValue  = "Value-123";

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.NotNull(attachment);
            Assert.IsType <ObjectAttachment>(attachment);
        }
        public void Dispatch_Exception_Success()
        {
            // arrange
            ExceptionAttachment attachment    = null;
            AttachmentId        correlationId = AttachmentId.NewId();
            string    payloadName             = "Name-848";
            Exception payloadValue            = new ArgumentNullException("Value-848");

            // act
            Action verify = () => attachment = AttachmentFactory
                                               .Create(correlationId, payloadName, payloadValue);

            // assert
            Assert.Null(Record.Exception(verify));
            Assert.NotNull(attachment);
            Assert.IsType <ExceptionAttachment>(attachment);
        }
Beispiel #23
0
        public override IEnumerable <IssueTrackerEvent> parseIssueTrackerEvents()
        {
            // First get the patch uploads
            IEnumerable <BugzillaAttachmentInfo> attachmentList = (IEnumerable <BugzillaAttachmentInfo>)AttachmentFactory.parseIssueTrackerEvents();

            // Lookup table to add file names to BugzillaReviews
            Dictionary <UInt64, IList <string> > dictAttachments = attachmentList.ToDictionary(bai => bai.AttachmentId, bai => bai.Filenames);

            // Second, get reviews
            IEnumerable <BugzillaReview> reviewList = GetActivityInfoFromFile(InputFilePath, dictAttachments);

            HashSet <int> setOfAllUsedBugIds = new HashSet <int>(reviewList.Select(review => review.BugId));

            AttachmentFactory.IncludeAttachmentsFilter = (attachment) => setOfAllUsedBugIds.Contains(attachment.BugId);
            attachmentList = (IEnumerable <BugzillaAttachmentInfo>)AttachmentFactory.parseIssueTrackerEvents();  // re-read the list

            return(MergeUtils.Merge <IssueTrackerEvent>(attachmentList, reviewList, (patch, review) => patch.When <= review.When));
        }
        /// <summary>
        /// Dispatches an <see cref="HttpRequest"/>.
        /// </summary>
        /// <param name="dispatcher">A dispatcher instance.</param>
        /// <param name="id">A correlation id.</param>
        /// <param name="payloadName">A payload name.</param>
        /// <param name="payloadValue">A HTTP request.</param>
        /// <remarks>This method may not break because it is called from EventSources.</remarks>
        public static void Dispatch(this AttachmentDispatcher dispatcher, AttachmentId id,
                                    string payloadName, HttpRequest payloadValue)
        {
            if (dispatcher != null && id != AttachmentId.Empty &&
                !string.IsNullOrWhiteSpace(payloadName) && payloadValue != null)
            {
                HttpRequestAttachment request = AttachmentFactory
                                                .Create <HttpRequestAttachment, HttpRequest>(id, payloadName, payloadValue);

                dispatcher.Dispatch(request);

                if (payloadValue.Body != null && payloadValue.Body.Length > 0)
                {
                    HttpRequestBodyAttachment requestBody = AttachmentFactory
                                                            .Create <HttpRequestBodyAttachment>(id, payloadName,
                                                                                                payloadValue.Body);

                    dispatcher.Dispatch(requestBody);
                }
            }
        }
        /// <summary>
        /// Dispatches an <see cref="HttpResponse"/>.
        /// </summary>
        /// <param name="dispatcher">A dispatcher instance.</param>
        /// <param name="id">A correlation id.</param>
        /// <param name="payloadName">A payload name.</param>
        /// <param name="payloadValue">A HTTP response.</param>
        /// <remarks>This method may not break because it is called from EventSources.</remarks>
        public static void Dispatch(this AttachmentDispatcher dispatcher, AttachmentId id,
                                    string payloadName, HttpResponse payloadValue)
        {
            if (dispatcher != null && id != AttachmentId.Empty &&
                !string.IsNullOrWhiteSpace(payloadName) && payloadValue != null)
            {
                HttpResponseAttachment response = AttachmentFactory
                                                  .Create <HttpResponseAttachment, HttpResponse>(id, payloadName, payloadValue);

                dispatcher.Dispatch(response);

#pragma warning disable S125 // Sections of code should not be "commented out"
                //if (payloadValue.Body != null && payloadValue.Body.Length > 0)
                //{
                //    HttpResponseBodyAttachment responseBody = AttachmentFactory
                //        .Create<HttpResponseBodyAttachment>(id, payloadName,
                //            payloadValue.Body);
                //
                //    dispatcher.Dispatch(responseBody);
                //}
#pragma warning disable S125 // Sections of code should not be "commented out"
            }
        }
        public async Task Create_Stream_PayloadNameNull()
        {
            using (MemoryStream payloadValue = new MemoryStream())
                using (StreamWriter writer = new StreamWriter(payloadValue))
                {
                    // arrange
                    ObjectAttachment attachment    = null;
                    AttachmentId     correlationId = AttachmentId.NewId();
                    string           payloadName   = null;

                    await writer.WriteAsync("Value-444");

                    await writer.FlushAsync();

                    // act
                    Action verify = () => attachment = AttachmentFactory
                                                       .Create <ObjectAttachment>(correlationId, payloadName, payloadValue);

                    // assert
                    Assert.Null(Record.Exception(verify));
                    Assert.Null(attachment);
                }
        }
        /// <summary>
        /// Works when file path is on the desktop / c drive, but not on other drives....
        /// </summary>
        /// <param name="description"> Description of the attached file.</param>
        /// <param name="filePath"> Filepath to the file.</param>
        /// <returns>The server file name for the attachment.</returns>
        public string AddAttachment(string description, string filePath)
        {
            try
            {
                AttachmentFactory attachmentFactory = this.TestRun.Attachments as AttachmentFactory;
                attachmentFactory.NewList(string.Empty);
                Attachment attachment = attachmentFactory.AddItem(DBNull.Value) as Attachment;
                attachment.Description = description;
                attachment.Type        = 1;
                attachment.FileName    = filePath;
                attachment.Post();
                attachment.Refresh();
                attachment.Save(false);

                // We set that this test case instance has an attachment.
                this.HasAttachment = true;
                return(attachment.ServerFileName);
            }
            catch (Exception e)
            {
                e.ToString();
                throw new CannotAddTestCaseAttachment(CannotAddTestCaseAttachment.ErrorMsg + $"({this.Name}) - {description} and {filePath}");
            }
        }
Beispiel #28
0
        public static bool ExportExecutionDetailsToQC(BusinessFlow bizFlow, ref string result, PublishToALMConfig publishToALMConfig = null)
        {
            result = string.Empty;
            if (bizFlow.ExternalID == "0" || String.IsNullOrEmpty(bizFlow.ExternalID))
            {
                result = GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + bizFlow.Name + " is missing ExternalID, cannot locate QC TestSet without External ID";
                return(false);
            }

            try
            {
                //get the BF matching test set
                TestSet testSet = ImportFromQC.GetQCTestSet(bizFlow.ExternalID);//bf.externalID holds the TestSet TSTests collection id
                if (testSet != null)
                {
                    //get the Test set TC's
                    List <TSTest> qcTSTests = ImportFromQC.GetTSTestsList(testSet); //list of TSTest's on main TestSet in TestLab

                    //get all BF Activities groups
                    ObservableList <ActivitiesGroup> activGroups = bizFlow.ActivitiesGroups;
                    if (activGroups.Count > 0)
                    {
                        foreach (ActivitiesGroup activGroup in activGroups)
                        {
                            if ((publishToALMConfig.FilterStatus == FilterByStatus.OnlyPassed && activGroup.RunStatus == eActivitiesGroupRunStatus.Passed) ||
                                (publishToALMConfig.FilterStatus == FilterByStatus.OnlyFailed && activGroup.RunStatus == eActivitiesGroupRunStatus.Failed) ||
                                publishToALMConfig.FilterStatus == FilterByStatus.All)
                            {
                                TSTest tsTest = null;
                                //go by TC ID = TC Instance ID
                                tsTest = qcTSTests.Where(x => x.TestId == activGroup.ExternalID && x.ID == activGroup.ExternalID2).FirstOrDefault();
                                if (tsTest == null)
                                {
                                    //go by Linked TC ID + TC Instance ID
                                    tsTest = qcTSTests.Where(x => ImportFromQC.GetTSTestLinkedID(x) == activGroup.ExternalID && x.ID == activGroup.ExternalID2).FirstOrDefault();
                                }
                                if (tsTest == null)
                                {
                                    //go by TC ID
                                    tsTest = qcTSTests.Where(x => x.TestId == activGroup.ExternalID).FirstOrDefault();
                                }
                                if (tsTest != null)
                                {
                                    //get activities in group
                                    List <Activity> activities   = (bizFlow.Activities.Where(x => x.ActivitiesGroupID == activGroup.Name)).Select(a => a).ToList();
                                    string          TestCaseName = PathHelper.CleanInValidPathChars(tsTest.TestName);
                                    if ((publishToALMConfig.VariableForTCRunName == null) || (publishToALMConfig.VariableForTCRunName == string.Empty))
                                    {
                                        String timeStamp = DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");
                                        publishToALMConfig.VariableForTCRunName = "GingerRun_" + timeStamp;
                                    }

                                    RunFactory runFactory = (RunFactory)tsTest.RunFactory;
                                    Run        run        = (Run)runFactory.AddItem(publishToALMConfig.VariableForTCRunNameCalculated);

                                    // Attach ActivityGroup Report if needed
                                    if (publishToALMConfig.ToAttachActivitiesGroupReport)
                                    {
                                        if ((activGroup.TempReportFolder != null) && (activGroup.TempReportFolder != string.Empty) &&
                                            (System.IO.Directory.Exists(activGroup.TempReportFolder)))
                                        {
                                            //Creating the Zip file - start
                                            string targetZipPath = System.IO.Directory.GetParent(activGroup.TempReportFolder).ToString();
                                            string zipFileName   = targetZipPath + "\\" + TestCaseName.ToString() + "_GingerHTMLReport.zip";

                                            if (!System.IO.File.Exists(zipFileName))
                                            {
                                                ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName);
                                            }
                                            else
                                            {
                                                System.IO.File.Delete(zipFileName);
                                                ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName);
                                            }
                                            System.IO.Directory.Delete(activGroup.TempReportFolder, true);
                                            //Creating the Zip file - finish
                                            //Attaching Zip file - start
                                            AttachmentFactory      attachmentFactory = (AttachmentFactory)run.Attachments;
                                            TDAPIOLELib.Attachment attachment        = (TDAPIOLELib.Attachment)attachmentFactory.AddItem(System.DBNull.Value);
                                            attachment.Description = "TC Ginger Execution HTML Report";
                                            attachment.Type        = 1;
                                            attachment.FileName    = zipFileName;
                                            attachment.Post();

                                            //Attaching Zip file - finish
                                            System.IO.File.Delete(zipFileName);
                                        }
                                    }


                                    //create run with activities as steps
                                    run.CopyDesignSteps();
                                    run.Post();
                                    StepFactory stepF     = run.StepFactory;
                                    List        stepsList = stepF.NewList("");

                                    //int i = 0;
                                    int index = 1;
                                    foreach (Step step in stepsList)
                                    {
                                        //search for matching activity based on ID and not order, un matching steps need to be left as No Run
                                        int      stepDesignID     = (stepsList[index]).Field("ST_DESSTEP_ID");
                                        Activity matchingActivity = activities.Where(x => x.ExternalID == stepDesignID.ToString()).FirstOrDefault();
                                        if (matchingActivity != null)
                                        {
                                            switch (matchingActivity.Status)
                                            {
                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed:
                                                step.Status = "Failed";
                                                List <IAct> failedActs = matchingActivity.Acts.Where(x => x.Status == Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed).ToList();
                                                string      errors     = string.Empty;
                                                foreach (Act act in failedActs)
                                                {
                                                    errors += act.Error + Environment.NewLine;
                                                }
                                                step["ST_ACTUAL"] = errors;
                                                break;

                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.NA:
                                                step.Status       = "N/A";
                                                step["ST_ACTUAL"] = "NA";
                                                break;

                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Passed:
                                                step.Status       = "Passed";
                                                step["ST_ACTUAL"] = "Passed as expected";
                                                break;

                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped:
                                                //step.Status = "No Run";
                                                step.Status       = "N/A";
                                                step["ST_ACTUAL"] = "Skipped";
                                                break;

                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Pending:
                                                step.Status       = "No Run";
                                                step["ST_ACTUAL"] = "Was not executed";
                                                break;

                                            case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Running:
                                                step.Status       = "Not Completed";
                                                step["ST_ACTUAL"] = "Not Completed";
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            //Step not exist in Ginger so left as "No Run" unless it is step data
                                            if (step.Name.ToUpper() == "STEP DATA")
                                            {
                                                step.Status = "Passed";
                                            }
                                            else
                                            {
                                                step.Status = "No Run";
                                            }
                                        }
                                        step.Post();
                                        index++;
                                    }

                                    //get all execution status for all steps
                                    ObservableList <string> stepsStatuses = new ObservableList <string>();
                                    foreach (Step step in stepsList)
                                    {
                                        stepsStatuses.Add(step.Status);
                                    }

                                    //update the TC general status based on the activities status collection.
                                    if (stepsStatuses.Where(x => x == "Failed").Count() > 0)
                                    {
                                        run.Status = "Failed";
                                    }
                                    else if (stepsStatuses.Where(x => x == "No Run").Count() == stepsList.Count || stepsStatuses.Where(x => x == "N/A").Count() == stepsList.Count)
                                    {
                                        run.Status = "No Run";
                                    }
                                    else if (stepsStatuses.Where(x => x == "Passed").Count() == stepsList.Count || (stepsStatuses.Where(x => x == "Passed").Count() + stepsStatuses.Where(x => x == "N/A").Count()) == stepsList.Count)
                                    {
                                        run.Status = "Passed";
                                    }
                                    else
                                    {
                                        run.Status = "Not Completed";
                                    }
                                    run.Post();
                                }
                                else
                                {
                                    //No matching TC was found for the ActivitiesGroup in QC
                                    result = "Matching TC's were not found for all " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroups) + " in QC/ALM.";
                                }
                            }
                        }
                    }
                    else
                    {
                        //No matching Test Set was found for the BF in QC
                        result = "No matching Test Set was found in QC/ALM.";
                    }
                }
                if (result == string.Empty)
                {
                    result = "Export performed successfully.";
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                result = "Unexpected error occurred- " + ex.Message;
                Reporter.ToLog(eLogLevel.ERROR, "Failed to export execution details to QC/ALM", ex);
                //if (!silentMode)
                //    Reporter.ToUser(eUserMsgKey.ErrorWhileExportingExecDetails, ex.Message);
                return(false);
            }
        }
Beispiel #29
0
        private void Serializer_ImageSaved(object sender, ImageSavedEventArgs e)
        {
            Processor processor = new Processor();

            processor.Send(this.Recipient, this.Subject, this.EmailBody, AttachmentFactory.GetAttachments(e.ImagePath));
        }
Beispiel #30
0
        private static void ExportRequirements()
        {
            string server_url = ConfigurationManager.AppSettings["SERVER_URL"];
            string username   = ConfigurationManager.AppSettings["USER_NAME"];
            string password   = ConfigurationManager.AppSettings["PASSWORD"];
            string domain     = ConfigurationManager.AppSettings["DOMAIN"];
            string project    = ConfigurationManager.AppSettings["PROJECT"];

            string req_file = ConfigurationManager.AppSettings["REQUIREMENTS_FILE"];
            string att_file = ConfigurationManager.AppSettings["ATTACHMENTS_FILE"];
            string att_path = ConfigurationManager.AppSettings["ATTACHMENTS_PATH"];

            if (!Directory.Exists(att_path))
            {
                Directory.CreateDirectory(att_path);
            }

            TDConnection tdc = new TDConnection();

            tdc.InitConnectionEx(server_url);
            tdc.ConnectProjectEx(domain, project, username, password);

            Console.WriteLine("Connected to QC Server");

            ReqFactory req_factory = (ReqFactory)tdc.ReqFactory;
            TDFilter   req_filter  = (TDFilter)req_factory.Filter;


            /**
             *  Set your own filters for requirements below
             */

            // req_filter["RQ_REQ_PATH"] = "AAAAAGAAE*";


            StreamWriter rfs = new StreamWriter(File.Open(req_file, FileMode.Create),
                                                Encoding.Default,
                                                1024);

            StreamWriter afs = new StreamWriter(File.Open(att_file, FileMode.Create),
                                                Encoding.Default,
                                                1024);

            foreach (Req r in req_filter.NewList())
            {
                string name = r.Name.Replace("\"", "").Replace("\t", "").Trim();

                Console.WriteLine("Req \"{0}\"", name);

                rfs.WriteLine(String.Join("\t", new String[] {
                    r.ID.ToString(),
                    r.ParentId.ToString(),
                    r["RQ_REQ_PATH"],
                    name,
                    r["RQ_VTS"].ToString()
                }));

                if (!r.HasAttachment)
                {
                    continue;
                }

                AttachmentFactory att_factory = r.Attachments;

                foreach (Attachment a in att_factory.NewList(""))
                {
                    Console.WriteLine("Attachment \"{0}\"", a.Name);

                    afs.WriteLine(String.Join("\t", new String[] {
                        r.ID.ToString(),
                        a.ID.ToString(),
                        a.Name,
                        a.FileSize.ToString(),
                        a.LastModified.ToShortDateString()
                    }));

                    IExtendedStorage storage = a.AttachmentStorage;
                    storage.ClientPath = Path.GetFullPath(att_path) + "\\";
                    storage.Load(a.Name, true);
                }
            }

            rfs.Close();
            afs.Close();

            tdc.Disconnect();
            tdc.Logout();

            Console.WriteLine("Disconnected.");
        }
        public bool Attach(
            int TestSetId,
            AttachmentType Type,
            string Path,
            string Description = default(string),
            string Name        = default(string))
        {
            bool success = false;

            try
            {
                if (!Connect(ServerUrl, Username, Password, Domain, Project))
                {
                    return(false);
                }

                TestSetFactory tsFact   = tdc.TestSetFactory;
                TestSet        tSet     = tsFact[TestSetId];
                string         tSetName = tSet.Name; //Strange ALM bug allows you to select a non existant tet set. Calling name ensures it exists

                AttachmentFactory attachFact = tSet.Attachments;
                Attachment        attach     = attachFact.AddItem(DBNull.Value);
                attach.FileName = Path;

                TDAPI_ATTACH_TYPE attachType = TDAPI_ATTACH_TYPE.TDATT_FILE;

                switch (Type)
                {
                case AttachmentType.File:
                case AttachmentType.file:
                    attachType = TDAPI_ATTACH_TYPE.TDATT_FILE;
                    break;

                case AttachmentType.URL:
                case AttachmentType.url:
                case AttachmentType.Url:
                    attachType = TDAPI_ATTACH_TYPE.TDATT_INTERNET;
                    break;
                }

                attach.Type = (int)attachType;

                if (Description != default(string))
                {
                    attach.Description = Description;
                }

                //Post will fail if attachment path is bad
                attach.Post();

                if ((Name != default(string)) && (attachType == TDAPI_ATTACH_TYPE.TDATT_FILE))
                {
                    attach.Rename(Name);
                    attach.Post();
                }
                success = true;
            }
            catch (COMException ce)
            {
                //If we get an error, delete the attachment
                //If the file path is invalid and the attachment never uploads, ALM throws an error but posts the attachment anyways
                //returning no attachment object. So the only way to detect this is to look for 0 sized attachments and delete them
                TestSetFactory    tsFact     = tdc.TestSetFactory;
                TestSet           tSet       = tsFact[TestSetId];
                AttachmentFactory attachFact = tSet.Attachments;
                List attachList = attachFact.NewList("");
                foreach (Attachment a in attachList)
                {
                    if (a.FileSizeEx == 0)
                    {
                        attachFact.RemoveItem(a.ID);
                    }
                }
                rr.AddErrorLine(HandleException(ce));
            }
            finally { Disconnect(); }

            return(success);
        }