// GET: Defect
 public ActionResult AddDefect()
 {
     if ((Session["userID"]) == null)
     {
         return(RedirectToAction("Index", "Login"));
     }
     if (Convert.ToInt32(Session["Defect_SIT"]) == 1)
     {
         DefectModel model  = new DefectModel();
         int         SIT_ID = Convert.ToInt32(Session["SIT_ID"]);
         var         SIT    = db.SITs.Where(m => m.SIT_ID == SIT_ID).FirstOrDefault();
         var         user   = db.Users.Where(m => m.User_ID == SIT.Dev_ID).FirstOrDefault();
         model.TaskName = SIT.Name;
         model.DevName  = user.User_Name;
         return(View(model));
     }
     else
     {
         int         SubID = Convert.ToInt32(Session["SubID"]);
         DefectModel model = new DefectModel();
         var         item  = db.SubTasks.Where(m => m.SubID == SubID).FirstOrDefault();
         var         item2 = db.Tasks.Where(m => m.TaskID == item.TaskID).FirstOrDefault();
         var         item3 = db.Users.Where(m => m.User_ID == item.SubDevID).FirstOrDefault();
         model.Sub_ID      = SubID;
         model.SubTaskName = item.SubName;
         model.TaskName    = item2.TaskName;
         model.DevName     = item3.User_Email;
         return(View(model));
     }
 }
Exemple #2
0
        static DefectModel LoadAndPrepareDefectMap(string path, bool flipX, bool flipY, bool transpose)
        {
            Image Defects = Image.FromFilePatient(50, 500,
                                                  path,
                                                  HeaderlessDims,
                                                  (int)HeaderlessOffset,
                                                  ImageFormatsHelper.StringToType(HeaderlessType));

            if (flipX)
            {
                Defects = Defects.AsFlippedX();
            }
            if (flipY)
            {
                Defects = Defects.AsFlippedY();
            }
            if (transpose)
            {
                Defects = Defects.AsTransposed();
            }

            DefectModel Model = new DefectModel(Defects, 4);

            Defects.Dispose();

            return(Model);
        }
        public ActionResult SaveData(DefectModel model)
        {
            var i = db.Defects.Where(m => m.Defect_ID == model.Defect_ID).FirstOrDefault();

            i.Detail       = model.Detail;
            i.SendDate     = model.SendDate;
            i.UpdateDate   = DateTime.Now;
            i.Comment_Dev  = model.Comment_Dev;
            i.Comment_Test = model.Comment_Test;
            if (i.Status != 0 || Convert.ToInt32(Session["userID"]) != model.CreateBy)
            {
                if (model.StatusDev.ToString() == "กำลังแก้ไข" && model.CreateBy != Convert.ToInt32(Session["userID"]))
                {
                    i.Status = 1;
                }
                else if (model.StatusDev.ToString() == "แก้ไขแล้ว" && model.CreateBy != Convert.ToInt32(Session["userID"]))
                {
                    i.Status = 2;
                }
                else if (model.StatusTest.ToString() == "ปิด" && model.CreateBy == Convert.ToInt32(Session["userID"]))
                {
                    i.Status = 3;
                }
                else if (model.StatusTest.ToString() == "แก้ไขใหม่" && model.CreateBy == Convert.ToInt32(Session["userID"]))
                {
                    i.Status = 4;
                }
                i.UpdateBy = Convert.ToInt32(Session["userID"]);
                db.SaveChanges();
                Session["Save_Defect"] = 1;
                return(RedirectToAction("DetailDefect", "Defect", new { DefectID = i.Defect_ID }));
            }
            else if (Convert.ToInt32(Session["userID"]) == model.CreateBy)
            {
                if (model.AttachFile != null)
                {
                    var      Upload = Upload_Defect(model.AttachFile);
                    string[] txt    = Upload.Split(",".ToCharArray());
                    i.AttachFile = txt[0];
                    i.AttachShow = txt[1];
                }
                i.UpdateBy = Convert.ToInt32(Session["userID"]);
                db.SaveChanges();
                return(RedirectToAction("ShowDefect", "Defect"));
            }
            return(RedirectToAction("ShowDefect", "Defect"));
        }
Exemple #4
0
        static void Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            //if (!Debugger.IsAttached)
            //    Debugger.Launch();

            if (args.Length < 3)
            {
                return;
            }

            DeviceID = int.Parse(args[0]) % GPU.GetDeviceCount();
            PipeName = args[1];
            bool DebugMode = bool.Parse(args[2]);

            GPU.SetDevice(DeviceID);

            Console.WriteLine($"Running on GPU #{DeviceID} ({GPU.GetFreeMemory(DeviceID)} MB free) through {PipeName}\n");

            Formatter = new BinaryFormatter();

            Heartbeat = new Thread(new ThreadStart(() =>
            {
                if (!DebugMode)
                {
                    while (true)
                    {
                        try
                        {
                            NamedPipeClientStream PipeHeartbeat = new NamedPipeClientStream(".", PipeName + "_heartbeat", PipeDirection.In);
                            PipeHeartbeat.Connect(5000);

                            PipeHeartbeat.Dispose();
                        }
                        catch
                        {
                            if (!Terminating)
                            {
                                Process.GetCurrentProcess().Kill();
                            }
                        }
                    }
                }
            }));
            Heartbeat.Start();

            while (true)
            {
                PipeReceive = new NamedPipeClientStream(".", PipeName + "_out", PipeDirection.In);
                PipeReceive.Connect();

                NamedSerializableObject Command = (NamedSerializableObject)Formatter.Deserialize(PipeReceive);

                PipeReceive.Dispose();

                Console.WriteLine($"Received \"{Command.Name}\", with {Command.Content.Length} arguments, for GPU #{GPU.GetDevice()}, {GPU.GetFreeMemory(DeviceID)} MB free");

                try
                {
                    Stopwatch Watch = new Stopwatch();
                    Watch.Start();

                    if (Command.Name == "Exit")
                    {
                        Movie.WriteAverageAsync?.Wait();

                        SendSuccessStatus(true);
                        Process.GetCurrentProcess().Kill();

                        return;
                    }
                    else if (Command.Name == "Ping")
                    {
                        Console.WriteLine("Ping!");
                    }
                    else if (Command.Name == "SetHeaderlessParams")
                    {
                        HeaderlessDims   = (int2)Command.Content[0];
                        HeaderlessOffset = (long)Command.Content[1];
                        HeaderlessType   = (string)Command.Content[2];

                        Console.WriteLine($"Set headerless parameters to {HeaderlessDims}, {HeaderlessOffset}, {HeaderlessType}");
                    }
                    else if (Command.Name == "LoadGainRef")
                    {
                        GainRef?.Dispose();
                        DefectMap?.Dispose();

                        string GainPath    = (string)Command.Content[0];
                        bool   FlipX       = (bool)Command.Content[1];
                        bool   FlipY       = (bool)Command.Content[2];
                        bool   Transpose   = (bool)Command.Content[3];
                        string DefectsPath = (string)Command.Content[4];

                        if (!string.IsNullOrEmpty(GainPath))
                        {
                            GainRef = LoadAndPrepareGainReference(GainPath, FlipX, FlipY, Transpose);
                        }
                        if (!string.IsNullOrEmpty(DefectsPath))
                        {
                            DefectMap = LoadAndPrepareDefectMap(DefectsPath, FlipX, FlipY, Transpose);
                        }

                        Console.WriteLine($"Loaded gain reference and defect map: {GainRef}, {FlipX}, {FlipY}, {Transpose}, {DefectsPath}");
                    }
                    else if (Command.Name == "LoadStack")
                    {
                        OriginalStack?.Dispose();

                        string  Path           = (string)Command.Content[0];
                        decimal ScaleFactor    = (decimal)Command.Content[1];
                        int     EERGroupFrames = (int)Command.Content[2];

                        HeaderEER.GroupNFrames = EERGroupFrames;

                        OriginalStack      = LoadAndPrepareStack(Path, ScaleFactor);
                        OriginalStackOwner = Helper.PathToNameWithExtension(Path);

                        Console.WriteLine($"Loaded stack: {OriginalStack}, {ScaleFactor}");
                    }
                    else if (Command.Name == "MovieProcessCTF")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieCTF Options = (ProcessingOptionsMovieCTF)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                        {
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");
                        }

                        Movie M = new Movie(Path);
                        M.ProcessCTF(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Processed CTF for {Path}");
                    }
                    else if (Command.Name == "MovieProcessMovement")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieMovement Options = (ProcessingOptionsMovieMovement)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                        {
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");
                        }

                        Movie M = new Movie(Path);
                        M.ProcessShift(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Processed movement for {Path}");
                    }
                    else if (Command.Name == "MovieExportMovie")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieExport Options = (ProcessingOptionsMovieExport)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                        {
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");
                        }

                        Movie M = new Movie(Path);
                        M.ExportMovie(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Exported movie for {Path}");
                    }
                    else if (Command.Name == "MovieExportParticles")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsParticlesExport Options = (ProcessingOptionsParticlesExport)Command.Content[1];
                        float2[] Coordinates = (float2[])Command.Content[2];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                        {
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");
                        }

                        Movie M = new Movie(Path);
                        M.ExportParticles(OriginalStack, Coordinates, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Exported {Coordinates.Length} particles for {Path}");
                    }
                    else if (Command.Name == "TomoProcessCTF")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieCTF Options = (ProcessingOptionsMovieCTF)Command.Content[1];

                        TiltSeries T = new TiltSeries(Path);
                        T.ProcessCTFSimultaneous(Options);
                        T.SaveMeta();

                        Console.WriteLine($"Processed CTF for {Path}");
                    }
                    else if (Command.Name == "TomoExportParticles")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsTomoSubReconstruction Options = (ProcessingOptionsTomoSubReconstruction)Command.Content[1];
                        float3[] Coordinates = (float3[])Command.Content[2];
                        float3[] Angles      = Command.Content[3] != null ? (float3[])Command.Content[3] : null;

                        TiltSeries T = new TiltSeries(Path);
                        T.ReconstructSubtomos(Options, Coordinates, Angles);
                        T.SaveMeta();

                        Console.WriteLine($"Exported {Coordinates.Length} particles for {Path}");
                    }
                    else if (Command.Name == "MPAPreparePopulation")
                    {
                        string Path = (string)Command.Content[0];

                        MPAPopulation = new Population(Path);

                        foreach (var species in MPAPopulation.Species)
                        {
                            Console.Write($"Preparing {species.Name} for refinement... ");

                            species.PrepareRefinementRequisites(true, DeviceID);

                            Console.WriteLine("Done.");
                        }
                    }
                    else if (Command.Name == "MPARefine")
                    {
                        string Path                        = (string)Command.Content[0];
                        string WorkingDirectory            = (string)Command.Content[1];
                        string LogPath                     = (string)Command.Content[2];
                        ProcessingOptionsMPARefine Options = (ProcessingOptionsMPARefine)Command.Content[3];
                        DataSource Source                  = (DataSource)Command.Content[4];

                        Movie Item = null;

                        if (Helper.PathToExtension(Path).ToLower() == ".tomostar")
                        {
                            Item = new TiltSeries(Path);
                        }
                        else
                        {
                            Item = new Movie(Path);
                        }

                        GPU.SetDevice(DeviceID);

                        Item.PerformMultiParticleRefinement(WorkingDirectory, Options, MPAPopulation.Species.ToArray(), Source, GainRef, DefectMap, (message) =>
                        {
                            Console.WriteLine(message);

                            bool Success = false;
                            int Tries    = 0;
                            while (!Success && Tries < 10)
                            {
                                try
                                {
                                    using (TextWriter Writer = File.AppendText(LogPath))
                                        Writer.WriteLine(message);
                                    Success = true;
                                }
                                catch
                                {
                                    Thread.Sleep(100);
                                    Tries++;
                                }
                            }
                        });

                        Item.SaveMeta();

                        GPU.CheckGPUExceptions();

                        Console.WriteLine($"Finished refining {Item.Name}");
                    }
                    else if (Command.Name == "MPASaveProgress")
                    {
                        string Path = (string)Command.Content[0];

                        MPAPopulation.SaveRefinementProgress(Path);
                    }
                    else if (Command.Name == "TryAllocatePinnedMemory")
                    {
                        long[]   ChunkSizes = (long[])Command.Content[0];
                        IntPtr[] Chunks     = new IntPtr[ChunkSizes.Length];

                        for (int i = 0; i < ChunkSizes.Length; i++)
                        {
                            Chunks[i] = GPU.MallocHostPinned(ChunkSizes[i] / sizeof(float));
                            //Dummies.Add(Helper.ArrayOfSequence(0, (int)(ChunkSizes[i] / sizeof(float) / 2), 1));
                        }

                        GPU.CheckGPUExceptions();

                        //for (int i = 0; i < ChunkSizes.Length; i++)
                        //    GPU.FreeHostPinned(Chunks[i]);

                        Console.WriteLine($"Successfully allocated {ChunkSizes.Sum()} bytes of pinned memory");
                    }

                    Watch.Stop();
                    Console.WriteLine((Watch.ElapsedMilliseconds / 1000f).ToString("F3"));

                    Console.WriteLine("");

                    SendSuccessStatus(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());

                    File.WriteAllText($"worker_{DeviceID}_crash.txt", e.ToString());

                    //Console.Read();

                    SendSuccessStatus(false);
                }
            }
        }
Exemple #5
0
        private async void ButtonMatch_OnClick(object sender, RoutedEventArgs e)
        {
            bool Filter = (bool)CheckFilter.IsChecked;
            bool Manual = (bool)CheckManual.IsChecked;

            #region Get all movies that can potentially be used

            List <Movie> ValidMovies = Movies.Where(v =>
            {
                if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                {
                    return(false);
                }
                if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                {
                    return(false);
                }
                if (v.OptionsCTF == null)
                {
                    return(false);
                }
                return(true);
            }).ToList();

            if (ValidMovies.Count == 0)
            {
                Close?.Invoke();
                return;
            }

            #endregion

            #region Set up progress displays

            NParallel    = Math.Min(ValidMovies.Count, GPU.GetDeviceCount());
            GridSizes    = Helper.ArrayOfConstant(new int3(1), NParallel);
            GridProgress = new int[NParallel];
            GridNames    = new string[NParallel];

            GridControls = Helper.ArrayOfFunction(i => new FlatGridMiniature()
            {
                Width = 256
            }, NParallel);
            GridLabels = Helper.ArrayOfFunction(i => new TextBlock {
                FontSize = 18, Margin = new Thickness(0, 15, 0, 0), HorizontalAlignment = HorizontalAlignment.Center
            }, NParallel);

            for (int n = 0; n < NParallel; n++)
            {
                StackPanel SP = new StackPanel {
                    Orientation = Orientation.Vertical, Margin = new Thickness(15, 0, 15, 0)
                };
                SP.Children.Add(GridControls[n]);
                SP.Children.Add(GridLabels[n]);

                PanelGrids.Children.Add(SP);
            }

            #endregion

            PanelConfiguration.Visibility = Visibility.Collapsed;
            PanelProgress.Visibility      = Visibility.Visible;

            int Completed = 0;
            ProgressOverall.Maximum = ValidMovies.Count;

            await Task.Run(() =>
            {
                #region Load template and make copies for all devices

                Image[] Template = new Image[NParallel];
                {
                    Template[0]           = Image.FromFile(PathTemplate);
                    Template[0].PixelSize = (float)Options.Tasks.TomoMatchTemplatePixel;

                    for (int i = 0; i < Template.Length; i++)
                    {
                        Template[i] = Template[0].GetCopy();
                    }
                }

                #endregion

                #region Load gain reference if needed

                Image[] ImageGain       = new Image[NParallel];
                DefectModel[] DefectMap = new DefectModel[NParallel];
                if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain && File.Exists(Options.Import.GainPath))
                {
                    for (int d = 0; d < NParallel; d++)
                    {
                        ImageGain[d] = MainWindow.LoadAndPrepareGainReference();
                    }
                }
                if (!string.IsNullOrEmpty(Options.Import.DefectsPath) && Options.Import.CorrectDefects && File.Exists(Options.Import.DefectsPath))
                {
                    for (int d = 0; d < NParallel; d++)
                    {
                        DefectMap[d] = MainWindow.LoadAndPrepareDefectMap();
                    }
                }

                #endregion

                object SyncDummy = new object();

                Helper.ForEachGPU(ValidMovies, (item, gpuID) =>
                {
                    if (IsCanceled)
                    {
                        return(true);    // This cancels the iterator
                    }
                    Dispatcher.Invoke(() =>
                    {
                        SetGridSize(gpuID, new int3(1, 1, 1));
                        SetGridProgress(gpuID, 0);
                        SetGridName(gpuID, "Loading data...");
                    });

                    ProcessingOptionsFullMatch MatchOptions = Options.GetProcessingFullMatch();
                    MatchOptions.TemplateName = Helper.PathToName(PathTemplate);

                    #region Load and prepare original movie

                    Image OriginalStack = null;
                    decimal ScaleFactor = 1M / MatchOptions.DownsampleFactor;

                    MapHeader OriginalHeader = MapHeader.ReadFromFile(item.Path);

                    MainWindow.LoadAndPrepareHeaderAndMap(item.Path, ImageGain[gpuID], DefectMap[gpuID], ScaleFactor, out OriginalHeader, out OriginalStack);

                    if (IsCanceled)
                    {
                        OriginalStack?.Dispose();

                        return(true);
                    }

                    #endregion

                    item.MatchFull(OriginalStack, MatchOptions, Template[gpuID], (size, value, name) =>
                    {
                        Dispatcher.Invoke(() =>
                        {
                            SetGridSize(gpuID, size);
                            SetGridProgress(gpuID, value);
                            SetGridName(gpuID, name);
                        });

                        return(IsCanceled);
                    });

                    OriginalStack?.Dispose();

                    Dispatcher.Invoke(() => ProgressOverall.Value = ++Completed);

                    return(false);   // No need to cancel GPU ForEach iterator
                }, 1);
            });

            Close?.Invoke();
        }
Exemple #6
0
 public ViewModel(DefectModel defectModel)
 {
     _defectModel = defectModel;
 }
        public ActionResult Defect_Dev(int SubID)
        {
            DefectModel        model      = new DefectModel();
            List <DefectModel> DefectList = new List <DefectModel>();
            var Defect = db.Defects.Where(m => m.Sub_ID == SubID).OrderBy(m => m.Defect_ID).ToList();

            foreach (var item in Defect)
            {
                var Dev  = db.SubTasks.Where(m => m.SubID == item.Sub_ID).FirstOrDefault();
                var Task = db.Tasks.Where(m => m.TaskID == Dev.TaskID).FirstOrDefault();
                var User = db.Users.Where(m => m.User_ID == Dev.SubDevID).FirstOrDefault();
                model.DevID       = Dev.SubDevID;
                model.TaskName    = Task.TaskName;
                model.SubTaskName = Dev.SubName;
                model.DevName     = User.User_Name;
                if (item.Status == 0)
                {
                    DefectList.Add(new DefectModel
                    {
                        Defect_ID   = item.Defect_ID,
                        Detail      = item.Detail,
                        Status      = item.Status,
                        SendDate    = item.SendDate,
                        AttachShow  = item.AttachShow,
                        Path_Defect = item.AttachFile
                    });
                }
                else if (item.Status == 1)
                {
                    DefectList.Add(new DefectModel
                    {
                        Defect_ID   = item.Defect_ID,
                        Detail      = item.Detail,
                        Status      = item.Status,
                        SendDate    = item.SendDate,
                        AttachShow  = item.AttachShow,
                        Path_Defect = item.AttachFile
                    });
                }
                else if (item.Status == 2)
                {
                    DefectList.Add(new DefectModel
                    {
                        Defect_ID   = item.Defect_ID,
                        Detail      = item.Detail,
                        Status      = item.Status,
                        SendDate    = item.SendDate,
                        AttachShow  = item.AttachShow,
                        Path_Defect = item.AttachFile
                    });
                }
                else if (item.Status == 3)
                {
                    DefectList.Add(new DefectModel
                    {
                        Defect_ID   = item.Defect_ID,
                        Detail      = item.Detail,
                        Status      = item.Status,
                        SendDate    = item.SendDate,
                        AttachShow  = item.AttachShow,
                        Path_Defect = item.AttachFile
                    });
                }
            }
            ViewBag.DataList = DefectList;;
            return(View(model));
        }
 public ActionResult AddDefect(DefectModel model)
 {
     if (Convert.ToInt32(Session["Defect_SIT"]) == 1)
     {
         if (model.DetailList[0] != "")
         {
             int     projectID = Convert.ToInt32(Session["ProjectID"]);
             Defect  d         = new Defect();
             SubTask st        = new SubTask();
             int     SIT_ID    = Convert.ToInt32(Session["SIT_ID"]);
             var     count     = model.DetailList.Count;
             if (count > 1)
             {
                 for (int i = 0; i < count; ++i)
                 {
                     d.Sub_ID     = SIT_ID;
                     d.Detail     = model.DetailList[i].ToString();
                     d.SendDate   = model.SendDateList[i];
                     d.Status     = 0;
                     d.CreateDate = DateTime.Now;
                     d.CreateBy   = Convert.ToInt32(Session["userID"]);
                     d.Project_ID = projectID;
                     if (model.AttachFileList[i] != null)
                     {
                         var      Upload = Upload_Defect(model.AttachFileList[i]);
                         string[] txt    = Upload.Split(",".ToCharArray());
                         d.AttachFile = txt[0];
                         d.AttachShow = txt[1];
                     }
                     db.Defects.Add(d);
                     db.SaveChanges();
                     var SIT = db.SITs.Where(m => m.SIT_ID == SIT_ID).FirstOrDefault();
                     SIT.Defect_SIT = 1;
                     SIT.Status     = 4;
                     db.SaveChanges();
                     var    Email  = db.Users.Where(m => m.User_ID == d.CreateBy).FirstOrDefault();
                     var    Sendto = db.Users.Where(m => m.User_ID == SIT.Dev_ID).FirstOrDefault();
                     string sender = Email.User_Email.ToString();
                     //string sender = "*****@*****.**";
                     string subject  = "Defect หัวข้อ" + st.SubName;
                     string receiver = Sendto.User_Email.ToString();
                     //string receiver = "*****@*****.**";
                     string          mess = "มีข้อผิดพลาดในหัวข้อ" + st.SubName;
                     InboxController ms   = new InboxController();
                     ms.SendEmail(receiver, subject, mess, sender);
                 }
             }
             else
             {
                 d.Sub_ID     = SIT_ID;
                 d.Detail     = model.DetailList[0].ToString();
                 d.SendDate   = model.SendDateList[0];
                 d.Status     = 0;
                 d.CreateDate = DateTime.Now;
                 d.CreateBy   = Convert.ToInt32(Session["userID"]);
                 d.Project_ID = projectID;
                 if (model.AttachFileList[0] != null)
                 {
                     var      Upload = Upload_Defect(model.AttachFileList[0]);
                     string[] txt    = Upload.Split(",".ToCharArray());
                     d.AttachFile = txt[0];
                     d.AttachShow = txt[1];
                 }
                 db.Defects.Add(d);
                 db.SaveChanges();
                 var SIT = db.SITs.Where(m => m.SIT_ID == SIT_ID).FirstOrDefault();
                 SIT.Defect_SIT = 1;
                 SIT.Status     = 4;
                 db.SaveChanges();
                 var    Email  = db.Users.Where(m => m.User_ID == d.CreateBy).FirstOrDefault();
                 var    Sendto = db.Users.Where(m => m.User_ID == SIT.Dev_ID).FirstOrDefault();
                 string sender = Email.User_Email.ToString();
                 //string sender = "*****@*****.**";
                 string subject  = "Defect หัวข้อ" + st.SubName;
                 string receiver = Sendto.User_Email.ToString();
                 //string receiver = "*****@*****.**";
                 string          mess = "มีข้อผิดพลาดในหัวข้อ" + st.SubName;
                 InboxController ms   = new InboxController();
                 ms.SendEmail(receiver, subject, mess, sender);
             }
             return(RedirectToAction("ShowDefect"));
         }
         return(View(new DefectModel
         {
             Error_Detail = "กรุณาใส่ข้อมูลให้ครบถ้วน"
         }));
     }
     else
     {
         if (model.DetailList[0] != "")
         {
             int     projectID = Convert.ToInt32(Session["ProjectID"]);
             Defect  d         = new Defect();
             SubTask st        = new SubTask();
             int     SubID     = Convert.ToInt32(Session["SubID"]);
             var     count     = model.DetailList.Count;
             if (count > 1)
             {
                 for (int i = 0; i < count; ++i)
                 {
                     d.Sub_ID     = model.Sub_ID;
                     d.Detail     = model.DetailList[i].ToString();
                     d.SendDate   = model.SendDateList[i];
                     d.Status     = 0;
                     d.CreateDate = DateTime.Now;
                     d.CreateBy   = Convert.ToInt32(Session["userID"]);
                     d.Project_ID = projectID;
                     if (model.AttachFileList[i] != null)
                     {
                         var      Upload = Upload_Defect(model.AttachFileList[i]);
                         string[] txt    = Upload.Split(",".ToCharArray());
                         d.AttachFile = txt[0];
                         d.AttachShow = txt[1];
                     }
                     db.Defects.Add(d);
                     db.SaveChanges();
                     var s = db.SubTasks.Where(m => m.SubID == model.Sub_ID).FirstOrDefault();
                     s.HaveDefect = 1;
                     s.SubStatus  = 5;
                     s.SubPercent = 25;
                     db.SaveChanges();
                     var    Email  = db.Users.Where(m => m.User_ID == d.CreateBy).FirstOrDefault();
                     var    Sendto = db.Users.Where(m => m.User_ID == s.SubDevID).FirstOrDefault();
                     string sender = Email.User_Email.ToString();
                     //string sender = "*****@*****.**";
                     string subject  = "Defect หัวข้อ" + st.SubName;
                     string receiver = Sendto.User_Email.ToString();
                     //string receiver = "*****@*****.**";
                     string          mess = "มีข้อผิดพลาดในหัวข้อ" + st.SubName;
                     InboxController ms   = new InboxController();
                     ms.SendEmail(receiver, subject, mess, sender);
                 }
             }
             else
             {
                 d.Sub_ID     = model.Sub_ID;
                 d.Detail     = model.DetailList[0].ToString();
                 d.SendDate   = model.SendDateList[0];
                 d.Status     = 0;
                 d.CreateDate = DateTime.Now;
                 d.CreateBy   = Convert.ToInt32(Session["userID"]);
                 d.Project_ID = projectID;
                 if (model.AttachFileList[0] != null)
                 {
                     var      Upload = Upload_Defect(model.AttachFileList[0]);
                     string[] txt    = Upload.Split(",".ToCharArray());
                     d.AttachFile = txt[0];
                     d.AttachShow = txt[1];
                 }
                 db.Defects.Add(d);
                 db.SaveChanges();
                 var s = db.SubTasks.Where(m => m.SubID == model.Sub_ID).FirstOrDefault();
                 s.HaveDefect = 1;
                 s.SubStatus  = 5;
                 db.SaveChanges();
                 var    Email  = db.Users.Where(m => m.User_ID == d.CreateBy).FirstOrDefault();
                 var    Sendto = db.Users.Where(m => m.User_ID == s.SubDevID).FirstOrDefault();
                 string sender = Email.User_Email.ToString();
                 //string sender = "*****@*****.**";
                 string subject  = "Defect หัวข้อ" + st.SubName;
                 string receiver = Sendto.User_Email.ToString();
                 //string receiver = "*****@*****.**";
                 string          mess = "มีข้อผิดพลาดในหัวข้อ" + st.SubName;
                 InboxController ms   = new InboxController();
                 ms.SendEmail(receiver, subject, mess, sender);
             }
             return(RedirectToAction("ShowDefect"));
         }
         return(View(new DefectModel
         {
             Error_Detail = "กรุณาใส่ข้อมูลให้ครบถ้วน"
         }));
     }
 }
        public ActionResult DetailDefect(int DefectID)
        {
            if ((Session["userID"]) == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            DefectModel model   = new DefectModel();
            var         item    = db.Defects.Where(m => m.Defect_ID == DefectID).FirstOrDefault();
            var         SubTask = db.SubTasks.Where(m => m.SubID == item.Sub_ID).FirstOrDefault();

            if (SubTask != null)
            {
                var Task = db.Tasks.Where(m => m.TaskID == SubTask.TaskID).FirstOrDefault();
                var Dev  = db.Users.Where(m => m.User_ID == SubTask.SubDevID).FirstOrDefault();
                model.Defect_ID    = item.Defect_ID;
                model.TaskName     = Task.TaskName;
                model.SubTaskName  = SubTask.SubName;
                model.Detail       = item.Detail;
                model.DevID        = SubTask.SubDevID;
                model.DevName      = Dev.User_Name;
                model.Status       = item.Status;
                model.SendDate     = item.SendDate;
                model.CreateBy     = item.CreateBy;
                model.Comment_Dev  = item.Comment_Dev;
                model.Comment_Test = item.Comment_Test;
                model.AttachShow   = item.AttachShow;
                model.Path_Defect  = item.AttachFile;
                if (item.Status == 1)
                {
                    model.StatusDev = DefectModel.StatusDefectDev.กำลังแก้ไข;
                }
                else if (item.Status == 2)
                {
                    model.StatusDev = DefectModel.StatusDefectDev.แก้ไขแล้ว;
                }
                else if (item.Status == 3)
                {
                    model.StatusTest = DefectModel.StatusDefectTest.ปิด;
                }
                else if (item.Status == 4)
                {
                    model.StatusTest = DefectModel.StatusDefectTest.แก้ไขใหม่;
                }
                return(View(model));
            }
            else
            {
                var SIT      = db.SITs.Where(m => m.SIT_ID == item.Sub_ID).FirstOrDefault();
                var Dev_Name = db.Users.Where(m => m.User_ID == SIT.Dev_ID).FirstOrDefault();
                model.Defect_ID    = item.Defect_ID;
                model.TaskName     = SIT.Name;
                model.SubTaskName  = null;
                model.Detail       = item.Detail;
                model.DevID        = SIT.Dev_ID;
                model.DevName      = Dev_Name.User_Name;
                model.Status       = item.Status;
                model.SendDate     = item.SendDate;
                model.CreateBy     = item.CreateBy;
                model.Comment_Dev  = item.Comment_Dev;
                model.Comment_Test = item.Comment_Test;
                model.Path_Defect  = item.AttachFile;
                model.AttachShow   = item.AttachShow;
                if (item.Status == 1)
                {
                    model.StatusDev = DefectModel.StatusDefectDev.กำลังแก้ไข;
                }
                else if (item.Status == 2)
                {
                    model.StatusDev = DefectModel.StatusDefectDev.แก้ไขแล้ว;
                }
                else if (item.Status == 3)
                {
                    model.StatusTest = DefectModel.StatusDefectTest.ปิด;
                }
                else if (item.Status == 4)
                {
                    model.StatusTest = DefectModel.StatusDefectTest.แก้ไขใหม่;
                }
                return(View(model));
            }
        }
        public ActionResult ShowDefect()
        {
            if ((Session["userID"]) == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            Session["SIT_Defect"] = 0;
            List <DefectModel> DefectList = new List <DefectModel>();
            DefectModel        model      = new DefectModel();
            int projectID = Convert.ToInt32(Session["ProjectID"]);
            var p         = db.Projects.Where(m => m.ProjectID == projectID).FirstOrDefault();

            model.Project_Status = p.Status;
            var item = db.Defects.Where(m => m.Project_ID == projectID).OrderByDescending(s => s.Defect_ID).ToList();

            foreach (var i in item)
            {
                model.CreateBy = i.CreateBy;
                var item2 = db.SubTasks.Where(m => m.SubID == i.Sub_ID).FirstOrDefault();
                if (item2 != null)
                {
                    var item3  = db.Tasks.Where(m => m.TaskID == item2.TaskID).FirstOrDefault();
                    var Dev    = db.Users.Where(m => m.User_ID == item2.SubDevID).FirstOrDefault();
                    var Tester = db.Users.Where(m => m.User_ID == item3.TestID).FirstOrDefault();
                    var QA     = db.Users.Where(m => m.User_ID == item3.QAID).FirstOrDefault();
                    //////////////////////////////////////////////////////////////////
                    int number = 0;
                    var d      = db.Defects.Where(m => m.Sub_ID == i.Sub_ID).ToList();
                    foreach (var c in d)
                    {
                        if (c.Status == 3)
                        {
                            number = number + 1;
                            if (number == d.Count)
                            {
                                var subtask = db.SubTasks.Where(m => m.SubID == c.Sub_ID).FirstOrDefault();
                                subtask.HaveDefect = 0;
                                var Handle = db.ProjectMembers.Where(m => m.UserID == subtask.Handle).FirstOrDefault();
                                if (Handle != null)
                                {
                                    if (Handle.Role == 3)
                                    {
                                        subtask.SubStatus = 1;
                                    }
                                    else if (Handle.Role == 4)
                                    {
                                        subtask.SubStatus = 2;
                                    }
                                    db.SaveChanges();
                                    number = 0;
                                }
                                else
                                {
                                    subtask.SubStatus = 3;
                                    db.SaveChanges();
                                    number = 0;
                                }
                            }
                        }
                    }

                    DefectList.Add(new DefectModel
                    {
                        TaskName    = item3.TaskName,
                        Defect_ID   = i.Defect_ID,
                        SubTaskName = item2.SubName,
                        Detail      = i.Detail,
                        Status      = i.Status,
                        DevName     = Dev.User_Name,
                        TestName    = Tester.User_Name,
                        QAName      = QA.User_Name,
                        CreateBy    = i.CreateBy,
                        SendDate    = i.SendDate
                    });
                }
                else
                {
                    int number = 0;
                    var d      = db.Defects.Where(m => m.Sub_ID == i.Sub_ID).ToList();
                    foreach (var c in d)
                    {
                        if (c.Status == 3)
                        {
                            number = number + 1;
                            if (number == d.Count)
                            {
                                var SI = db.SITs.Where(m => m.SIT_ID == c.Sub_ID).FirstOrDefault();
                                SI.Defect_SIT = 0;
                                var Handle = db.ProjectMembers.Where(m => m.UserID == SI.Handle).FirstOrDefault();
                                if (Handle != null)
                                {
                                    if (Handle.Role == 3)
                                    {
                                        SI.Status = 0;
                                    }
                                    else if (Handle.Role == 4)
                                    {
                                        SI.Status = 1;
                                    }
                                    else if (Handle.Role == 5)
                                    {
                                        SI.Status = 2;
                                    }
                                    db.SaveChanges();
                                    number = 0;
                                }
                                else
                                {
                                    SI.Status = 3;
                                    db.SaveChanges();
                                    number = 0;
                                }
                            }
                        }
                    }
                    var SIT    = db.SITs.Where(m => m.SIT_ID == i.Sub_ID).FirstOrDefault();
                    var User   = db.Users.Where(m => m.User_ID == SIT.Dev_ID).FirstOrDefault();
                    var Tester = db.Users.Where(m => m.User_ID == SIT.Tester_ID).FirstOrDefault();
                    var QA     = db.Users.Where(m => m.User_ID == SIT.QA_ID).FirstOrDefault();
                    DefectList.Add(new DefectModel
                    {
                        Defect_ID   = i.Defect_ID,
                        TaskName    = SIT.Name,
                        SubTaskName = "ไม่มี",
                        Detail      = i.Detail,
                        Status      = i.Status,
                        DevName     = User.User_Name,
                        TestName    = Tester.User_Name,
                        QAName      = QA.User_Name,
                        CreateBy    = i.CreateBy,
                        SendDate    = i.SendDate
                    });
                }
            }
            ViewBag.DataList       = DefectList;
            Session["Save_Defect"] = 0;
            return(View(model));
        }