// insert in the drop down menu all existing discrete scale
 public void PopulateTypeScaleDiscrete()
 {
     cbxDiscreteScale.DataSource     = DataAccessTestCase.getScaleDiscrete();
     cbxDiscreteScale.DataTextField  = "DescriptionScaleDiscrete";
     cbxDiscreteScale.DataValueField = "ID_TypScaleDiscrete";
     cbxDiscreteScale.DataBind();
 }
        // checks if the testcase name doesnt exist a second time
        protected void CVTestCaseName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;

            if (DataAccessTestCase.VerifyExistTestCaseName(txtNameTestCase.Text))
            {
                args.IsValid = false;
            }
        }
        public void writeConfigFile(long idtestcase)
        {
            Class.TestCase    tc             = DataAccess.DataAccessTestCase.getTestCase(idtestcase);
            List <GroupImage> listgroupImage = DataAccessTestCase.getAllImagesOfTestcase(idtestcase);
            string            path           = Constant.pathConfigFileTestcase;


            string listOfUsertypes         = "";
            List <Class.TypUser> Usertypes = DataAccessUser.GetTypeUserForTestCase(idtestcase);

            foreach (Class.TypUser user in Usertypes)
            {
                listOfUsertypes += user.ID_Typ + ",";
            }


            try
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + "\\" + tc.NameTestCase + "_" + idtestcase + ".cfg"))
                {
                    string activeLearning      = "off";
                    string scale               = "continuous";
                    int    totalAmountOfImages = 0;

                    if (tc.DiskreteScale)
                    {
                        scale = "discrete";
                    }

                    if (tc.ActiveLearning)
                    {
                        activeLearning = "on";
                    }

                    file.WriteLine("Id:" + idtestcase + "; name:" + tc.NameTestCase + "; general info:" + tc.GeneralInfo + "; test question:" + tc.TestQuestion + "; scale type:" + scale
                                   + "; active learning:" + activeLearning + "; initial threshold:" + tc.initialThreshold + "; user interval:" + tc.userThreshold + "; database path:" + tc.dbPath + "; eligible user types: " + listOfUsertypes);
                    file.WriteLine("IdGroup; Path; IsReference; IdGroupHasImage; PatientName");

                    foreach (GroupImage image in listgroupImage)
                    {
                        file.WriteLine(image.Idgroup + "; " + image.Path + "; " + image.IsReference + "; " + image.IdGroupHasImage + "; " + image.PatienteName + ";");
                        totalAmountOfImages++;
                    }
                    file.WriteLine("total amount of images in testcase: " + totalAmountOfImages);
                }
            }
            catch (Exception) { }
        }
        public static bool SaveLabelContinuous(List <LableScaleContinuous> Listlablecontinuous)
        {
            if (Listlablecontinuous.Count == 0)
            {
                return(false);
            }
            Class.manageImg managerView = HttpContext.Current.Session["managerView"] as Class.manageImg;
            Class.User      user        = HttpContext.Current.Session["User"] as Class.User;
            Result          res         = null;
            int             index       = managerView.currentPageIndex;

            foreach (LableScaleContinuous lb in Listlablecontinuous)
            {
                // save labels in current session
                for (int i = 0; i < managerView.allImages[index].Count; i++)
                {
                    if (managerView.allImages[index][i].IdGroupImage == lb.IdGroupImage)
                    {
                        for (int c = 0; c < managerView.allImages[index][i].LableContinuous.Count; c++)
                        {
                            if (managerView.allImages[index][i].LableContinuous[c].IdLable == lb.IdLable)
                            {
                                managerView.allImages[index][i].LableContinuous[c].Lable = lb.Lable;
                            }
                        }
                    }
                }


                if (lb.IdGroupImage != 0)
                {
                    LableScaleContinuous lable = new LableScaleContinuous();
                    lable.Lable             = lb.Lable;
                    lable.IdGroupImage      = lb.IdGroupImage;
                    lable.IdUser            = Convert.ToInt64(user.Id_user);
                    lable.IdScaleContinuous = lb.IdScaleContinuous;
                    res = DataAccessTestCase.InsertLableScaleContinuous(lable);
                }
            }

            return(res.result);
        }
        public static void SaveLabelDiscrete(List <LableScaleDiskrete> Listlablediscrete)
        {
            Class.manageImg managerView = HttpContext.Current.Session["managerView"] as Class.manageImg;


            if (Listlablediscrete.Count == 0)
            {
                return;
            }
            // discrete label wird hier gespeichert
            Class.User user  = HttpContext.Current.Session["User"] as Class.User;
            Result     res   = null;
            int        index = managerView.currentPageIndex;

            foreach (LableScaleDiskrete lb in Listlablediscrete)
            {
                // save labels in current session
                for (int i = 0; i < managerView.allImages[index].Count; i++)
                {
                    if (managerView.allImages[index][i].IdGroupImage == lb.IdGroupImage)
                    {
                        managerView.allImages[index][i].LableDiscrete = lb.Lable;
                    }
                }



                if (lb.IdGroupImage != 0)
                {
                    LableScaleDiskrete lable = new LableScaleDiskrete();
                    lable.Lable        = lb.Lable;
                    lable.IdGroupImage = lb.IdGroupImage;
                    lable.IdUser       = Convert.ToInt64(user.Id_user);
                    res = DataAccessTestCase.InsertLableScaleDiskrete(lable);
                }
            }
        }
        // takes selected type scale continuous from the page
        public List <long> GetSelectedTypeScaleContinuous()
        {
            // check for duplicate descriptions, add the version to the list and remove duplicates
            for (int i = 0; i < tsc.Count(); i++)
            {
                tsc[i].scaleVersions = new List <string>();
                tsc[i].scaleVersions.Add(tsc[i].verScaleCont + "");

                for (int c = i + 1; c < tsc.Count(); c++)
                {
                    if (tsc[i].DescriptionScaleContinuous == tsc[c].DescriptionScaleContinuous)
                    {
                        tsc[i].scaleVersions.Add(tsc[c].verScaleCont + "");
                        tsc.RemoveAt(c);
                        c--;
                    }
                }
            }
            //------------------------------------------------------------------------------------

            List <TypScaleContinuous> tsc2 = DataAccessTestCase.getScaleContinuous();
            List <long> List = new List <long>();



            // retrieve the selected continuous scale versions from javascript
            ScriptManager.RegisterStartupScript(this, GetType(), "fUpdateTable", "fUpdateTable();", true);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var           json = HiddenFieldScaleVersions.Value;
            List <string> scaleVersionsCont = serializer.Deserialize <List <string> >(json);


            if (rblTypeScale.SelectedValue == "1")
            {
                // get the corresponding versionIDs
                for (int i = 0; i < tsc2.Count; i++)
                {
                    for (int c = 0; c < tsc.Count; c++)
                    {
                        if ((tsc2[i].DescriptionScaleContinuous == tsc[c].DescriptionScaleContinuous))
                        {
                            for (int z = 0; z < tsc[c].scaleVersions.Count; z++)
                            {
                                if (tsc2[i].verScaleCont == int.Parse(scaleVersionsCont[c]))
                                {
                                    if (int.Parse(scaleVersionsCont[c]) > -1)
                                    {
                                        List.Add(tsc2[i].ID_TypScaleContinuous);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            ////---------------------- old version ------------------------------//

            //for (int i = 0; i < cbxContinuousScale.Items.Count; i++)
            //{

            //    if (cbxContinuousScale.Items[i].Selected)
            //    {
            //        List.Add(Convert.ToInt64(cbxContinuousScale.Items[i].Value));

            //    }

            //}
            ////----------------------------------------------------------------//


            return(List);
        }
        public void ThreadRun()
        {
            // create the complete loop-over structue
            // get amount of looped over image pages, get amount of images per page ==> very convoluted ==> trick: first create List<List> of allImages and then count amount of outer and inner List-length

            // loop over all groups

            List <Class.Group> groupsTC = DataAccess.DataAccessTestCase.getGroupFromIdTestCase(IDTestcase);

            List <TypScaleContinuous> listScaleContinous;
            TypScaleDiscrete          scaleDiscrete;
            List <PackageImage>       pi;
            List <string>             images = new List <string>();

            var extensions = new List <String> {
                ".dcm", ".DCM", ".ima", ".IMA", ".mhd", ".MHD"
            };

            // check if scale is discrete or cont
            if (tc.DiskreteScale)
            {
                scaleDiscrete      = DataAccess.DataAccessTestCase.TypeScaleDiscreteFromIdTestCase(tc.IDTestcase);
                listScaleContinous = new List <TypScaleContinuous>();
            }
            else
            {
                scaleDiscrete      = new TypScaleDiscrete();
                listScaleContinous = DataAccessTestCase.TypeScaleContinuousFromIdTestCase(tc.IDTestcase);
            }


            string path       = "";
            string pathIn     = Constant.pathALinitialInput + string.Format("{0:D4}", tc.IDTestcase) + ".csv";
            string pathInUser = Constant.pathALuserInput + string.Format("{0:D4}", tc.IDTestcase) + "_User" + string.Format("{0:D4}", usr.Id_user) + ".csv";

            bool mode = false;


            // checks if files exist and set file path by following priority: user > initial; if no files exist start in standard mode
            if (tc.ActiveLearning)
            {
                if (System.IO.File.Exists(pathInUser))          // high priority
                {
                    mode = true;
                    path = pathInUser;
                }
                else if (System.IO.File.Exists(pathIn))         // low priority
                {
                    mode = true;
                    path = pathIn;
                }
                else
                {
                    mode = false;           // (redundant); active learning activated, but no optimization files yet
                }
            }
            else
            {
                mode = false;               // (redundant); active learning deactivated
            }
            //-------------------------------------------------------------------------------------------------------------------------------------



            // standard procedure: normal case (no active learning)
            {
                foreach (Class.Group group in groupsTC)
                {
                    List <GroupImage> listgroupImage   = DataAccessTestCase.GetGrouphasImageFromGroup(group.IdGroup, usr.Id_user);
                    List <string>     listNamePatiente = DataAccessTestCase.GetNamePatiente(group.IdGroup);

                    int index             = 0;
                    int indexRelReference = 0;


                    switch (group.PageStyle)
                    {
                    case 0:
                    {
                        iNImages = listgroupImage.Count;                // all images of group on one page
                        break;
                    }

                    case 1:
                    {
                        iNImages = group.ImagesPerPage;                 // amount defined by user
                        break;
                    }

                    default:
                        iNImages = listgroupImage.Count;                // default all images of group on one page
                        break;
                    }



                    foreach (string NamePatience in listNamePatiente)
                    {
                        IEnumerable <GroupImage> listImageReference = from p in listgroupImage
                                                                      where p.PatienteName.ToUpper() == NamePatience.ToUpper() &&
                                                                      p.IsReference == true
                                                                      select p;



                        IEnumerable <GroupImage> listImagePatient = from p in listgroupImage
                                                                    where p.PatienteName.ToUpper() == NamePatience.ToUpper() &&
                                                                    p.IsReference == false
                                                                    select p;

                        index++;
                        pi = new List <PackageImage>();
                        int  page           = 0;
                        bool referenceAdded = false;

                        foreach (GroupImage groupImg in listImagePatient)
                        {
                            PackageImage pack = new PackageImage();
                            pack.GroupId = groupImg.Idgroup;

                            pack.IdGroupImage     = groupImg.IdGroupHasImage;
                            pack.Path             = groupImg.Path;
                            pack.Lenght           = System.IO.Directory.EnumerateFiles(tc.dbPath + "\\" + pack.Path, "*.*", SearchOption.AllDirectories).Where(s => Constant.lsExtensions.Any(e => s.EndsWith(e))).Count();
                            pack.DiskreteScale    = tc.DiskreteScale;
                            pack.MinDiskreteScale = tc.MinDiskreteScale;
                            pack.MaxDiskreteScale = tc.MaxDiskreteScale;
                            pack.ContinuousScale  = tc.DiskreteScale == false ? true : false;
                            pack.Index            = index;
                            pack.dbPath           = tc.dbPath;
                            pack.LableDiscrete    = groupImg.LableDiscrete;
                            pi.Add(pack);

                            if ((group.GroupHasReference) && (!referenceAdded) && (!group.ReferenceIsGlobal))
                            {
                                // referenze bild wird geladen
                                GroupImage giRef = listImageReference.Where(p => p.PatienteName.ToUpper().Trim() == groupImg.PatienteName.ToUpper().Trim()).FirstOrDefault();

                                // alle infos zum referenz bild werden in die variable pack ref gespeichert
                                PackageImage packRef = new PackageImage();
                                packRef.IdGroupImage = giRef.IdGroupHasImage;
                                packRef.Path         = giRef.Path;

                                packRef.IsReference      = true;
                                packRef.Lenght           = System.IO.Directory.EnumerateFiles(tc.dbPath + "\\" + packRef.Path, "*.*", SearchOption.AllDirectories).Where(s => extensions.Any(e => s.EndsWith(e))).Count();
                                packRef.DiskreteScale    = tc.DiskreteScale;
                                packRef.MinDiskreteScale = tc.MinDiskreteScale;
                                packRef.MaxDiskreteScale = tc.MaxDiskreteScale;
                                packRef.ContinuousScale  = tc.DiskreteScale == false ? true : false;
                                packRef.IsReference      = giRef.IsReference;
                                packRef.Index            = index;
                                packRef.PageStyle        = group.PageStyle;
                                packRef.dbPath           = tc.dbPath;
                                pi.Add(packRef);
                                referenceAdded = true;
                            }

                            if (group.ReferenceIsGlobal)
                            {
                                pack.ReferenceGlobal = true;
                                if (tc.DiskreteScale)
                                {
                                    GlobalReference reference = new GlobalReference();
                                    reference.PathImageMax = scaleDiscrete.PathImageMax;
                                    reference.PathImageMin = scaleDiscrete.PathImageMin;

                                    reference.DescriptionScale = scaleDiscrete.DescriptionScaleDiscrete;
                                    reference.ID_TypScale      = scaleDiscrete.ID_TypScaleDiscrete;
                                    reference.Idgroup          = groupImg.Idgroup;
                                    pack.GlobalReferences.Add(reference);

                                    pack.PathWorseGlobalDiscrete = scaleDiscrete.PathImageMin;
                                    pack.PathBestGlobalDiscrete  = scaleDiscrete.PathImageMax;
                                }
                                else
                                {
                                    foreach (TypScaleContinuous typ in listScaleContinous)
                                    {
                                        GlobalReference reference = new GlobalReference();
                                        reference.PathImageMax     = typ.PathImageMax;
                                        reference.PathImageMin     = typ.PathImageMin;
                                        reference.DescriptionScale = typ.DescriptionScaleContinuous;
                                        reference.ID_TypScale      = typ.ID_TypScaleContinuous;
                                        reference.Idgroup          = groupImg.Idgroup;
                                        pack.GlobalReferences.Add(reference);

                                        typ.PathImageMin = typ.PathImageMin;
                                        typ.PathImageMax = typ.PathImageMax;
                                    }
                                }
                            }
                            else
                            {
                                pack.ReferenceGlobal = false;
                            }

                            if (pack.IsReference)
                            {
                                indexRelReference = index;
                            }
                            else
                            {
                                pack.IndexRelReference = indexRelReference;
                            }

                            // nimmt die kontinuierlichen skalen wenn ausgewahlt
                            if (pack.ContinuousScale)
                            {
                                pack.TypeScaleContinuous = listScaleContinous as List <TypScaleContinuous>;
                                pack.LableContinuous     = DataAccessTestCase.GetLableContinuous(pack.IdGroupImage, usr.Id_user, listScaleContinous);
                            }

                            pack.PageStyle = group.PageStyle;
                            page++;

                            if ((page >= iNImages) && (pack.PageStyle == 1))
                            {
                                allImages.Add(pi);
                                referenceAdded = false;
                                pi             = new List <PackageImage>();
                                page           = 0;
                            }
                        }
                        if (pi.Count > 0)
                        {
                            allImages.Add(pi);
                        }
                    }
                }
            }


            iNGroups = allImages.Count();
            List <PackageImage> pilocal = new List <PackageImage>();



            //--------- shuffle images ---------------------

            Shuffle(allImages);         // shuffle pages

            for (int i = 0; i < allImages.Count(); i++)
            {       // shuffle images on page
                Shuffle(allImages[i]);
            }
            //-----------------------------------------------



            // put reference image at first position
            for (int i = 0; i < allImages.Count(); i++)
            {
                for (int c = 1; c < allImages[i].Count(); c++)
                {
                    if (allImages[i][c].IsReference)
                    {
                        PackageImage temp = new PackageImage();
                        temp            = allImages[i][0];
                        allImages[i][0] = allImages[i][c];
                        allImages[i][c] = temp;
                    }
                }
            }


            //--------------------------------------------------------- active learning ----------------------------------------------------------------------------//

            if (mode) // if active learning is activated and files have been found -> realign allImages in accordance to matlab output
            {
                // schaut ob es ein path gibt (redundant)
                if (System.IO.File.Exists(path))
                {
                    // read image paths into list
                    using (StreamReader streamReader = new StreamReader(path))
                    {
                        string currentLine;

                        while ((currentLine = streamReader.ReadLine()) != null)
                        {
                            if (currentLine != "")
                            {
                                images.Add(currentLine.TrimEnd(';')); // remove semicolon and add image path
                            }
                        }

                        images.RemoveAt(0); // remove first entry (number of optimizations)
                    }


                    List <PackageImage> remainingImages   = new List <PackageImage>();
                    List <PackageImage> prioritizedImages = new List <PackageImage>();

                    // get prioritized images from matlab optimization output
                    for (int i = 0; i < images.Count; i++)
                    {
                        prioritizedImages.Add(getImage(images[i]));
                    }

                    // retrieve remaining (not yet labelled) images
                    for (int i = 0; i < allImages.Count; i++)
                    {
                        for (int c = 0; c < allImages[i].Count; c++)
                        {
                            if ((!allImages[i][c].IsReference) && (allImages[i][c].Path != "")) // dont consider local reference images
                            {
                                prioritizedImages.Add(allImages[i][c]);
                            }
                        }
                    }


                    // realign allImages in correspondence with list from matlab file
                    List <List <PackageImage> > tempAllimages = new List <List <PackageImage> >();
                    List <PackageImage>         tempPage      = new List <PackageImage>();

                    int counter = 0;  // pageindex

                    // adds local reference on page 1 if needed
                    if ((groupsTC[0].GroupHasReference) && (!groupsTC[0].ReferenceIsGlobal))
                    {
                        tempPage.Add(allImages[0][0]);        // if local reference has been added as first image to the page previously
                    }


                    for (int i = 0; i < prioritizedImages.Count; i++)
                    {
                        tempPage.Add(prioritizedImages[i]);

                        if (counter < iNImages)
                        {              // number of imagers per page has been reached
                            tempAllimages.Add(tempPage);
                            counter++; // next page
                            tempPage = new List <PackageImage>();

                            // adds reference on new page
                            if ((groupsTC[0].GroupHasReference) && (!groupsTC[0].ReferenceIsGlobal))
                            {
                                tempPage.Add(allImages[0][0]);
                            }
                            counter = 0;
                        }
                    }

                    allImages = tempAllimages;     // change allimages
                }
            }

            //------------------------------------------------------------------------------------------------------------------------------------------------------//
        }
        public static string getListOfPackageImage(int index)

        {
            Class.manageImg managerView = HttpContext.Current.Session["managerView"] as Class.manageImg;
            managerView.currentPageIndex = index;
            HttpContext.Current.Session["managerView"] = managerView;

            ViewImage_ that = HttpContext.Current.Session["viewImage"] as ViewImage_;

            that.updateReference(index);

            // set default values
            managerView.allImages[index][0].getUnlabelled = new int[] { -1, -1 };
            managerView.allImages[index][0].getPercentage = "-";


            if (managerView.tc.ActiveLearning) // when active learning is enabled, check if threshold is reached
            {
                if (DataAccess.DataAccessTestCase.checkThreshold(managerView))
                {
                    return("alert('Active learning procedure has been executed, page index will be reset');  setTimeout(function(){ Reset=true; }, 3000);");
                }
            }


            if (index >= 0 && index <= managerView.iNGroups)
            {
                managerView.sCurrentImageFolder = new List <String>(managerView.allImages[index].Count);
                for (var i = 0; i < managerView.allImages[index].Count; i++)
                {
                    managerView.sCurrentImageFolder.Add(null);
                    managerView.sCurrentImageFolder[i] = managerView.tc.dbPath + "\\" + managerView.allImages[index][i].Path.Replace('/', '\\'); //- Martin
                }


                // get the labelscales
                for (int i = 0; i < managerView.allImages[index].Count; i++)
                {
                    if (managerView.tc.DiskreteScale)
                    {
                        managerView.allImages[index][i].LableDiscrete = DataAccessTestCase.GetDiscreteLabel(managerView.IDUser, managerView.allImages[index][i].IdGroupImage);//pcw
                    }
                    else
                    {
                        managerView.allImages[index][i].LableContinuous = DataAccessTestCase.GetLableContinuous(managerView.allImages[index][i].IdGroupImage, managerView.IDUser, managerView.allImages[index][i].TypeScaleContinuous);//pcw
                    }
                }



                List <String> sPath = managerView.sCurrentImageFolder;
                if (sPath == null)
                {
                    throw new ArgumentException("path variable in manageImg is not specified!");
                }
                else
                {
                    // get paths and dimension of every individual image
                    for (int i = 0; i < managerView.allImages[index].Count; i++)
                    {
                        managerView.allImages[index][i].imagePaths = (System.IO.Directory.EnumerateFiles(sPath[i], "*.*", SearchOption.AllDirectories).Where(s => Constant.lsExtensions.Any(e => s.EndsWith(e)))).ToArray();
                        Array.Sort(managerView.allImages[index][i].imagePaths);
                        int[]            iSize    = new int[] { 0, 0, 0 };
                        string           pfad     = managerView.allImages[index][i].imagePaths[0];
                        itk.simple.Image itkImage = SimpleITK.ReadImage(pfad);              // bei DICOM werden nur die Dimensionen des ersten Bildes ausgelesen, diese sind bei den anderen Schichten identisch

                        VectorUInt32 UInt32Size = itkImage.GetSize();
                        iSize[0] = unchecked ((int)UInt32Size[0]);
                        iSize[1] = unchecked ((int)UInt32Size[1]);

                        if (managerView.allImages[index][i].imagePaths.Length > 1)// for DICOM files
                        {
                            iSize[2] = managerView.allImages[index][i].imagePaths.Length;
                        }
                        else if (managerView.allImages[index][i].imagePaths.Length == 1)//
                        {
                            iSize[2] = unchecked ((int)UInt32Size[2]);
                            iSize[2]--;
                        }
                        managerView.allImages[index][i].imageDimensions = iSize;
                    }
                }



                // get index of the next/previous page with not completely labelled images
                try {
                    managerView.allImages[index][0].getNumOfPages = managerView.allImages.Count();
                    managerView.allImages[index][0].getUnlabelled = getUnlabelled(index);
                    managerView.allImages[index][0].getPercentage = getCurrPercentage();
                }catch (ArgumentOutOfRangeException ex) {
                    return("alert('An error occurred while trying to load the image package, please contact the administrator');");
                }

                //Obfuscate image paths

                for (int c = 0; c < managerView.allImages[index].Count; c++)
                {
                    for (int z = 0; z < managerView.allImages[index][c].imagePaths.Length; z++)
                    {
                        managerView.allImages[index][c].imagePaths[z] = obfuscate(managerView.allImages[index][c].imagePaths[z]);
                    }
                }

                // put the array in the JSON format
                var json = new JavaScriptSerializer().Serialize(managerView.allImages[index]);


                return(json);
                //return managerView.allImages[index];
            }
            else
            {
                return(null);
            }
        }