Beispiel #1
0
        public bool CreateQCPolSourceAll()
        {
            if (Cancel)
            {
                return(false);
            }

            lblStatus.Text = "Starting ... CreateSanitaryQC - CreateQCPolSourceAll";
            Application.DoEvents();

            TVItemService tvItemServiceR = new TVItemService(LanguageEnum.en, user);

            TVItemModel tvItemModelRoot = tvItemServiceR.GetRootTVItemModelDB();

            if (!CheckModelOK <TVItemModel>(tvItemModelRoot))
            {
                return(false);
            }

            TVItemModel tvItemModelCanada = tvItemServiceR.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelRoot.TVItemID, "Canada", TVTypeEnum.Country);

            if (!CheckModelOK <TVItemModel>(tvItemModelCanada))
            {
                return(false);
            }

            TVItemModel tvItemModelQC = tvItemServiceR.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelCanada.TVItemID, "Québec", TVTypeEnum.Province);

            if (!CheckModelOK <TVItemModel>(tvItemModelQC))
            {
                return(false);
            }

            List <TVItemModel> TVItemModelSubsectorList = tvItemServiceR.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelQC.TVItemID, TVTypeEnum.Subsector);

            if (TVItemModelSubsectorList.Count == 0)
            {
                richTextBoxStatus.AppendText("Error: could not find TVItem Subsector for " + tvItemModelQC.TVText + "\r\n");
                return(false);
            }

            List <string> NoSecList = new List <string>()
            {
                "M", "G-00"
            };

            List <TempData.QCSecteurMPol> qcSecteurMPol = new List <TempData.QCSecteurMPol>();

            using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
            {
                qcSecteurMPol = (from c in dbDT.QCSecteurMPols
                                 select c).ToList <TempData.QCSecteurMPol>();
            }

            List <Obs>    obsTypeList = new List <Obs>();
            List <string> sectorList  = new List <string>();
            List <TempData.QCSubsectorAssociation> qcsubsectorAssociationList = new List <TempData.QCSubsectorAssociation>();

            using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
            {
                qcsubsectorAssociationList = (from c in dbDT.QCSubsectorAssociations
                                              select c).ToList <TempData.QCSubsectorAssociation>();
            }

            using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
            {
                sectorList = (from s in dbQC.geo_pollution_p
                              select s.secteur).Distinct().ToList();
            }

            List <string> sectorOrderedList = (from c in sectorList
                                               orderby c
                                               select c).ToList();

            int StartQCCreateSanitarysQC = int.Parse(textBoxQCCreateSanitaryQC.Text);

            int TotalCount = sectorOrderedList.Count();
            int Count      = 0;

            foreach (string sec in sectorOrderedList)
            {
                Count += 1;

                TVItemService                    tvItemService                    = new TVItemService(LanguageEnum.en, user);
                PolSourceSiteService             polSourceSiteService             = new PolSourceSiteService(LanguageEnum.en, user);
                MapInfoService                   mapInfoService                   = new MapInfoService(LanguageEnum.en, user);
                PolSourceObservationService      polSourceObservationService      = new PolSourceObservationService(LanguageEnum.en, user);
                PolSourceObservationIssueService polSourceObservationIssueService = new PolSourceObservationIssueService(LanguageEnum.en, user);

                lblStatus.Text  = (Count * 100 / TotalCount).ToString() + " ... CreateSanitaryQC for sector " + sec;
                lblStatus2.Text = Count + " of " + TotalCount;
                Application.DoEvents();

                textBoxQCCreateSanitaryQC.Text = Count.ToString();

                if (StartQCCreateSanitarysQC > Count)
                {
                    continue;
                }

                if (sec != null)
                {
                    Application.DoEvents();

                    TVItemModel tvItemModelSubsector = new TVItemModel();

                    if (sec.StartsWith("M") || sec.StartsWith("G-00"))
                    {
                    }
                    else
                    {
                        TempData.QCSubsectorAssociation qcsubAss = (from c in qcsubsectorAssociationList
                                                                    where c.QCSectorText == sec
                                                                    select c).FirstOrDefault <TempData.QCSubsectorAssociation>();

                        tvItemModelSubsector = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelQC.TVItemID, qcsubAss.SubsectorText, TVTypeEnum.Subsector);
                        if (!CheckModelOK <TVItemModel>(tvItemModelSubsector))
                        {
                            return(false);
                        }
                    }

                    List <PCCSM.geo_pollution_p> polQCList = new List <PCCSM.geo_pollution_p>();
                    using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
                    {
                        polQCList = (from c in dbQC.geo_pollution_p
                                     where c.secteur == sec &&
                                     c.id_geo_pollution_p != 0 &&
                                     (c.x != null && c.y != null)
                                     //&& c.ex.exlure_importation == false
                                     select c).ToList <PCCSM.geo_pollution_p>();
                    }

                    int countPol      = 0;
                    int totalCountPol = polQCList.Count;
                    foreach (PCCSM.geo_pollution_p pqc in polQCList)
                    {
                        if (Cancel)
                        {
                            return(false);
                        }

                        countPol       += 1;
                        lblStatus2.Text = "Doing " + countPol + " of " + totalCountPol;
                        Application.DoEvents();

                        PolSourceSiteModel polSourceSiteModelNew = new PolSourceSiteModel();

                        string Code = tvItemService.CleanText(pqc.code.ToUpper());
                        List <PolSourceObsInfoEnum> polSourceObsInfoList = GetPolSourceType(Code.Trim(), "--", "QC");

                        string ObservationInfo = (int)polSourceObsInfoList[0] + "," + (int)polSourceObsInfoList[1] + ",";

                        polSourceSiteModelNew.IsPointSource = true;
                        //if (pqc.status == "actif")
                        //{
                        //    polSourceSiteModelNew.IsActive = true;
                        //}
                        //else
                        //{
                        //    polSourceSiteModelNew.IsActive = false;
                        //}
                        polSourceSiteModelNew.Oldsiteid = pqc.id_geo_pollution_p;

                        string SectText = (from c in qcSecteurMPol
                                           where c.geo_pollution_id == pqc.id_geo_pollution_p
                                           select c.Subsector).FirstOrDefault <string>();

                        if (string.IsNullOrWhiteSpace(SectText))
                        {
                            List <MapInfoModel> mapInfoModelList = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)pqc.y, (float)pqc.x, TVTypeEnum.Subsector);

                            foreach (MapInfoModel mapInfoModel in mapInfoModelList)
                            {
                                List <MapInfoPointModel> mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithMapInfoIDDB(mapInfoModel.MapInfoID);

                                List <Coord> coordList2 = new List <Coord>();
                                foreach (MapInfoPointModel mapInfoPointModel in mapInfoPointModelList)
                                {
                                    coordList2.Add(new Coord()
                                    {
                                        Lat = (float)mapInfoPointModel.Lat, Lng = (float)mapInfoPointModel.Lng, Ordinal = mapInfoPointModel.Ordinal
                                    });
                                }

                                if (mapInfoService.CoordInPolygon(coordList2, new Coord()
                                {
                                    Lat = (float)pqc.y, Lng = (float)pqc.x, Ordinal = 0
                                }))
                                {
                                    TVItemModel tvItemModelSS = tvItemService.GetTVItemModelWithTVItemIDDB(mapInfoModel.TVItemID);
                                    SectText = tvItemModelSS.TVText.Substring(0, tvItemModelSS.TVText.IndexOf(" ")).Trim();

                                    using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
                                    {
                                        TempData.QCSecteurMPol qcSecteurMPolExist = (from c in dbDT.QCSecteurMPols
                                                                                     where c.Subsector == SectText &&
                                                                                     c.geo_pollution_id == pqc.id_geo_pollution_p
                                                                                     select c).FirstOrDefault();

                                        if (qcSecteurMPolExist == null)
                                        {
                                            TempData.QCSecteurMPol qcsmpol = new TempData.QCSecteurMPol()
                                            {
                                                geo_pollution_id = pqc.id_geo_pollution_p,
                                                Subsector        = SectText,
                                            };

                                            dbDT.QCSecteurMPols.Add(qcsmpol);
                                            try
                                            {
                                                dbDT.SaveChanges();
                                            }
                                            catch (Exception ex)
                                            {
                                                richTextBoxStatus.AppendText("Error saving new TempData.QCSecteurMPol [" + ex.Message + "]");
                                                return(false);
                                            }
                                        }
                                    }

                                    break;
                                }
                            }

                            if (string.IsNullOrWhiteSpace(SectText))
                            {
                                int   MapInfoID = 0;
                                float MinDist   = 10000000f;
                                foreach (TVItemModel tvItemModel in TVItemModelSubsectorList)
                                {
                                    List <MapInfoPointModel> mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModel.TVItemID, TVTypeEnum.Subsector, MapInfoDrawTypeEnum.Point);

                                    float tempDist = (float)mapInfoService.CalculateDistance(mapInfoPointModelList[0].Lat, mapInfoPointModelList[0].Lng, (double)pqc.y, (double)pqc.x, mapInfoService.R);

                                    if (tempDist < MinDist)
                                    {
                                        MapInfoID = mapInfoPointModelList[0].MapInfoID;
                                        MinDist   = tempDist;
                                    }
                                }

                                MapInfoModel mapInfoModel = mapInfoService.GetMapInfoModelWithMapInfoIDDB(MapInfoID);
                                if (!string.IsNullOrWhiteSpace(mapInfoModel.Error))
                                {
                                    richTextBoxStatus.AppendText("Error [" + mapInfoModel.Error + "]");
                                    return(false);
                                }

                                TVItemModel tvItemModelSS = tvItemService.GetTVItemModelWithTVItemIDDB(mapInfoModel.TVItemID);
                                SectText = tvItemModelSS.TVText.Substring(0, tvItemModelSS.TVText.IndexOf(" ")).Trim();
                            }
                        }

                        if (string.IsNullOrWhiteSpace(SectText))
                        {
                            richTextBoxStatus.AppendText(pqc.y + " " + pqc.x + " " + pqc.id_geo_pollution_p + "\r\n");
                            continue;
                        }

                        tvItemModelSubsector = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelQC.TVItemID, SectText, TVTypeEnum.Subsector);
                        if (!CheckModelOK <TVItemModel>(tvItemModelSubsector))
                        {
                            return(false);
                        }

                        // doing EN TVText
                        string PolSourceSiteTVTextEN = _BaseEnumService.GetEnumText_PolSourceObsInfoEnum(polSourceObsInfoList[0]);
                        if (polSourceObsInfoList.Count > 1)
                        {
                            if (polSourceObsInfoList[1] != PolSourceObsInfoEnum.Error)
                            {
                                PolSourceSiteTVTextEN += " - " + _BaseEnumService.GetEnumText_PolSourceObsInfoEnum(polSourceObsInfoList[1]);
                            }
                        }

                        PolSourceSiteTVTextEN = tvItemService.CleanText(PolSourceSiteTVTextEN + " - " + "      ".Substring(0, 6 - pqc.id_geo_pollution_p.ToString().Length) + pqc.id_geo_pollution_p.ToString());

                        Thread.CurrentThread.CurrentCulture   = new CultureInfo("fr-CA");
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");

                        // Doing FR TVText
                        PolSourceObservationService polSourceObservationService2 = new PolSourceObservationService(LanguageEnum.fr, user);

                        string PolSourceSiteTVTextFR = _BaseEnumService.GetEnumText_PolSourceObsInfoEnum(polSourceObsInfoList[0]);
                        if (polSourceObsInfoList.Count > 1)
                        {
                            if (polSourceObsInfoList[1] != PolSourceObsInfoEnum.Error)
                            {
                                PolSourceSiteTVTextFR += " - " + _BaseEnumService.GetEnumText_PolSourceObsInfoEnum(polSourceObsInfoList[1]);
                            }
                        }

                        PolSourceSiteTVTextFR = tvItemService.CleanText(PolSourceSiteTVTextFR + " - " + "      ".Substring(0, 6 - pqc.id_geo_pollution_p.ToString().Length) + pqc.id_geo_pollution_p.ToString());

                        Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-CA");
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");

                        TVItemModel tvItemModelPolSourceSite = tvItemService.PostCreateTVItem(tvItemModelSubsector.TVItemID, PolSourceSiteTVTextEN, PolSourceSiteTVTextFR, TVTypeEnum.PolSourceSite);
                        if (!CheckModelOK <TVItemModel>(tvItemModelPolSourceSite))
                        {
                            return(false);
                        }

                        List <Coord> coordList = new List <Coord>()
                        {
                            new Coord()
                            {
                                Lat = (float)pqc.y,
                                Lng = (float)pqc.x,
                            }
                        };

                        MapInfoModel mapInfoModelRet = mapInfoService.CreateMapInfoObjectDB(coordList, MapInfoDrawTypeEnum.Point, TVTypeEnum.PolSourceSite, tvItemModelPolSourceSite.TVItemID);
                        if (!CheckModelOK <MapInfoModel>(mapInfoModelRet))
                        {
                            return(false);
                        }

                        polSourceSiteModelNew.PolSourceSiteTVItemID = tvItemModelPolSourceSite.TVItemID;
                        polSourceSiteModelNew.PolSourceSiteTVText   = PolSourceSiteTVTextEN;

                        PolSourceSiteModel polSourceSiteModelRet = polSourceSiteService.GetPolSourceSiteModelWithPolSourceSiteTVItemIDDB(tvItemModelPolSourceSite.TVItemID);
                        if (!string.IsNullOrWhiteSpace(polSourceSiteModelRet.Error))
                        {
                            polSourceSiteModelRet = polSourceSiteService.PostAddPolSourceSiteDB(polSourceSiteModelNew);
                            if (!CheckModelOK <PolSourceSiteModel>(polSourceSiteModelRet))
                            {
                                return(false);
                            }
                        }

                        string TextObs = tvItemService.CleanText(string.IsNullOrEmpty(pqc.description) ? "" : pqc.description);

                        PolSourceObservationModel polSourceObservationModelNew = new PolSourceObservationModel();
                        if (pqc.date_observation == null)
                        {
                            polSourceObservationModelNew.ObservationDate_Local = new DateTime(2050, 1, 1);
                        }
                        else
                        {
                            polSourceObservationModelNew.ObservationDate_Local = (DateTime)(pqc.date_observation.Value).AddHours(1);
                        }

                        string observateur = "unknown";
                        if (pqc.observateur != null)
                        {
                            if (pqc.observateur.Length > 98)
                            {
                                observateur = pqc.observateur.Substring(0, 60);
                            }
                            else
                            {
                                observateur = pqc.observateur;
                            }
                        }

                        string observation = "(empty)";
                        if (pqc.description != null)
                        {
                            observation = Code.ToString().ToUpper() + " - " + pqc.description;
                        }

                        string TVTextInspectorEN = "Inspector " + observateur + " - (QC)";
                        string TVTextInspectorFR = "Inspecteur " + observateur + " - (QC)";

                        TVItemModel tvItemModelContact = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelRoot.TVItemID, TVTextInspectorEN, TVTypeEnum.Contact);
                        if (!string.IsNullOrWhiteSpace(tvItemModelContact.Error))
                        {
                            tvItemModelContact = tvItemService.PostCreateTVItem(tvItemModelRoot.TVItemID, TVTextInspectorEN, TVTextInspectorFR, TVTypeEnum.Contact);
                            if (!CheckModelOK <TVItemModel>(tvItemModelContact))
                            {
                                return(false);
                            }
                        }

                        polSourceObservationModelNew.ContactTVItemID = tvItemModelContact.TVItemID;

                        polSourceObservationModelNew.PolSourceSiteID         = polSourceSiteModelRet.PolSourceSiteID;
                        polSourceObservationModelNew.Observation_ToBeDeleted = observation;

                        PolSourceObservationModel polSourceObservationModelRet = polSourceObservationService.GetPolSourceObservationModelExistDB(polSourceObservationModelNew);
                        if (!string.IsNullOrWhiteSpace(polSourceObservationModelRet.Error))
                        {
                            polSourceObservationModelRet = polSourceObservationService.PostAddPolSourceObservationDB(polSourceObservationModelNew);
                            if (!CheckModelOK <PolSourceObservationModel>(polSourceObservationModelRet))
                            {
                                return(false);
                            }
                        }

                        PolSourceObservationIssueModel polSourceObservationIssueModelNew = new PolSourceObservationIssueModel()
                        {
                            PolSourceObservationID = polSourceObservationModelNew.PolSourceObservationID,
                            ObservationInfo        = ObservationInfo,
                            PolSourceObsInfoList   = polSourceObsInfoList,
                            Ordinal = 0,
                        };

                        PolSourceObservationIssueModel polSourceObservationIssueModelRet = polSourceObservationIssueService.GetPolSourceObservationIssueModelExistDB(polSourceObservationIssueModelNew);
                        if (!string.IsNullOrWhiteSpace(polSourceObservationIssueModelRet.Error))
                        {
                            polSourceObservationIssueModelRet = polSourceObservationIssueService.PostAddPolSourceObservationIssueDB(polSourceObservationIssueModelNew);
                            if (!CheckModelOK <PolSourceObservationModel>(polSourceObservationModelRet))
                            {
                                return(false);
                            }
                        }

                        // do historic PolSourceObservation

                        List <PCCSM.db_histo_operation> histoPolSourceList = new List <PCCSM.db_histo_operation>();
                        using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
                        {
                            histoPolSourceList = (from c in dbQC.geo_pollution_p
                                                  from h in dbQC.db_histo_operation
                                                  where c.id_geo_pollution_p == h.id_geo_pollution_p &&
                                                  c.id_geo_pollution_p == pqc.id_geo_pollution_p
                                                  select h).ToList();
                        }

                        foreach (PCCSM.db_histo_operation hist in histoPolSourceList)
                        {
                            Application.DoEvents();

                            PolSourceObservationModel polSourceObservationModelNew2 = new PolSourceObservationModel();

                            if (hist.date_operation == null)
                            {
                                polSourceObservationModelNew2.ObservationDate_Local = new DateTime(1900, 1, 1);
                            }
                            else
                            {
                                polSourceObservationModelNew2.ObservationDate_Local = (DateTime)hist.date_operation;
                            }

                            observateur = "unknown";
                            if (hist.auteur != null)
                            {
                                if (hist.auteur.Length > 98)
                                {
                                    observateur = hist.auteur.Substring(0, 60);
                                }
                                else
                                {
                                    observateur = hist.auteur;
                                }
                            }

                            observation = "(vide)";
                            if (hist.description != null)
                            {
                                observation = hist.description;
                            }

                            TVTextInspectorEN = "Inspector " + observateur + " - (QC)";
                            TVTextInspectorFR = "Inspecteur " + observateur + " - (QC)";

                            tvItemModelContact = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelRoot.TVItemID, TVTextInspectorEN, TVTypeEnum.Contact);
                            if (!string.IsNullOrWhiteSpace(tvItemModelContact.Error))
                            {
                                tvItemModelContact = tvItemService.PostCreateTVItem(tvItemModelRoot.TVItemID, TVTextInspectorEN, TVTextInspectorFR, TVTypeEnum.Contact);
                                if (!CheckModelOK <TVItemModel>(tvItemModelContact))
                                {
                                    return(false);
                                }
                            }

                            polSourceObservationModelNew2.ContactTVItemID = tvItemModelContact.TVItemID;

                            polSourceObservationModelNew2.PolSourceSiteID         = polSourceSiteModelRet.PolSourceSiteID;
                            polSourceObservationModelNew2.Observation_ToBeDeleted = observation;

                            PolSourceObservationModel polSourceObservationModelRet2 = polSourceObservationService.GetPolSourceObservationModelExistDB(polSourceObservationModelNew2);
                            if (!string.IsNullOrWhiteSpace(polSourceObservationModelRet2.Error))
                            {
                                polSourceObservationModelRet2 = polSourceObservationService.PostAddPolSourceObservationDB(polSourceObservationModelNew2);
                                if (!CheckModelOK <PolSourceObservationModel>(polSourceObservationModelRet2))
                                {
                                    return(false);
                                }
                            }

                            PolSourceObservationIssueModel polSourceObservationIssueModelNew2 = new PolSourceObservationIssueModel()
                            {
                                PolSourceObservationID = polSourceObservationModelNew2.PolSourceObservationID,
                                ObservationInfo        = ObservationInfo,
                                PolSourceObsInfoList   = polSourceObsInfoList,
                                Ordinal = 0,
                            };

                            PolSourceObservationIssueModel polSourceObservationIssueModelRet2 = polSourceObservationIssueService.GetPolSourceObservationIssueModelExistDB(polSourceObservationIssueModelNew2);
                            if (!string.IsNullOrWhiteSpace(polSourceObservationIssueModelRet2.Error))
                            {
                                polSourceObservationIssueModelRet2 = polSourceObservationIssueService.PostAddPolSourceObservationIssueDB(polSourceObservationIssueModelNew2);
                                if (!CheckModelOK <PolSourceObservationModel>(polSourceObservationModelRet2))
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
        public void GenerateLinksBetweenMWQMSitesAndPolSourceSitesForCSSPWebToolsVisualization()
        {
            string NotUsed = "";

            TVItemService                  tvItemService                  = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            AppTaskService                 appTaskService                 = new AppTaskService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVFileService                  tvFileService                  = new TVFileService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            ProvinceToolsService           provinceToolsService           = new ProvinceToolsService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MapInfoService                 mapInfoService                 = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            AppTaskModel                   appTaskModel                   = appTaskService.GetAppTaskModelWithAppTaskIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID);
            PolSourceSiteEffectService     polSourceSiteEffectService     = new PolSourceSiteEffectService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            PolSourceSiteEffectTermService polSourceSiteEffectTermService = new PolSourceSiteEffectTermService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            if (_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes._Required, TaskRunnerServiceRes.TVItemID);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_Required", TaskRunnerServiceRes.TVItemID);
                return;
            }
            if (_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID2 == 0)
            {
                NotUsed = string.Format(TaskRunnerServiceRes._Required, TaskRunnerServiceRes.TVItemID2);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_Required", TaskRunnerServiceRes.TVItemID2);
                return;
            }

            TVItemModel tvItemModelProvince = tvItemService.GetTVItemModelWithTVItemIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            if (!string.IsNullOrWhiteSpace(tvItemModelProvince.Error))
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFind_With_Equal_, TaskRunnerServiceRes.TVItem, TaskRunnerServiceRes.TVItemID, _TaskRunnerBaseService._BWObj.appTaskModel.TVItemID.ToString());
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("CouldNotFind_With_Equal_", TaskRunnerServiceRes.TVItem, TaskRunnerServiceRes.TVItemID, _TaskRunnerBaseService._BWObj.appTaskModel.TVItemID.ToString());
                return;
            }

            if (tvItemModelProvince.TVType != TVTypeEnum.Province)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.TVTypeShouldBe_, TVTypeEnum.Province.ToString());
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("TVTypeShouldBe_", TVTypeEnum.Province.ToString());
                return;
            }

            string Parameters = _TaskRunnerBaseService._BWObj.appTaskModel.Parameters;

            string[] ParamValueList   = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            int      ProvinceTVItemID = 0;

            foreach (string s in ParamValueList)
            {
                string[] ParamValue = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                if (ParamValue.Length != 2)
                {
                    NotUsed = string.Format(TaskRunnerServiceRes.CouldNotParse_Properly, TaskRunnerServiceRes.Parameters);
                    _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotParse_Properly", TaskRunnerServiceRes.Parameters);
                    return;
                }

                if (ParamValue[0] == "ProvinceTVItemID")
                {
                    ProvinceTVItemID = int.Parse(ParamValue[1]);
                }
                else
                {
                    NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFind_, ParamValue[0]);
                    _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotFind_", ParamValue[0].ToString());
                    return;
                }
            }

            if (tvItemModelProvince.TVItemID != ProvinceTVItemID)
            {
                NotUsed = string.Format(TaskRunnerServiceRes._NotEqualTo_, "tvItemModelProvince.TVItemID[" + tvItemModelProvince.TVItemID.ToString() + "]", "ProvinceTVItemID[" + ProvinceTVItemID.ToString() + "]");
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat2List("_NotEqualTo_", "tvItemModelProvince.TVItemID[" + tvItemModelProvince.TVItemID.ToString() + "]", "ProvinceTVItemID[" + ProvinceTVItemID.ToString() + "]");
                return;
            }

            string ServerPath = tvFileService.GetServerFilePath(ProvinceTVItemID);
            string Init       = provinceToolsService.GetInit(ProvinceTVItemID);

            #region Reading the MWQMSitesAndPolSourceSites_XX.KML
            List <TVItemIDAndLatLng> TVItemIDAndLatLngList = new List <TVItemIDAndLatLng>();

            string FileName = $"MWQMSitesAndPolSourceSites_{Init}.kml";

            FileInfo fi = new FileInfo(ServerPath + FileName);

            if (!fi.Exists)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFindFile_, fi.FullName);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotFindFile_", fi.FullName);
                return;
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(fi.FullName);

            foreach (XmlNode node in doc.ChildNodes)
            {
                GetTVItemIDAndLatLng(TVItemIDAndLatLngList, node);
            }

            #endregion Reading the MWQMSitesAndPolSourceSites_XX.KML

            #region Reading the GroupingInputs__XX.KML

            string FileName2 = $"GroupingInputs_{Init}.kml";

            FileInfo fi2 = new FileInfo(ServerPath + FileName2);

            if (!fi2.Exists)
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFindFile_, fi2.FullName);
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("CouldNotFindFile_", fi2.FullName);
                return;
            }

            XmlDocument doc2 = new XmlDocument();
            doc2.Load(fi2.FullName);

            string CurrentSubsector = "";
            string CurrentGroupingMWQMSitesAndPolSourceSites = "";

            List <PolyObj> polyObjList = new List <PolyObj>();

            XmlNode StartNode2 = doc2.ChildNodes[1].ChildNodes[0];
            foreach (XmlNode n in StartNode2.ChildNodes)
            {
                if (n.Name == "Folder")
                {
                    CurrentSubsector = "";

                    foreach (XmlNode n22 in n)
                    {
                        if (n22.Name == "name")
                        {
                            CurrentSubsector = n22.InnerText;
                        }

                        if (n22.Name == "Placemark")
                        {
                            CurrentGroupingMWQMSitesAndPolSourceSites = "";

                            foreach (XmlNode n2 in n22)
                            {
                                if (n2.Name == "name")
                                {
                                    CurrentGroupingMWQMSitesAndPolSourceSites = n2.InnerText;
                                }

                                if (n2.Name == "Polygon")
                                {
                                    foreach (XmlNode n222 in n2.ChildNodes)
                                    {
                                        if (n222.Name == "outerBoundaryIs")
                                        {
                                            foreach (XmlNode n2222 in n222.ChildNodes)
                                            {
                                                if (n2222.Name == "LinearRing")
                                                {
                                                    PolyObj polyObj = new PolyObj();

                                                    polyObj.Subsector      = CurrentSubsector;
                                                    polyObj.Classification = CurrentGroupingMWQMSitesAndPolSourceSites.ToUpper().Trim();

                                                    foreach (XmlNode n3 in n2222.ChildNodes)
                                                    {
                                                        if (n3.Name == "coordinates")
                                                        {
                                                            string coordText = n3.InnerText.Trim();

                                                            List <string> pointListText = coordText.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

                                                            int ordinal = 0;
                                                            foreach (string pointText in pointListText)
                                                            {
                                                                string pointTxt = pointText.Trim();

                                                                if (!string.IsNullOrWhiteSpace(pointTxt))
                                                                {
                                                                    List <string> valListText = pointTxt.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

                                                                    if (valListText.Count != 3)
                                                                    {
                                                                        NotUsed = "valListText.Count != 3";
                                                                        _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageList("valListText.Count != 3");
                                                                        return;
                                                                    }

                                                                    float Lng = float.Parse(valListText[0]);
                                                                    float Lat = float.Parse(valListText[1]);

                                                                    Coord coord = new Coord()
                                                                    {
                                                                        Lat = Lat, Lng = Lng, Ordinal = ordinal
                                                                    };

                                                                    polyObj.coordList.Add(coord);

                                                                    ordinal += 1;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if (polyObj.coordList.Count > 0)
                                                    {
                                                        polyObj.MinLat = polyObj.coordList.Min(c => c.Lat);
                                                        polyObj.MaxLat = polyObj.coordList.Max(c => c.Lat);
                                                        polyObj.MinLng = polyObj.coordList.Min(c => c.Lng);
                                                        polyObj.MaxLng = polyObj.coordList.Max(c => c.Lng);
                                                    }
                                                    polyObjList.Add(polyObj);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion Reading the GroupingInputs__XX.KML

            #region Saving PolSourceSiteEffect in CSSPDB
            TVItemModel tvItemModelProv = tvItemService.GetTVItemModelWithTVItemIDDB(ProvinceTVItemID);
            if (!string.IsNullOrWhiteSpace(tvItemModelProv.Error))
            {
                NotUsed = string.Format(TaskRunnerServiceRes.CouldNotFind_With_Equal_, TaskRunnerServiceRes.TVItem, TaskRunnerServiceRes.TVItemID, ProvinceTVItemID.ToString());
                _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat3List("CouldNotFind_With_Equal_", TaskRunnerServiceRes.TVItem, TaskRunnerServiceRes.TVItemID, ProvinceTVItemID.ToString());
                return;
            }

            // getting all active MWQMSites and PolSourceSites under the province

            List <TVItem> tvItemMWQMSiteList = new List <TVItem>();
            List <TVItem> tvItemPSSList      = new List <TVItem>();
            List <TVItem> tvItemInfraList    = new List <TVItem>();
            using (CSSPDBEntities db2 = new CSSPDBEntities())
            {
                tvItemMWQMSiteList = (from c in db2.TVItems
                                      where c.TVPath.StartsWith(tvItemModelProv.TVPath + "p") &&
                                      c.TVType == (int)TVTypeEnum.MWQMSite &&
                                      c.IsActive == true
                                      select c).ToList();


                tvItemPSSList = (from c in db2.TVItems
                                 where c.TVPath.StartsWith(tvItemModelProv.TVPath + "p") &&
                                 c.TVType == (int)TVTypeEnum.PolSourceSite &&
                                 c.IsActive == true
                                 select c).ToList();

                tvItemInfraList = (from c in db2.TVItems
                                   where c.TVPath.StartsWith(tvItemModelProv.TVPath + "p") &&
                                   c.TVType == (int)TVTypeEnum.Infrastructure &&
                                   c.IsActive == true
                                   select c).ToList();
            }

            List <TVItemModel> tvitemModelSSList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProv.TVItemID, TVTypeEnum.Subsector);

            List <PolSourceSiteEffect> existingPolSourceSiteEffectSubsectorList = new List <PolSourceSiteEffect>();
            List <PolSourceSiteEffect> newPolSourceSiteEffectSubsectorList      = new List <PolSourceSiteEffect>();

            int    CountSS    = 0;
            int    TotalCount = tvitemModelSSList.Count;
            string Status     = appTaskModel.StatusText;
            foreach (TVItemModel tvItemModelSS in tvitemModelSSList)
            {
                CountSS += 1;
                if (CountSS % 1 == 0)
                {
                    _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, (int)(100.0f * ((float)CountSS / (float)TotalCount)));
                }
                Application.DoEvents();

                string TVTextSS = "";
                if (tvItemModelSS.TVText.Contains(" "))
                {
                    TVTextSS = tvItemModelSS.TVText.Substring(0, tvItemModelSS.TVText.IndexOf(" "));
                }
                else
                {
                    TVTextSS = tvItemModelSS.TVText;
                }

                foreach (PolyObj polyObj in polyObjList.Where(c => c.Subsector == TVTextSS))
                {
                    List <MapInfo> mapInfoMWQMSiteList2 = new List <MapInfo>();
                    List <MapInfo> mapInfoPSSList2      = new List <MapInfo>();
                    List <MapInfo> mapInfoInfraList2    = new List <MapInfo>();

                    using (CSSPDBEntities db2 = new CSSPDBEntities())
                    {
                        var mapInfoMWQMSiteList = (from c in db2.MapInfos
                                                   let lat = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lat
                                                             let lng = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lng
                                                                       where c.TVType == (int)TVTypeEnum.MWQMSite &&
                                                                       c.MapInfoDrawType == (int)MapInfoDrawTypeEnum.Point &&
                                                                       lat >= polyObj.MinLat &&
                                                                       lat <= polyObj.MaxLat &&
                                                                       lng >= polyObj.MinLng &&
                                                                       lng <= polyObj.MaxLng
                                                                       select new { c, lat, lng }).ToList();

                        var mapInfoPSSList = (from c in db2.MapInfos
                                              let lat = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lat
                                                        let lng = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lng
                                                                  where c.TVType == (int)TVTypeEnum.PolSourceSite &&
                                                                  c.MapInfoDrawType == (int)MapInfoDrawTypeEnum.Point &&
                                                                  lat >= polyObj.MinLat &&
                                                                  lat <= polyObj.MaxLat &&
                                                                  lng >= polyObj.MinLng &&
                                                                  lng <= polyObj.MaxLng
                                                                  select new { c, lat, lng }).ToList();

                        var mapInfoInfraList = (from c in db2.MapInfos
                                                let lat = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lat
                                                          let lng = (from d in db2.MapInfoPoints where c.MapInfoID == d.MapInfoID select d).FirstOrDefault().Lng
                                                                    where (c.TVType == (int)TVTypeEnum.WasteWaterTreatmentPlant ||
                                                                           c.TVType == (int)TVTypeEnum.LiftStation ||
                                                                           c.TVType == (int)TVTypeEnum.LineOverflow) &&
                                                                    c.MapInfoDrawType == (int)MapInfoDrawTypeEnum.Point &&
                                                                    lat >= polyObj.MinLat &&
                                                                    lat <= polyObj.MaxLat &&
                                                                    lng >= polyObj.MinLng &&
                                                                    lng <= polyObj.MaxLng
                                                                    select new { c, lat, lng }).ToList();


                        foreach (var mapInfo in mapInfoMWQMSiteList)
                        {
                            if (mapInfoService.CoordInPolygon(polyObj.coordList, new Coord()
                            {
                                Lat = (float)mapInfo.lat, Lng = (float)mapInfo.lng, Ordinal = 0
                            }))
                            {
                                mapInfoMWQMSiteList2.Add(mapInfo.c);
                            }
                        }

                        foreach (var mapInfo in mapInfoPSSList)
                        {
                            if (mapInfoService.CoordInPolygon(polyObj.coordList, new Coord()
                            {
                                Lat = (float)mapInfo.lat, Lng = (float)mapInfo.lng, Ordinal = 0
                            }))
                            {
                                mapInfoPSSList2.Add(mapInfo.c);
                            }
                        }

                        foreach (var mapInfo in mapInfoInfraList)
                        {
                            if (mapInfoService.CoordInPolygon(polyObj.coordList, new Coord()
                            {
                                Lat = (float)mapInfo.lat, Lng = (float)mapInfo.lng, Ordinal = 0
                            }))
                            {
                                mapInfoInfraList2.Add(mapInfo.c);
                            }
                        }
                    }

                    List <int> PSSTVItemIDList = (from c in mapInfoPSSList2
                                                  select c.TVItemID).Distinct().ToList();
                    List <int> MWQMTVItemIDList = (from c in mapInfoMWQMSiteList2
                                                   select c.TVItemID).Distinct().ToList();
                    List <int> InfraTVItemIDList = (from c in mapInfoInfraList2
                                                    select c.TVItemID).Distinct().ToList();

                    using (CSSPDBEntities db2 = new CSSPDBEntities())
                    {
                        List <int> TVItemIDMWQMSiteWithinSubsector = tvItemMWQMSiteList.Where(c => c.TVPath.Contains(tvItemModelSS.TVPath + "p")).Select(c => c.TVItemID).ToList();

                        existingPolSourceSiteEffectSubsectorList = (from c in db2.PolSourceSiteEffects
                                                                    from m in TVItemIDMWQMSiteWithinSubsector
                                                                    where c.MWQMSiteTVItemID == m
                                                                    select c).ToList();
                    }

                    foreach (TVItem tvItemMWQMSite in tvItemMWQMSiteList.Where(c => c.TVPath.Contains(tvItemModelSS.TVPath + "p")))
                    {
                        if (MWQMTVItemIDList.Contains(tvItemMWQMSite.TVItemID))
                        {
                            List <PolSourceSiteEffect> MWQMSiteExistingPolSourceSiteEffectList = (from c in existingPolSourceSiteEffectSubsectorList
                                                                                                  where c.MWQMSiteTVItemID == tvItemMWQMSite.TVItemID
                                                                                                  select c).ToList();

                            // doing pollution source site
                            foreach (int PSSTVItemID in PSSTVItemIDList)
                            {
                                newPolSourceSiteEffectSubsectorList.Add(new PolSourceSiteEffect()
                                {
                                    PolSourceSiteOrInfrastructureTVItemID = PSSTVItemID, MWQMSiteTVItemID = tvItemMWQMSite.TVItemID,
                                });

                                if (!(MWQMSiteExistingPolSourceSiteEffectList.Where(c => c.PolSourceSiteOrInfrastructureTVItemID == PSSTVItemID).Any()))
                                {
                                    PolSourceSiteEffectModel polSourceSiteEffectModelNew = new PolSourceSiteEffectModel()
                                    {
                                        PolSourceSiteOrInfrastructureTVItemID = PSSTVItemID,
                                        MWQMSiteTVItemID = tvItemMWQMSite.TVItemID,
                                    };

                                    PolSourceSiteEffectModel polSourceSiteEffectModelAlreadyExist = polSourceSiteEffectService.GetPolSourceSiteEffectModelWithPolSourceSiteOrInfrastructureTVItemIDAndMWQMSiteTVItemIDDB(PSSTVItemID, tvItemMWQMSite.TVItemID);
                                    if (!string.IsNullOrWhiteSpace(polSourceSiteEffectModelAlreadyExist.Error))
                                    {
                                        PolSourceSiteEffectModel polSourceSiteEffectModelRet = polSourceSiteEffectService.PostAddPolSourceSiteEffectDB(polSourceSiteEffectModelNew);
                                        if (!string.IsNullOrWhiteSpace(polSourceSiteEffectModelRet.Error))
                                        {
                                            NotUsed = string.Format(TaskRunnerServiceRes.CouldNotAdd_Error_, TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                                            _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat2List("CouldNotAdd_Error_", TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                                            return;
                                        }
                                    }
                                }
                            }

                            // doing infrastructure
                            foreach (int InfraTVItemID in InfraTVItemIDList)
                            {
                                newPolSourceSiteEffectSubsectorList.Add(new PolSourceSiteEffect()
                                {
                                    PolSourceSiteOrInfrastructureTVItemID = InfraTVItemID, MWQMSiteTVItemID = tvItemMWQMSite.TVItemID,
                                });

                                if (!(MWQMSiteExistingPolSourceSiteEffectList.Where(c => c.PolSourceSiteOrInfrastructureTVItemID == InfraTVItemID).Any()))
                                {
                                    PolSourceSiteEffectModel polSourceSiteEffectModelNew = new PolSourceSiteEffectModel()
                                    {
                                        PolSourceSiteOrInfrastructureTVItemID = InfraTVItemID,
                                        MWQMSiteTVItemID = tvItemMWQMSite.TVItemID,
                                    };

                                    PolSourceSiteEffectModel polSourceSiteEffectModelAlreadyExist = polSourceSiteEffectService.GetPolSourceSiteEffectModelWithPolSourceSiteOrInfrastructureTVItemIDAndMWQMSiteTVItemIDDB(InfraTVItemID, tvItemMWQMSite.TVItemID);
                                    if (!string.IsNullOrWhiteSpace(polSourceSiteEffectModelAlreadyExist.Error))
                                    {
                                        PolSourceSiteEffectModel polSourceSiteEffectModelRet = polSourceSiteEffectService.PostAddPolSourceSiteEffectDB(polSourceSiteEffectModelNew);
                                        if (!string.IsNullOrWhiteSpace(polSourceSiteEffectModelRet.Error))
                                        {
                                            NotUsed = string.Format(TaskRunnerServiceRes.CouldNotAdd_Error_, TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                                            _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat2List("CouldNotAdd_Error_", TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            foreach (PolSourceSiteEffect polSourceSiteEffect in existingPolSourceSiteEffectSubsectorList)
            {
                if (!newPolSourceSiteEffectSubsectorList.Where(c => c.PolSourceSiteOrInfrastructureTVItemID == polSourceSiteEffect.PolSourceSiteOrInfrastructureTVItemID &&
                                                               c.MWQMSiteTVItemID == polSourceSiteEffect.MWQMSiteTVItemID).Any())
                {
                    PolSourceSiteEffectModel polSourceSiteEffectModelAlreadyExist = polSourceSiteEffectService.GetPolSourceSiteEffectModelWithPolSourceSiteOrInfrastructureTVItemIDAndMWQMSiteTVItemIDDB(polSourceSiteEffect.PolSourceSiteOrInfrastructureTVItemID, polSourceSiteEffect.MWQMSiteTVItemID);
                    if (string.IsNullOrWhiteSpace(polSourceSiteEffectModelAlreadyExist.Error))
                    {
                        PolSourceSiteEffectModel polSourceSiteEffectModelRet = polSourceSiteEffectService.PostDeletePolSourceSiteEffectDB(polSourceSiteEffectModelAlreadyExist.PolSourceSiteEffectID);
                        if (!string.IsNullOrWhiteSpace(polSourceSiteEffectModelRet.Error))
                        {
                            NotUsed = string.Format(TaskRunnerServiceRes.CouldNotDelete_Error_, TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                            _TaskRunnerBaseService._BWObj.TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat2List("CouldNotDelete_Error_", TaskRunnerServiceRes.PolSourceSiteEffect, polSourceSiteEffectModelRet.Error);
                            return;
                        }
                    }
                }
            }

            #endregion Saving PolSourceSiteEffect in CSSPDB

            appTaskModel.PercentCompleted = 100;
            appTaskService.PostUpdateAppTask(appTaskModel);
        }