Example #1
0
        protected Study CreateTestStudy1()
        {
            var studyUid = "1.2.3";
            var sops = base.SetupMRSeries(4, 5, studyUid);
            var xml = new StudyXml(studyUid);

            var seriesUids = new Dictionary<string, string>();
            var seriesModalities = new Dictionary<string, string>();
            var modalities = new[] { "MR", "MR", "SC", "KO" };

            foreach (var sop in sops)
            {
                //Make the UIDs constant.
                var seriesUid = sop[DicomTags.SeriesInstanceUid].ToString();
                if (!seriesUids.ContainsKey(seriesUid))
                {
                    seriesModalities[seriesUid] = modalities[seriesUids.Count];
                    seriesUids[seriesUid] = string.Format("1.2.3.{0}", seriesUids.Count + 1);
                }

                var modality = seriesModalities[seriesUid];
                seriesUid = seriesUids[seriesUid];

                sop[DicomTags.SeriesInstanceUid].SetString(0, seriesUid);
                sop[DicomTags.Modality].SetString(0, modality);

                var file = new DicomFile("", new DicomAttributeCollection(), sop);
                xml.AddFile(file);
            }

            var study = new Study();
            study.Update(xml);
            return study;
        }
Example #2
0
		private static Study NewStudy()
		{
			Study study = new Study();
			study.StudyInstanceUid = "123";
			study.AccessionNumber = "abc";
			return study;
		}
			public void Validate(DicomFile dicomFile)
			{
				DicomAttributeCollection sopInstanceDataset = dicomFile.DataSet;
				DicomAttributeCollection metaInfo = dicomFile.MetaInfo;

				DicomAttribute attribute = metaInfo[DicomTags.MediaStorageSopClassUid];
				// we want to skip Media Storage Directory Storage (DICOMDIR directories)
				if ("1.2.840.10008.1.3.10" == attribute.ToString())
					throw new DataStoreException("Cannot process dicom directory files.");

				DicomValidator.ValidateStudyInstanceUID(sopInstanceDataset[DicomTags.StudyInstanceUid]);
				DicomValidator.ValidateSeriesInstanceUID(sopInstanceDataset[DicomTags.SeriesInstanceUid]);
				DicomValidator.ValidateSOPInstanceUID(sopInstanceDataset[DicomTags.SopInstanceUid]);
				DicomValidator.ValidateTransferSyntaxUID(metaInfo[DicomTags.TransferSyntaxUid]);
				
				if (dicomFile.SopClass == null)
					throw new DataStoreException("The sop class must not be empty.");

				DicomValidator.ValidateSopClassUid(dicomFile.SopClass.Uid);

				Study study = new Study();
				study.Initialize(dicomFile);

				_validator.ValidatePersistentObject(study);
			}
 /// <summary>
 /// Shows only the quuestions and answers for the current study being viewed
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnShowThisStudy_Click(object sender, EventArgs e)
 {
     Study study = new Study(Convert.ToInt32(Request.QueryString["study_id"]));
     Participant participant = new Participant(Convert.ToInt32(Request.QueryString["participant_id"]));
     pnlQualifiers.Controls.Clear();
     showStudyInfo(study, participant);
 }
			public void Validate(DicomFile dicomFile)
			{
				const string metaInfoErrorMessageFormat = "Invalid DICOM File Meta Info ({0})";

				DicomAttributeCollection sopInstanceDataset = dicomFile.DataSet;
				DicomAttributeCollection metaInfo = dicomFile.MetaInfo;

				DicomAttribute attribute = metaInfo[DicomTags.MediaStorageSopClassUid];
				// we want to skip Media Storage Directory Storage (DICOMDIR directories)
				if ("1.2.840.10008.1.3.10" == attribute.ToString())
					throw new DataStoreException("Cannot process DICOM directory files.");

				DicomValidator.ValidateStudyInstanceUID(sopInstanceDataset[DicomTags.StudyInstanceUid]);
				DicomValidator.ValidateSeriesInstanceUID(sopInstanceDataset[DicomTags.SeriesInstanceUid]);
				DicomValidator.ValidateSOPInstanceUID(sopInstanceDataset[DicomTags.SopInstanceUid]);
				DicomValidator.ValidateTransferSyntaxUID(metaInfo[DicomTags.TransferSyntaxUid]);

				if (dicomFile.SopClass == null)
					throw new DataStoreException(string.Format(metaInfoErrorMessageFormat, "SOP Class UID is missing"));

				try
				{
					DicomValidator.ValidateSopClassUid(dicomFile.SopClass.Uid);
				}
				catch (DicomDataException ex)
				{
					throw new DataStoreException(string.Format(metaInfoErrorMessageFormat, "SOP Class UID is missing"), ex);
				}

				Study study = new Study();
				study.Initialize(dicomFile);

				_validator.ValidatePersistentObject(study);
			}
Example #6
0
 public StudyDto(Study study)
 {
     Id = study.ID;
     Name = study.Name;
     Stages = study.Stages.Select(s => new StageDto(s)).ToArray();
     Team = new TeamDto(study.Team);
     Items = new byte[] {};
     IsFinished = study.IsFinished;
 }
Example #7
0
 public static Study GetStudyFromAccession(string accession)
 {
     var node = GetSelectedNode();
     if (node == null)
         throw new Exception("Unable to get selected DICOM node");
     StudyRootFindScu findScu = new StudyRootFindScu();
     StudyQueryIod queryMessage = new StudyQueryIod();
     queryMessage.SetCommonTags();
     queryMessage.AccessionNumber = accession;
     IList<StudyQueryIod> results = findScu.Find(node.LocalAe, node.AET, node.IP, node.Port, queryMessage);
     if (results.Count == 1)
     {
         Study st = new Study();
         st.Accession = results[0].AccessionNumber;
         st.Images = (int)results[0].NumberOfStudyRelatedInstances;
         st.PatientDob = results[0].PatientsBirthDate;
         st.PatientFirstname = results[0].PatientsName.FirstName;
         st.PatientId = results[0].PatientId;
         st.PatientSurname = results[0].PatientsName.LastName;
         st.StudyDate = results[0].StudyDate;
         st.StudyDescription = results[0].StudyDescription;
         st.StudyModality = results[0].ModalitiesInStudy;
         st.StudyUid = results[0].StudyInstanceUid;
         if (st.StudyDate != null && st.PatientDob != null)
         {
             int age = st.StudyDate.Value.Year - st.PatientDob.Value.Year;
             if (st.PatientDob.Value > st.StudyDate.Value.AddYears(-age)) age--;
             st.PatientAge = age;
         }
         StudyRootFindScu seriesFindScu = new StudyRootFindScu();
         SeriesQueryIod seriesQuery = new SeriesQueryIod();
         seriesQuery.SetCommonTags();
         seriesQuery.StudyInstanceUid = results[0].StudyInstanceUid;
         IList<SeriesQueryIod> seriesResults = seriesFindScu.Find(node.LocalAe, node.AET, node.IP, node.Port, seriesQuery);
         if (seriesResults.Count > 0)
         {
             st.Series = new List<Series>();
             foreach (var se in seriesResults)
             {
                 Series s = new Series();
                 s.StudyUid = results[0].StudyInstanceUid;
                 s.Images = (int)se.NumberOfSeriesRelatedInstances;
                 s.SeriesDescription = se.SeriesDescription;
                 s.SeriesModality = se.Modality;
                 s.SeriesUid = se.SeriesInstanceUid;
                 st.Series.Add(s);
             }
         }
         return st;
     }
     else
     {
         throw new Exception("No study found");
     }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack) {
         Study study = new Study(Convert.ToInt32(Request.QueryString["study_id"]));
         Participant participant = new Participant(Convert.ToInt32(Request.QueryString["participant_id"]));
         lblUserName2.Text = participant.UserName;
         lblFullName2.Text = participant.FirstName + " " + participant.LastName;
         lblEmail2.Text = participant.Email;
         showStudyInfo(study, participant);
     }
 }
 /// <summary>
 /// Permanently deletes a qualifier from the database and from the study it was being used in.
 /// </summary>
 /// <param name="qualifier"></param>
 /// <param name="study"></param>
 public static void DeleteQualifier(Qualifier qualifier, Study study)
 {
     if (qualifier.QualID <= 0) {
         throw new Exception("Invalid qualifier to delete, the qualID = " + qualifier.QualID);
     }
     if (study.StudyID <= 0) {
         throw new Exception("Invalid study to delete, the studyID = " + study.StudyID);
     }
     string queryString = "delete from Study_Qualifiers where Qual_ID = " + qualifier.QualID + " and Study_ID = " + study.StudyID;
     DatabaseQuery query = new DatabaseQuery(queryString, DatabaseQuery.Type.Delete);
 }
    /// <summary>
    /// This method populates the dictionary of matches. The dictionary contains a key 
    /// which is the participant and a value which is the cumulative matching score
    /// for the participant based on the study that is passed into the method. The 
    /// dictionary is then returned with the complete list of participants and each of 
    /// their scores.
    /// </summary>
    /// <param name="study"></param>
    /// <returns></returns>
    public Dictionary<Participant, int> makeMatch(Study study)
    {
        // create necassary variables
        List<Participant> removeList = new List<Participant>();
        List<Participant> participants = GetAllParticipants();

        // Populate our Participant list based on the Participant IDs we got.
        // Go through each Participant in the Participant List.
        foreach (Participant p in participants) {

            // Go through each Answer in each participant Answer List.
            foreach (Answer ans in p.Answers) {

                // Go through each Qualifier in the provided Study.
                foreach (Qualifier qual in study.Qualifiers) {

                    // Compare the Qualifier id of the Participant answer to the Study Qual ID.
                    if (ans.Qualifier.QualID == qual.QualID) {

                        //Populate the dictionary
                        if (results.ContainsKey(p)) {
                            if (results[p] < 0) {
                                continue;
                            }
                            else if (ans.Score < 0) {
                                results[p] = ans.Score;
                            }
                            else {
                                results[p] = results[p] += ans.Score;
                            }
                        }
                        else {
                            results.Add(p, ans.Score);
                        }
                    }
                }
            }
        }

        // If the Value is a negative number add it to a remove list
        foreach (KeyValuePair<Participant, int> kvp in results) {
            if (kvp.Value < 0) {
                removeList.Add(kvp.Key);
            }
        }

        // Remove each entry of the remove list from the results
        foreach (Participant p in removeList) {
            results.Remove(p);
        }

        return results;
    }
        public void RunTest_KoTS()
        {
            var competitors = Helpers.CompetitorListHelper.GetStandardCompetitors(8);

            TournamentStrategy tournamentStrategy = new KoTS(2);
            MatchStrategy matchStrategy = new SimpleRandomMs();

            var study = new Study(tournamentStrategy, matchStrategy, false);
            study.Run(competitors, _numberOfTournamentIterations);

            DisplayTestResults(tournamentStrategy, matchStrategy, study);
        }
Example #12
0
        public bool CheckRecive(DicomDataset ds)
        {
            Patient patient = new Patient();

            patient.PatientBirthDate = ds.Get <string>(DicomTag.PatientBirthDate);
            patient.PatientID        = ds.Get <string>(DicomTag.PatientID);
            patient.PatientName      = ds.Get <string>(DicomTag.PatientName);
            patient.PatientSex       = ds.Get <string>(DicomTag.PatientSex);



            Study study = new Study();

            study.ReferringPhysiciansName = ds.Get <string>(DicomTag.ReferringPhysicianName);
            study.StudyDate        = ds.Get <string>(DicomTag.StudyDate);
            study.StudyID          = ds.Get <string>(DicomTag.StudyID);
            study.StudyInstanceUID = ds.Get <string>(DicomTag.StudyInstanceUID);
            study.StudyTime        = ds.Get <string>(DicomTag.StudyTime);


            Series series = new Series();

            series.Modality          = ds.Get <string>(DicomTag.Modality);
            series.SeriesInstanceUID = ds.Get <string>(DicomTag.SeriesInstanceUID);
            series.SeriesNumber      = ds.Get <string>(DicomTag.SeriesNumber);



            Image image = new Image();

            image.InstanceNumber     = ds.Get <string>(DicomTag.InstanceNumber);
            image.ContentDate        = ds.Get <string>(DicomTag.ContentDate);
            image.ContentTime        = ds.Get <string>(DicomTag.ContentTime);
            image.PatientOrientation = ds.Get <string>(DicomTag.PatientOrientation);

            if (m.GetList <Patient>(patient, "tb_patient").Count != 0 &&
                m.GetList <Study>(study, "tb_study").Count != 0 &&
                m.GetList <Series>(series, "tb_series").Count != 0 &&
                m.GetList <Image>(image, "tb_image").Count != 0)
            {
                return(false);
            }
            return(true);
        }
Example #13
0
        public DifferenceCollection Compare(DicomMessageBase message, Study study, StudyCompareOptions options)
        {
            DifferenceCollection list = new DifferenceCollection();

            if (options.MatchIssuerOfPatientId)
            {
                InternalCompare(DicomTags.IssuerOfPatientId, study.IssuerOfPatientId,
                                message.DataSet[DicomTags.IssuerOfPatientId].ToString(), 64, list);
            }

            if (options.MatchPatientId)
            {
                InternalCompare(DicomTags.PatientId, study.PatientId,
                                message.DataSet[DicomTags.PatientId].ToString(), 64, list);
            }


            if (options.MatchPatientsName)
            {
                InternalCompare(DicomTags.PatientsName, study.PatientsName,
                                message.DataSet[DicomTags.PatientsName].ToString(), 64, list);
            }

            if (options.MatchPatientsBirthDate)
            {
                InternalCompare(DicomTags.PatientsBirthDate, study.PatientsBirthDate,
                                message.DataSet[DicomTags.PatientsBirthDate].ToString(), 8, list);
            }

            if (options.MatchPatientsSex)
            {
                InternalCompare(DicomTags.PatientsSex, study.PatientsSex,
                                message.DataSet[DicomTags.PatientsSex].ToString(), 2, list);
            }


            if (options.MatchAccessionNumber)
            {
                InternalCompare(DicomTags.AccessionNumber, study.AccessionNumber,
                                message.DataSet[DicomTags.AccessionNumber].ToString(), 16, list);
            }

            return(list);
        }
Example #14
0
        /// <summary>
        /// Returns a value indicating whether the specified study has been scheduled for delete.
        /// </summary>
        /// <param name="study"></param>
        /// <param name="read"></param>
        /// <returns></returns>
        public string GetModalitiesInStudy(IPersistenceContext read, Study study)
        {
            Platform.CheckForNullReference(study, "Study");

            IQueryModalitiesInStudy          select = read.GetBroker <IQueryModalitiesInStudy>();
            ModalitiesInStudyQueryParameters parms  = new ModalitiesInStudyQueryParameters {
                StudyKey = study.Key
            };
            IList <Series> seriesList = select.Find(parms);
            List <string>  modalities = new List <string>();

            foreach (Series series in seriesList)
            {
                bool found = false;
                foreach (string modality in modalities)
                {
                    if (modality.Equals(series.Modality))
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    modalities.Add(series.Modality);
                }
            }

            string modalitiesInStudy = "";

            foreach (string modality in modalities)
            {
                if (modalitiesInStudy.Length == 0)
                {
                    modalitiesInStudy = modality;
                }
                else
                {
                    modalitiesInStudy += "\\" + modality;
                }
            }

            return(modalitiesInStudy);
        }
Example #15
0
    void OnEnable()
    {
        allStats    = new List <Stat>();
        playerMoney = new PlayerMoney(true);

        Satisfaction.Init();
        Comfortableness.Init();
        GeneralRanking.Init();
        Hunger.Init();
        Social.Init();
        Study.Init();



        WorldLimitedUseInteractable.onInteractUse += deductStamina;
        LocationHandler.OnTurnEnd += resetStamina;

        DateTimeSystem.OnMonthChange += clearMonthBudget;
    }
        protected bool RoleAllreadyExistsForUser(Study study, int userId, string roleName)
        {
            if (study.StudyParticipants == null)
            {
                throw new ArgumentNullException($"Study not loaded properly. Probably missing include for \"StudyParticipants\"");
            }

            if (study.StudyParticipants.Count == 0)
            {
                return(false);
            }

            if (study.StudyParticipants.Where(sp => sp.UserId == userId && sp.RoleName == roleName).Any())
            {
                return(true);
            }

            return(false);
        }
Example #17
0
        /// <summary>
        /// Check if study is valid or not
        /// </summary>
        /// <param name="errorMessage"></param>
        /// <param name="studyIDString"></param>
        /// <returns></returns>
        bool validStudy(ref string errorMessage, string studyIDString)
        {
            int studyID;

            if (String.IsNullOrEmpty(studyIDString))
            {
                errorMessage += "Study ID cannot be empty\n";
                return(false);
            }

            if (!int.TryParse(studyIDString, out studyID))
            {
                errorMessage += "Study ID is not numeric\n";
                return(false);
            }



            try
            {
                Study x = null;
                x = studies.SingleOrDefault(s => s.Id == studyID);

                if (x == null)
                {
                    errorMessage += "Study not found\n";
                    return(false);
                }
                else
                {
                    thisStudy = new StudyDetail(x, cmbEnvironment.Text);
                }
            }
            catch
            {
                errorMessage += "Error Searching for Study\n";
                return(false);
            }



            return(true);
        }
Example #18
0
        public ActionResult StudyRedo(string redo, string deckID, bool frontFirst)
        {
            string userID = GetUserID();

            List <Card> redoCards = CardsToRedo(redo);

            redoCards.Shuffle();

            Study study = new Study
            {
                DeckID     = deckID,
                UserID     = userID,
                Cards      = redoCards,
                FrontFirst = frontFirst,
                WholeDeck  = false
            };

            return(View("Study", study));
        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of NpgSQLConnection
        ///
        /// </summary>
        //internal IDbConnection Connection
        //{
        //    get
        //    {
        //        return new NpgsqlConnection(connectionString);
        //    }
        //}

        /// <summary>
        /// Add Method created to insert entries to the database
        /// </summary>
        /// <param name="item"></param>
        public void Add(Study item)
        {
            //using (IDbConnection dbConnection = Connection)
            //{
            //    dbConnection.Open();
            //    dbConnection.Execute("INSERT INTO public.\"Inputs\"(\"StudyName\",\"StudyStartDate\",\"EstimatedCompletionDate\",\"ProtocolID\",\"StudyGroup\",\"Phase\",\"PrimaryIndication\",\"SecondaryIndication\") VALUES(@StudyName,@StudyStartDate,@EstimatedCompletionDate,@ProtocolID,@StudyGroup,@Phase, @PrimaryIndication, @SecondaryIndication);", item);
            //}

            using (IDbConnection dbConnection = new DBManager("SQL").GetDatabasecOnnection())
            {
                dbConnection.Execute("INSERT INTO public.\"Inputs\"(\"StudyName\",\"StudyStartDate\",\"EstimatedCompletionDate\",\"ProtocolID\",\"StudyGroup\",\"Phase\",\"PrimaryIndication\",\"SecondaryIndication\") VALUES(@StudyName,@StudyStartDate,@EstimatedCompletionDate,@ProtocolID,@StudyGroup,@Phase, @PrimaryIndication, @SecondaryIndication);", item);
            }

            ////Sends Message to SQS using SQSClient
            //using(SQSClient sqsClient = new SQSClient())
            //{
            //    sqsClient.SendMessageTOSQS(JsonConvert.SerializeObject(item),item.ProtocolID);
            //}
        }
Example #20
0
        //TODO: Consolidate this and DeleteStudy?
        public void DeleteSeries(Study study, IList <Series> series, string reason)
        {
            // Load the Partition
            var             partitionConfigController = new ServerPartitionConfigController();
            ServerPartition partition = partitionConfigController.GetPartition(study.ServerPartitionKey);

            var seriesUids = new List <string>();

            foreach (Series s in series)
            {
                seriesUids.Add(s.SeriesInstanceUid);
            }

            using (IUpdateContext ctx = PersistentStoreRegistry.GetDefaultStore().OpenUpdateContext(UpdateContextSyncMode.Flush))
            {
                StudyDeleteHelper.DeleteSeries(ctx, partition, study.StudyInstanceUid, seriesUids, reason);
                ctx.Commit();
            }
        }
        public Study RequestStudy(string Identifier)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string url = @"https://clinicaltrials.gov/api/query/full_studies?expr=" + Identifier + "&max_rnk=1&fmt=XML";

            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            string      xmlString = client.DownloadString(url);
            XmlDocument doc       = new XmlDocument();

            doc.LoadXml(xmlString);

            ClinicalTrialsXmlParser parser = new ClinicalTrialsXmlParser(container.Resolve <List <EndpointDescriptor> >());
            Study study = parser.Parse(doc);

            return(study);
        }
Example #22
0
        private void ParseConditionsModule(ref Study result)
        {
            XmlNode     conditionsModule = doc.SelectSingleNode("/FullStudiesResponse/FullStudyList/FullStudy/Struct/Struct[@Name='ProtocolSection']/Struct[@Name='ConditionsModule']");
            XmlNodeList conditionList    = conditionsModule.SelectNodes("./List[@Name='ConditionList']/Field");

            foreach (XmlNode condition in conditionList)
            {
                Condition newCondition = new Condition(condition.InnerText);

                result.ConditionList.Add(newCondition);
            }

            XmlNodeList keywordList = conditionsModule.SelectNodes("./List[@Name='KeywordList']/Field");

            foreach (XmlNode keyword in keywordList)
            {
                result.KeywordList.Add(keyword.InnerText);
            }
        }
Example #23
0
 public static bool UpdateStudyByPeople(int people_Id, string school, string grade, string major, string protector, string relationship, string phoneNo)
 {
     try
     {
         DbEntry.UsingTransaction(delegate
         {
             Study st        = Study.FindOne(CK.K["People_Id"] == people_Id && CK.K["IsDelete"] == false);
             st.School       = school;
             st.Grade        = grade;
             st.Major        = major;
             st.Protector    = protector;
             st.Relationship = relationship;
             st.PhoneNo      = phoneNo;
             st.Save();
         });
     }
     catch { return(false); }
     return(true);
 }
        async Task OrderCreationOfStudySpecificDatasetStorageAccount(Study study, Dataset dataset, CloudResource resourceGroup, string clientIp, ProvisioningQueueParentDto queueParent, CancellationToken cancellationToken)
        {
            try
            {
                if (resourceGroup == null)
                {
                    throw new ArgumentNullException("resourceGroup", "Resource group entry is null");
                }

                _logger.LogInformation($"CreateResourcesForStudySpecificDataset - Dataset Id: {dataset.Id}");

                var currentUser = await _userService.GetCurrentUserAsync();

                var tagsForStorageAccount = ResourceTagFactory.StudySpecificDatasourceStorageAccountTags(_config, study, dataset.Name);
                var storageAccountName    = AzureResourceNameUtil.StudySpecificDataSetStorageAccount(dataset.Name);

                var resourceEntry = await _cloudResourceCreateService.CreateStudySpecificDatasetEntryAsync(dataset.Id, resourceGroup.Id, resourceGroup.Region, resourceGroup.ResourceGroupName, storageAccountName, tagsForStorageAccount);

                ProvisioningQueueUtil.CreateChildAndAdd(queueParent, resourceEntry);

                var serverPublicIp = await _publicIpService.GetIp();

                DatasetFirewallUtils.EnsureDatasetHasFirewallRules(_logger, currentUser, dataset, clientIp, serverPublicIp);

                await _db.SaveChangesAsync();

                var stateForFirewallOperation = DatasetFirewallUtils.TranslateAllowedIpsToOperationDesiredState(dataset.FirewallRules.ToList());

                var createStorageAccountOperation = CloudResourceOperationUtil.GetCreateOperation(resourceEntry);
                var firewallUpdateOperation       = await _cloudResourceOperationCreateService.CreateUpdateOperationAsync(resourceEntry.Id, CloudResourceOperationType.ENSURE_FIREWALL_RULES, dependsOn : createStorageAccountOperation.Id, desiredState : stateForFirewallOperation);

                ProvisioningQueueUtil.CreateChildAndAdd(queueParent, firewallUpdateOperation);

                var stateForCorsRules   = DatasetCorsUtils.CreateDatasetCorsRules(_config);
                var corsUpdateOperation = await _cloudResourceOperationCreateService.CreateUpdateOperationAsync(resourceEntry.Id, CloudResourceOperationType.ENSURE_CORS_RULES, dependsOn : firewallUpdateOperation.Id, desiredState : stateForCorsRules);

                ProvisioningQueueUtil.CreateChildAndAdd(queueParent, corsUpdateOperation);
            }
            catch (Exception ex)
            {
                throw new Exception($"Failed to schedule creation of Azure Storage Account", ex);
            }
        }
Example #25
0
        public static void TestFixtureSetup(TestContext context)
        {
            study1 = new Study
            {
                GUID    = "study_guid_1",
                StudyId = "study1",
            };
            Study study2 = new Study
            {
                GUID    = "study_guid_2",
                StudyId = "study2",
            };

            studiesTest = new Dictionary <string, Study>
            {
                { study1.GUID, study1 },
                { study2.GUID, study2 }
            };
        }
    /// <summary>
    /// Dynamically creates panels that store each qualifier and answer
    /// </summary>
    /// <param name="study"></param>
    public Panel generateQualifiers(Study study)
    {
        Panel pnlQualifer = new Panel();
        foreach (Qualifier qualifier in study.Qualifiers) {
            //create a new panel that will hold all the information for this qualifier

            Label lblQualifier = new Label();
            RadioButtonList rblistAnswers = new RadioButtonList();
            foreach (Answer answer in qualifier.Answers) {
                rblistAnswers.Items.Add(answer.AnswerText);
            }
            lblQualifier.Text = qualifier.Question;
            pnlQualifer.Controls.Add(lblQualifier);
            rblistAnswers.Enabled = false;
            pnlQualifer.Controls.Add(rblistAnswers);
            //add the panel we just made to the form
        }
        return pnlQualifer;
    }
Example #27
0
 public static bool UpdateStudy(int studyId, string school, string grade, string major, string protector, string relationship, string phoneNo)
 {
     try
     {
         DbEntry.UsingTransaction(delegate
         {
             Study st        = Study.FindById(studyId);
             st.School       = school;
             st.Grade        = grade;
             st.Major        = major;
             st.Protector    = protector;
             st.Relationship = relationship;
             st.PhoneNo      = phoneNo;
             st.Save();
         });
     }
     catch { return(false); }
     return(true);
 }
Example #28
0
        public void AssertUniqueKeys()
        {
            Study study = CreateTestStudy1();
            var   sops  = study.GetSeries().First().GetSopInstances().Cast <SopInstance>().ToList();

            var criteria  = new DicomAttributeCollection();
            var filters   = new SopInstancePropertyFilters(criteria);
            var results   = filters.FilterResults(sops);
            var converted = filters.ConvertResultsToDataSets(results);

            foreach (var result in converted)
            {
                //It's 6 because of InstanceAvailability, RetrieveAE, SpecificCharacterSet.
                Assert.AreEqual(6, result.Count);
                Assert.IsNotEmpty(result[DicomTags.StudyInstanceUid]);
                Assert.IsNotEmpty(result[DicomTags.SeriesInstanceUid]);
                Assert.IsNotEmpty(result[DicomTags.SopInstanceUid]);
            }
        }
Example #29
0
        public async Task <IActionResult> AddStudy(AddStudyCommand command)
        {
            if (string.IsNullOrEmpty(command.Name))
            {
                return(BadRequest("Name cannot be empty"));
            }

            var study = new Study
            {
                Id      = Guid.NewGuid(),
                Name    = command.Name,
                Created = DateTime.Now,
                State   = State.Enabled,
                Results = new List <Result>()
            };
            await _repository.AddAsync(study);

            return(Accepted());
        }
Example #30
0
        public void GetStudyFromStudySpecificDatasetOrThrow_ShouldReturnCorrectStudy()
        {
            var studyDatasets = new List <StudyDataset>();
            var study         = new Study()
            {
                Name = "test", Id = 1
            };

            studyDatasets.Add(new StudyDataset {
                Study = study
            });
            var dataset = new Dataset()
            {
                StudyDatasets = studyDatasets
            };
            var result = DatasetUtils.GetStudyFromStudySpecificDatasetOrThrow(dataset);

            Assert.Equal(study, result);
        }
        private void RemoveExistingImage(WorkQueueUid uid)
        {
            string path = StorageLocation.GetSopInstancePath(uid.SeriesInstanceUid, uid.SopInstanceUid);

            if (!File.Exists(path))
            {
                return;
            }

            StudyXml studyXml = StorageLocation.LoadStudyXml();
            var      file     = new DicomFile(path);

            file.Load(DicomReadOptions.DoNotStorePixelDataInDataSet | DicomReadOptions.Default); // don't need to load pixel data cause we will delete it

            #if DEBUG
            int originalInstanceCountInXml  = studyXml.NumberOfStudyRelatedInstances;
            int originalStudyInstanceCount  = Study.NumberOfStudyRelatedInstances;
            int originalSeriesInstanceCount = Study.Series[uid.SeriesInstanceUid].NumberOfSeriesRelatedInstances;
            #endif

            using (var processor = new ServerCommandProcessor("Delete Existing Image"))
            {
                var seriesInstanceUid = file.DataSet[DicomTags.SeriesInstanceUid].ToString();
                var sopInstanceUid    = file.DataSet[DicomTags.SopInstanceUid].ToString();

                processor.AddCommand(new FileDeleteCommand(path, true));
                processor.AddCommand(new RemoveInstanceFromStudyXmlCommand(StorageLocation, studyXml, seriesInstanceUid, sopInstanceUid));
                processor.AddCommand(new UpdateInstanceCountCommand(StorageLocation, seriesInstanceUid, sopInstanceUid));

                if (!processor.Execute())
                {
                    throw new ApplicationException(String.Format("Unable to remove existing image {0}", file.Filename), processor.FailureException);
                }
            }

            #if DEBUG
            Debug.Assert(!File.Exists(path));
            Debug.Assert(studyXml.NumberOfStudyRelatedInstances == originalInstanceCountInXml - 1);
            Debug.Assert(Study.Load(Study.Key).NumberOfStudyRelatedInstances == originalStudyInstanceCount - 1);
            Debug.Assert(Study.Load(Study.Key).Series[uid.SeriesInstanceUid].NumberOfSeriesRelatedInstances == originalSeriesInstanceCount - 1);
            #endif
        }
Example #32
0
        /// <summary>
        /// Create a list of DICOM SOP Instances to move based on a Series level C-MOVE-RQ
        /// </summary>
        /// <param name="persistenceContext"></param>
        /// <param name="msg"></param>
        /// <param name="errorComment"> </param>
        /// <returns></returns>
        private bool GetSopListForSeries(IPersistenceContext persistenceContext, DicomMessageBase msg, out string errorComment)
        {
            errorComment = string.Empty;
            string studyInstanceUid = msg.DataSet[DicomTags.StudyInstanceUid].GetString(0, "");
            var    seriesList       = (string[])msg.DataSet[DicomTags.SeriesInstanceUid].Values;

            // Now get the storage location
            StudyStorageLocation location;

            try
            {
                FilesystemMonitor.Instance.GetReadableStudyStorageLocation(Partition.Key, studyInstanceUid, StudyRestore.True,
                                                                           StudyCache.True, out location);
            }
            catch (StudyIsNearlineException e)
            {
                errorComment = string.Format(e.RestoreRequested ? "Study is nearline, inserted restore request: {0}" : "Study is nearline: {0}", studyInstanceUid);
                return(false);
            }
            catch (Exception e)
            {
                errorComment = string.Format("Exception occurred when determining study location: {0}", e.Message);
                return(false);
            }

            var select = persistenceContext.GetBroker <IStudyEntityBroker>();

            var criteria = new StudySelectCriteria();

            criteria.StudyInstanceUid.EqualTo(studyInstanceUid);
            criteria.ServerPartitionKey.EqualTo(Partition.Key);

            Study    study       = select.FindOne(criteria);
            StudyXml studyStream = LoadStudyXml(location);

            foreach (string seriesInstanceUid in seriesList)
            {
                _theScu.LoadSeriesFromSeriesXml(studyStream, Path.Combine(location.GetStudyPath(), seriesInstanceUid), studyStream[seriesInstanceUid], study.PatientsName, study.PatientId);
            }

            return(true);
        }
Example #33
0
        public bool MoveStudy(Study study, Device device, IList <Series> seriesList)
        {
            if (seriesList != null)
            {
                using (
                    IUpdateContext context = PersistentStoreRegistry.GetDefaultStore().OpenUpdateContext(UpdateContextSyncMode.Flush))
                {
                    ServerPartition partition = ServerPartition.Load(study.ServerPartitionKey);

                    List <string> seriesUids = new List <string>();
                    foreach (Series series in seriesList)
                    {
                        seriesUids.Add(series.SeriesInstanceUid);
                    }

                    IList <WorkQueue> entries = StudyEditorHelper.MoveSeries(context, partition, study.StudyInstanceUid, device.Key, seriesUids);
                    if (entries != null)
                    {
                        context.Commit();
                    }

                    return(true);
                }
            }
            WorkQueueAdaptor       workqueueAdaptor = new WorkQueueAdaptor();
            DateTime               time             = Platform.Time;
            WorkQueueUpdateColumns columns          = new WorkQueueUpdateColumns
            {
                WorkQueueTypeEnum   = WorkQueueTypeEnum.WebMoveStudy,
                WorkQueueStatusEnum = WorkQueueStatusEnum.Pending,
                ServerPartitionKey  = study.ServerPartitionKey,
                StudyStorageKey     = study.StudyStorageKey,
                FailureCount        = 0,
                DeviceKey           = device.Key,
                ScheduledTime       = time,
                ExpirationTime      = time.AddMinutes(4)
            };

            workqueueAdaptor.Add(columns);

            return(true);
        }
        private List <Sop> LoadSegmentationSopsForStudy(string studyInstanceUid)
        {
            const string segmentationModality = "SEG";

            Study study = ImageViewer.StudyTree.GetStudy(studyInstanceUid);

            if (study != null && study.ModalitiesInStudy.Any(modality => modality == segmentationModality))
            {
                IEnumerable <Series> segSeries = study.Series.Where(series => series.Modality == segmentationModality);
                var sops = new List <Sop>();
                foreach (Series series in segSeries)
                {
                    sops.AddRange(series.Sops);
                }

                return(sops);
            }

            return(null);
        }
Example #35
0
        public void SelectByInstanceNumber()
        {
            Study study = CreateTestStudy1();
            var   sops  = study.GetSeries().First().GetSopInstances().Cast <SopInstance>().ToList();

            var criteria = new DicomAttributeCollection();

            criteria[DicomTags.InstanceNumber].SetInt32(0, 102);

            var filters = new SopInstancePropertyFilters(criteria);
            var results = filters.FilterResults(sops);

            Assert.AreEqual(1, results.Count());

            criteria[DicomTags.InstanceNumber].SetInt32(0, 106);
            filters = new SopInstancePropertyFilters(criteria);

            results = filters.FilterResults(sops);
            Assert.AreEqual(0, results.Count());
        }
Example #36
0
        private void AuditLog(Study affectedStudy)
        {
            // Audit log
            DicomStudyDeletedAuditHelper helper =
                new DicomStudyDeletedAuditHelper(
                    ServerPlatform.AuditSource,
                    EventIdentificationContentsEventOutcomeIndicator.Success);

            helper.AddUserParticipant(new AuditPersonActiveParticipant(
                                          SessionManager.Current.Credentials.
                                          UserName,
                                          null,
                                          SessionManager.Current.Credentials.
                                          DisplayName));
            helper.AddStudyParticipantObject(new AuditStudyParticipantObject(
                                                 affectedStudy.StudyInstanceUid,
                                                 affectedStudy.AccessionNumber ??
                                                 string.Empty));
            ServerPlatform.LogAuditMessage(helper);
        }
        public Study ConvertStudy(CreateStudyModel csmodel, int id_researcher)
        {
            var study = new Study
            {
                Name                    = csmodel.currentStudy.Name,
                Pay                     = (int)csmodel.currentStudy.Pay,
                Preparation             = csmodel.currentStudy.Preparation,
                Isdraft                 = csmodel.currentStudy.Isdraft,
                DirectStudyLink         = "None",
                IdResearcher            = id_researcher,
                Abstract                = csmodel.currentStudy.Abstract,
                DateCreated             = DateTime.Now,
                Description             = csmodel.currentStudy.Description,
                Duration                = csmodel.currentStudy.Duration,
                EligibilityRequirements = csmodel.currentStudy.EligibilityRequirements,
                Location                = csmodel.currentStudy.Location
            };

            return(study);
        }
        public async Task EnsureFirewallExistsAsync(Study study, Dataset dataset, string clientIp, CancellationToken cancellationToken = default)
        {
            var currentUser = await _userService.GetCurrentUserAsync();

            var serverPublicIp = await _publicIpService.GetIp();

            if (DatasetFirewallUtils.SetDatasetFirewallRules(currentUser, dataset, clientIp, serverPublicIp))
            {
                await _db.SaveChangesAsync(cancellationToken);

                var stateForFirewallOperation     = DatasetFirewallUtils.TranslateAllowedIpsToOperationDesiredState(dataset.FirewallRules.ToList());
                var datasetStorageAccountResource = DatasetUtils.GetStudySpecificStorageAccountResourceEntry(dataset);
                var firewallUpdateOperation       = await _cloudResourceOperationCreateService.CreateUpdateOperationAsync(datasetStorageAccountResource.Id,
                                                                                                                          CloudResourceOperationType.ENSURE_FIREWALL_RULES, desiredState : stateForFirewallOperation);

                await _provisioningQueueService.CreateItemAndEnqueue(firewallUpdateOperation);

                await WaitForOperationToCompleteAsync(firewallUpdateOperation.Id);
            }
        }
        protected override TestResult InnerTest(object data, object root)
        {
            if (ServerExecutionContext.Current.PrimaryStudyKey != null)
            {
                var study = Study.Load(ServerExecutionContext.Current.PrimaryStudyKey);
                Platform.CheckForNullReference(study, "The referenced study does not exist in the database");

                if (study.OrderKey != null)
                {
                    var order = Order.Load(study.OrderKey);
                    if (order.QCExpected)
                    {
                        return(DefaultTestResult(true));
                    }
                }
                Platform.Log("QC", LogLevel.Info, "Study does not have an order or the order is not intended for QC.");
            }

            return(DefaultTestResult(false));
        }
 /// <summary>
 /// Shows questions/answers and score for a particular study
 /// </summary>
 /// <param name="study"></param>
 private void showStudyInfo(Study study, Participant participant)
 {
     foreach (Qualifier qualifier in study.Qualifiers) {
         Label lblQualifier = new Label();
         pnlQualifiers.Controls.Add(lblQualifier);
         RadioButtonList rblistAnswers = new RadioButtonList();
         foreach (Answer answer in qualifier.Answers) {
             ListItem item = new ListItem(answer.AnswerText + "  [" + answer.Score + "]", answer.AnsID.ToString());
             rblistAnswers.Items.Add(item);
             foreach (Answer participantAnswer in participant.Answers) {
                 if (answer.AnsID == participantAnswer.AnsID) {
                     rblistAnswers.SelectedValue = answer.AnsID.ToString();
                 }
             }
         }
         pnlQualifiers.Controls.Add(rblistAnswers);
         lblQualifier.Text = qualifier.Question;
         rblistAnswers.Enabled = false;
     }
 }
Example #41
0
        public void Test_CreatingNewStudy_HasSomeImages()
        {
            var r = new Random(100);

            var generator = new DicomDataGenerator(r, null);

            var p = new Person(r);

            Study study = new Study(generator, p, new ModalityStats("MR", 2, 0, 50, 0, r), r);

            Assert.AreEqual(2, study.Series.Count);
            Assert.AreEqual(50, study.Series[0].Datasets.Count);


            foreach (DicomDataset ds in study.Series[0])
            {
                Assert.AreEqual("MR", ds.GetValues <string>(DicomTag.Modality)[0]);
                Assert.AreEqual(study.StudyTime, ds.GetSingleValue <DateTime>(DicomTag.StudyTime).TimeOfDay);
            }
        }
Example #42
0
        private void BuildFromStudy(Study study)
        {
            IImageSet existing = GetImageSet(study.StudyInstanceUid);


            //if (existing != null)
            //{
            //    var descriptor = (IDicomImageSetDescriptor)existing.Descriptor;
            //    if (descriptor.LoadStudyError == null)
            //    {
            //        // Abort if valid image set has already been added.
            //        return;
            //    }
            //}

            var imageSet = CreateImageSet(GetStudyIdentifier(study));

            if (imageSet.Uid != study.StudyInstanceUid)
            {
                throw new InvalidOperationException("ImageSet Uid must be the same as Study Instance Uid.");
            }

            SortSeries(study.Series);

            foreach (Series series in study.Series)
            {
                SortSops(series.Sops);
            }

            FillImageSet(imageSet, study);

            if (existing == null)
            {
                AddImageSet(imageSet);
            }
            else
            {
                LogicalWorkspace.ImageSets[LogicalWorkspace.ImageSets.IndexOf(existing)] = imageSet;
                existing.Dispose();
            }
        }
        public ActionResult Question(int index, string result)
        {
            switch (result)
            {
            case "Rätt":
                Study.Articles[index].SetLastResult(StudyArticleResult.Success);
                break;

            case "Fel":
                Study.Articles[index].SetLastResult(StudyArticleResult.Failure);
                break;

            case "Revidera":
                Study.Articles[index].SetLastResult(StudyArticleResult.Revise);
                break;

            default:
                throw new ArgumentOutOfRangeException("value");
            }


            index++;

            if (index >= Study.Articles.Count)
            {
                SaveReport(Study.Articles);

                if (Study.Repeat())
                {
                    return(RedirectToAction("Question", new { index = 0, message = "Nu går vi igenom alla frågor där du hade fel en gång till." }));
                }
                else
                {
                    return(RedirectToAction("Index", new { message = "Grattis! Nu har du klarat alla frågor." }));
                }
            }
            else
            {
                return(RedirectToAction("Question", new { index = index }));
            }
        }
        public void RunTest_RoundRobinThenQuarterfinals_NonRandomMatches()
        {
            var competitors = Helpers.CompetitorListHelper.GetStandardCompetitors(8);

            TournamentStrategy tournamentStrategy = new RrKoSfFiTS(2.0, 2);
            MatchStrategy matchStrategy = new NonRandomMs();

            var study = new Study(tournamentStrategy, matchStrategy, false);
            study.Run(competitors, _numberOfTournamentIterations);

            DisplayTestResults(tournamentStrategy, matchStrategy, study);

            Assert.AreEqual(1, competitors[0].TournamentRankMean);
            Assert.AreEqual(2, competitors[1].TournamentRankMean);
            Assert.AreEqual(3, competitors[2].TournamentRankMean);
            Assert.AreEqual(4, competitors[3].TournamentRankMean);
            Assert.AreEqual(5, competitors[4].TournamentRankMean);
            Assert.AreEqual(6, competitors[5].TournamentRankMean);
            Assert.AreEqual(7, competitors[6].TournamentRankMean);
            Assert.AreEqual(8, competitors[7].TournamentRankMean);
        }
        public List<Study> FindAllStudies()
        {
            SqlConnection conn = GetConnection();
            SqlCommand cmd = conn.CreateCommand();
            List<Study> studies = new List<Study>();

            using (conn)
            {
                conn.Open();
                cmd.CommandText = "SELECT * FROM tbl_studies";

                 using (var reader = cmd.ExecuteReader())
                 {
                     if (!reader.Read())
                         {
                             return null;
                         }
                     else
                     {
                         while (reader.Read())
                         {
                             Study study = new Study();
                            study.StudyID = reader.GetInt32(reader.GetOrdinal("study_ID"));
                            study.StudyName = reader.GetString(reader.GetOrdinal("study_name"));
                            study.StudyManager = reader.GetString(reader.GetOrdinal("study_manager"));
                            study.StudyCreated = reader.GetDateTime(reader.GetOrdinal("Study_DateCreated"));
                            studies.Add(study);
                         }

                     }

                  }
            }
            conn.Close();
            return studies;
        }
        public void RunTest_RrTS_1()
        {
            var competitors = Helpers.CompetitorListHelper.GetCompetitorsWithRandomizedSeeds(8);

            TournamentStrategy tournamentStrategy = new RrTS(1, 1);
            MatchStrategy matchStrategy = new SimpleRandomMs();

            Study study = new Study(tournamentStrategy, matchStrategy, false);
            study.Run(competitors, _numberOfTournamentIterations, true);

            DisplayTestResults(tournamentStrategy, matchStrategy, study);
        }
Example #47
0
			private static string GetSpecificCharacterSet(Study study)
			{
				return study.SpecificCharacterSet;
			}
    /// <summary>
    /// This is the page load method and is called whenever the ParticipantStudy 
    /// page is loaded. If the page is a post back it sets the main panel 
    /// visibility to true. If it is not a post back, the visibility gets set to
    /// false. The method sets the study name and description appropriately, and then
    /// loads the main qualifier panel with inner panels containing the questions and
    /// answers.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Assign our local variables
        qualCount = 0; // used to check if all the qualifiers for a study have been previously answered.
        bool skipFlag = false; // used to determine if we need to skip a particular qualifier

        int partID = ((Participant)Session["user"]).UserID;
        study = new Study(Convert.ToInt32(Request.QueryString["study_id"]));
        List<int> ansIDs = DAL.GetParticipantAnswers(partID);
        List<string> resNameEamil = DAL.GetResearcher(study.ResearcherID);

        // Assign all of the qualifiers for the study
        studyQualifiers = study.Qualifiers;

        if (!IsPostBack) {
            pnlQuals.Visible = false;
        }
        lblName.Text = study.Name;
        lblResName.Text = resNameEamil[0];
        lblResEmail.Text = resNameEamil[1];
        lblDescription.Text = study.Description;

        // Logic to go through and check for previously answered Study Qualifiers
        for (int i = 0; i < studyQualifiers.Count; i++) {
            skipFlag = false;
            qual = studyQualifiers[i];

            foreach (int id in ansIDs) {
                foreach (Answer ans in qual.Answers) {
                    if (id == ans.AnsID) {
                        skipFlag = true;
                        qualCount++;
                        break;
                    }
                }
                if (skipFlag == true) {
                    break;
                }
            }

            // if the qualifier has previously been answered don't add it to the list,
            // if not do add it.
            if (skipFlag == true) {
                continue;
            }
            else {
                relevantQualifiers.Add(qual);
            }

            // Create our individual question and answer
            pnlQuals.Controls.Add(CreateQuestionAnswer(qual));
            pnlQuals.Controls.Add(new LiteralControl("<br />"));
        }
    }
Example #49
0
 public Study createStudy(string studyName, string hearIn, string seeIn, int hours, int minutes, int seconds, int trials, int target)
 {
     DataClasses1DataContext database = new DataClasses1DataContext();
     Study s = new Study();
     s.Name = studyName;
     s.HearInstructions = hearIn;
     s.SeeInstructions = seeIn;
     s.WaitHours = hours;
     s.WaitMins = minutes;
     s.WaitSecs = seconds;
     s.WordTrialsPerBlock = trials;
     s.TargetWordsPerMinute = target;
     s.Active = true;
     database.Studies.InsertOnSubmit(s);
     database.SubmitChanges();
     return s;
 }
    /// <summary>
    /// Method that automatically fills out all of the forms based on the study given as a parameter
    /// </summary>
    /// <param name="study"></param>
    private void populateForm(Study study)
    {
        tbName.Text = study.Name;
        tbDescription.Text = study.Description;
        tbIncentive.Text = study.Incentive;
        cbStdExpired.Visible = true;
        lblExpired.Visible = true;
        lblExpired2.Visible = true;
        if (study.Expired == true) {
            cbStdExpired.Checked = true;
        }

        //fills in the list box of qualifiers
        lbQualifiers.Items.Clear();
        foreach (Qualifier qualifier in study.Qualifiers) {
            pnlExistingQuals.Visible = true;
            ListItem item = new ListItem(qualifier.Question, qualifier.QualID.ToString());
            lbQualifiers.Items.Add(item);
        }
    }
    /// <summary>
    /// Queries the database to compare what Answers currently exist in the 
    /// database with the study passed in and removes them from the database if they no longer exist.
    /// </summary>
    /// <param name="study">Accepts the study that we are deleting the qualifier from</param>
    private void removeDeletedAnwers(Study study)
    {
        string queryString = "select Ans_ID from Study_Qualifiers sq, Answers a where sq.Qual_ID = a.Qual_ID and sq.Study_ID = " + study.StudyID;
        DatabaseQuery query = new DatabaseQuery(queryString, DatabaseQuery.Type.Select);
        List<Answer> oldAnswers = new List<Answer>();
        for (int i = 0; i < query.Results.Count; i++) {
            oldAnswers.Add(new Answer(Convert.ToInt32(query.Results[i][0])));
        }

        foreach (Answer oldAnswer in oldAnswers) {
            bool found = false;
            foreach (Qualifier qual in study.Qualifiers) {
                foreach (Answer ans in qual.Answers) {
                    if (oldAnswer.AnsID == ans.AnsID) {
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                DAL.DeleteAnswer(oldAnswer);
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        int count;
        int x = lbAnswerList.SelectedIndex;
        isEdit = Convert.ToBoolean(Request.QueryString["edit"] == "true");
        qualEditIndex = Convert.ToInt32(Session["qualEditIndex"]);
        if (!IsPostBack) {
            Session["study"] = null;
            //Editing an existing study
            if (isEdit) {
                study = new Study(Convert.ToInt32(Request.QueryString["study_id"]));
                populateForm(study);
                Session["study"] = study;
            }
        }
        study = (Study)Session["study"];
        //if the study is null, create a temp study that will be altered later.
        if (study == null) {
            //create a temporary study that will be overwritten later
            study = new Study(-1, "", "", "", DateTime.Now, false, 0, new List<Qualifier>());
        }

        // Create all of our qualifiers to be used to select from
        existingQualList = ConstructQualifiers(new Dictionary<int, List<List<string>>>());

        // filter out the qualifiers that already exist in the current study.
        // only required when editing a study.
        if (isEdit) {
            for (int i = existingQualList.Count - 1; i >= 0; i--) {
                foreach (Qualifier qualifier in study.Qualifiers) {
                    if (existingQualList[i].QualID == qualifier.QualID) {
                        existingQualList.RemoveAt(i);
                        break;
                    }
                }
            }
        }

        // populate Pre existing qualifier list box
        if (!IsPostBack) {
            foreach (Qualifier qual in existingQualList) {
                lbPreDefinedQuals.Items.Add(qual.Question);
                count = lbPreDefinedQuals.Items.Count - 1;
                lbPreDefinedQuals.Items[count].Attributes.Add("Answer", "Test");
            }
            for (int i = 0; i < lbPreDefinedQuals.Items.Count; i++) {
                lbPreDefinedQuals.Items[i].Attributes.Add("style", "background-color: orange");
            }
        }

        if (!IsPostBack) {
            Session["answerText"] = new List<string>();
            foreach (Qualifier qual in existingQualList) {
                temp = new StringBuilder("Answers: \n");
                foreach (Answer ans in qual.Answers) {
                    temp.Append(ans.AnswerText);
                    temp.AppendLine(" " + "(Rank: [" + ans.Score.ToString() + "])");
                }
                ((List<string>)Session["answerText"]).Add(temp.ToString());
                temp = null;
            }
        }

        for (int i = 0; i < lbPreDefinedQuals.Items.Count; i++) {
            lbPreDefinedQuals.Items[i].Attributes.Add("Title", ((List<string>)Session["AnswerText"])[i]);
        }
    }
    /// <summary>
    /// Helper method that decides whether each part of the study should be inserted or updated into the database
    /// </summary>
    /// <param name="study"></param>
    private void finishStudy(Study study)
    {
        //if studyID is -1 it is a new study, insert it into the database
        if (study.StudyID < 0) {
            study.StudyID = DAL.InsertStudy(study);
        }
        else {
            DAL.UpdateStudy(study);
        }
        foreach (Qualifier qualifier in study.Qualifiers) {
            //if qualifierID is -1 it is a new qualifier, insert it into the database
            if (qualifier.QualID < 0) {
                qualifier.QualID = DAL.InsertQualifier(qualifier, study.StudyID);
            }
            else {
                //if the study already has this qualifier in it than just update it
                if (DAL.QualifierExistsInStudy(study.StudyID, qualifier.QualID)) {
                    DAL.UpdateQualifier(qualifier);
                }
                //if the study doesn't have this qualifier than they must be adding an existing
                //study and we only need to add it to the Study_Qualifier table but not the Qualifier table
                else {
                    DAL.InsertExisingQualifier(qualifier, study.StudyID);
                }
            }
            //if answerID is -1, it is a new answer, insert it into the database
            foreach (Answer answer in qualifier.Answers) {
                if (answer.AnsID < 0) {
                    int ansID = DAL.InsertAnswer(answer, qualifier.QualID);
                    answer.AnsID = ansID;
                }
                else {
                    // bug continued:
                    // Because we are setting the ansID equal to the rank,
                    // when the rank of the answer is greater than 0 we are updating.
                    // This explains why we only have answers in the database of rank -1 or 0
                    DAL.UpdateAnswer(answer);
                }
            }
        }
        removeDeletedAnwers(study);
        removeDeletedQualifiers(study);

        return;
    }
    /// <summary>
    /// This method takes all the information from the answer and qualifier fields and
    /// populates the database. It will first populate the Qualifier table, then it
    /// will populate the Study_Qualifier table, and finally it will populate the
    /// Answer table. It will then clear all the text fields and the user may provide 
    /// another qualifier.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveQualifier(object sender, EventArgs e)
    {
        List<Answer> answersInListBox = new List<Answer>();
        int studyID;

        //error checking to make sure they filled out all of the forms correctly
        if (tbQuestion.Text.Equals(string.Empty) || lbAnswerList.Items.Count == 0) {
            lblErrorCont.Visible = true;
            return;
        }
        lblErrorCont.Visible = false;

        //code to save the qualifier if it was selected from the list of previously created qualifiers
        foreach (Qualifier existingQual in existingQualList) {

            // we only need to enter this logic when the qualifier is new
            if ((existingQual.Question.Equals(tbQuestion.Text)) && (((bool)Session["qualIsNew"]) == true)) {
                study.Qualifiers.Add(existingQual);

                studyID = -1;
                if (isEdit) {
                    studyID = Convert.ToInt32(Request.QueryString["study_id"]);
                }
                study = new Study(studyID, tbName.Text, tbDescription.Text, tbIncentive.Text, DateTime.Now, cbStdExpired.Checked, ((Researcher)(Session["user"])).UserID, study.Qualifiers);
                Session["study"] = study;

                // clear the contents of the fields for new entries
                tbQualDesc.Text = string.Empty;
                tbQuestion.Text = string.Empty;
                tbAnswer.Text = string.Empty;
                tbScore.Text = string.Empty;
                lbAnswerList.Items.Clear();
                populateQualifiers(study.Qualifiers);
                Session["qualEditIndex"] = -1;
                pnlQuals.Visible = false;
                pnlExistingQuals.Visible = true;

                return;
            }
        }

        Qualifier qualifier = null;
        int qualID = ((lbQualifiers.Items.Count+1)*-1);
        if (qualEditIndex > -1) {
            qualID = study.Qualifiers[qualEditIndex].QualID;
        }
        qualifier = new Qualifier(qualID, tbQuestion.Text, tbQualDesc.Text, Convert.ToInt32(((Researcher)Session["user"]).UserID));

        //clear all of the answers and then add them in one at a time to the qualifier
        qualifier.Answers.Clear();
        foreach (ListItem item in lbAnswerList.Items) {
            List<String> ansRank = sepearateAnswerAndRank(item.Text);
            string ans = ansRank[0];
            int rank = Convert.ToInt32(ansRank[1]);
            int ansID = -1;
            if (Convert.ToInt32(item.Value) > 0) {
                ansID = Convert.ToInt32(item.Value);
            }
            Answer answer = new Answer(ansID, ans, rank, qualifier);
            qualifier.Answers.Add(answer);
        }

        //qualifier doesn't exist, add it to the list
        if (qualifier.QualID < 0) {
            study.Qualifiers.Add(qualifier);
        }

        //qualifier already exists, we are just updating it, remove the old one and replace it with the new one
        else {
            study.Qualifiers.Remove(study.Qualifiers[qualEditIndex]);
            study.Qualifiers.Add(qualifier);
        }
        studyID = -1;
        if (isEdit) {
            studyID = Convert.ToInt32(Request.QueryString["study_id"]);
        }
        study = new Study(studyID, tbName.Text, tbDescription.Text, tbIncentive.Text, DateTime.Now, cbStdExpired.Checked, ((Researcher)(Session["user"])).UserID, study.Qualifiers);
        Session["study"] = study;

        // clear the contents of the fields for new entries
        tbQualDesc.Text = string.Empty;
        tbQuestion.Text = string.Empty;
        tbAnswer.Text = string.Empty;
        tbScore.Text = string.Empty;
        lbAnswerList.Items.Clear();
        populateQualifiers(study.Qualifiers);
        Session["qualEditIndex"] = -1;
        pnlQuals.Visible = false;
        pnlExistingQuals.Visible = true;
    }
    /// <summary>
    /// Takes all of the data filled out for the study and either inserts or updates it into the database.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnFinished_Click(object sender, EventArgs e)
    {
        //Check that the name and description are filled in.
        if (tbName.Text.Equals(string.Empty) || tbDescription.Text.Equals(string.Empty)) {
            lblError.Text = "Please fill out the necessary fields.";
            lblError.Visible = true;
            return;
        }
        lblError.Visible = false;

        int expired = Convert.ToInt32(cbStdExpired.Checked);
        Researcher res = (Researcher)Session["user"];
        int studyID = -1; //-1 means that it hasn't been set yet. Only a new study should have the value of -1, otherwise it should be the ID of the study in the database

        //check to see if we are editing or creating a study
        if (isEdit) {
            studyID = Convert.ToInt32(Request.QueryString["study_id"]);
        }

        //Create a study object with all of its attributes filled out from the forms that the user entered
        study = new Study(studyID, tbName.Text, tbDescription.Text, tbIncentive.Text, DateTime.Now, Convert.ToBoolean(expired), res.UserID, study.Qualifiers);

        finishStudy(study);

        //Send an email A notification email out to all the participants that a new study is ready
        if (!isEdit) {
            EmailSender mailSender = new EmailSender();
            List<string> recipients = DAL.GetRecipientEmails();
            string subject = "New research studies are available!";
            StringBuilder body = new StringBuilder("Please log on to the Study Participant Portal to check out new studies!");
            mailSender.sendEmail("*****@*****.**", recipients, subject, body);

            mailSender = null;
            body = null;
        }

        Response.Redirect("StudyForm.aspx?study_id=" + study.StudyID);
    }
Example #56
0
        public IImageSet BuildImageSet(StudyTree studyTree, out Study study)
        {
            if (IsRemote)
            {
                study = null;
                //Add only the image set, which essentially makes it a remote study.
                var identifier = new StudyRootStudyIdentifier(this, this, new StudyIdentifier())
                                     {
                                         PatientId = ReconciledPatientId ?? PatientId
                                     };

                return new ImageSet(new DicomImageSetDescriptor(identifier));
            }

            study = AddStudy(studyTree);
            var studyIdentifier = study.GetIdentifier();
            studyIdentifier = new StudyRootStudyIdentifier(studyIdentifier) { PatientId = ReconciledPatientId ?? study.ParentPatient.PatientId };
            var imageSet = new ImageSet(new DicomImageSetDescriptor(studyIdentifier));
            foreach (var series in study.Series)
            {
                foreach (var displaySet in DisplaySetFactory.CreateDisplaySets(series))
                    imageSet.DisplaySets.Add(displaySet);
            }

            return imageSet;
        }
 private void DisplayTestResults(TournamentStrategy tournamentStrategy, MatchStrategy matchStrategy, Study study)
 {
     Trace.WriteLine(string.Format("Number of Tournament Iterations: {0}", _numberOfTournamentIterations));
     Trace.WriteLine(study.StrategyInformation);
 }
    /// <summary>
    /// Queries the database to compare what Qualifiers currently exist in the 
    /// database with the study passed in and removes them from the database if they no longer exist.
    /// </summary>
    /// <param name="study">Accepts the study that we are deleting the qualifier from</param>
    private void removeDeletedQualifiers(Study study)
    {
        string queryString = "select Qual_ID from Study_Qualifiers where Study_ID = " + study.StudyID;
        DatabaseQuery query = new DatabaseQuery(queryString, DatabaseQuery.Type.Select);
        List<Qualifier> oldQualifiers = new List<Qualifier>();
        for (int i = 0; i < query.Results.Count; i++) {
            oldQualifiers.Add(new Qualifier(Convert.ToInt32(query.Results[i][0])));
        }

        foreach (Qualifier oldQualifier in oldQualifiers) {
            bool found = false;
            foreach (Qualifier qual in study.Qualifiers) {
                if (oldQualifier.QualID == qual.QualID) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                DAL.DeleteQualifier(oldQualifier, study);
            }
        }
    }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="study"></param>
 /// <returns></returns>
 private List<string> getEmails(Study study)
 {
     List<String> emails = new List<string>();
     Matchmaker matchmaker = new Matchmaker(new Study(study.StudyID));
     foreach (KeyValuePair<Participant, int> result in matchmaker.Results) {
         emails.Add(result.Key.Email);
     }
     tbEmailList.Visible = true;
     lblEmailStatus.Visible = true;
     return emails;
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack) {
         int studyID = Convert.ToInt32(Request.QueryString["study_id"]);
         Study = new Study(studyID);
         lblStdName.Text = Study.Name;
         lblStdDate.Text = Study.DateCreated.ToString();
         lblStdDescription.Text = Study.Description;
         lblEmailStatus.Visible = false;
     }
     pnlStdQualifiers.Controls.Add(generateQualifiers(Study));
 }