Example #1
0
        public BaseService(LanguageEnum LanguageRequest, IPrincipal User)
        {
            if (!(LanguageRequest == LanguageEnum.en || LanguageRequest == LanguageEnum.fr))
            {
                this.LanguageRequest = LanguageEnum.en;
            }
            else
            {
                if (LanguageListAllowable.Contains(LanguageRequest))
                {
                    this.LanguageRequest = LanguageRequest;
                }
                else
                {
                    this.LanguageRequest = LanguageEnum.en;
                }
            }
            _BaseEnumService  = new BaseEnumService(LanguageRequest);
            _BaseModelService = new BaseModelService(LanguageRequest);

            this.User = User;
            db        = new CSSPDBEntities();
            FillTVTypeNamesAndPathList();
            _BaseModelService.FillPolSourceObsInfoChild(polSourceObsInfoChildList);

            OriginX            = TileSize / 2;
            OriginY            = TileSize / 2;
            PixelsPerLonDegree = TileSize / 360.0;
            PixelsPerLonRadian = TileSize / (2 * Math.PI);
        }
Example #2
0
        public TVItemModel MarkSamplesWithMWQMSampleIDForOpenDataDB(int MWQMSampleID, bool UseForOpenData)
        {
            using (CSSPDBEntities dd = new CSSPDBEntities())
            {
                MWQMSample mwqmSample = (from s in dd.MWQMSamples
                                         where s.MWQMSampleID == MWQMSampleID
                                         select s).FirstOrDefault();

                if (mwqmSample == null)
                {
                    return(ReturnError(string.Format(ServiceRes.CouldNotFind_With_Equal_, ServiceRes.MWQMSample, ServiceRes.MWQMSampleID, MWQMSampleID.ToString())));
                }

                mwqmSample.UseForOpenData = UseForOpenData;

                try
                {
                    dd.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(ReturnError(string.Format(ServiceRes.CouldNotUpdateError_, ex.Message + " InnerException: " + (ex.InnerException != null ? ex.InnerException.Message : ""))));
                }
            }

            return(ReturnError(""));
        }
Example #3
0
        public TVItemModel ToggleUseForOpenDataFlagOfAllSamplesUnderMWQMSiteTVItemIDDB(int MWQMSiteTVItemID, DateTime StartDate, DateTime EndDate, bool UseForOpenData)
        {
            string RoutineTxt = ((int)SampleTypeEnum.Routine).ToString() + ",";

            TVItem tvItemSite = new TVItem();

            using (CSSPDBEntities dd = new CSSPDBEntities())
            {
                tvItemSite = (from c in dd.TVItems
                              where c.TVItemID == MWQMSiteTVItemID
                              select c).FirstOrDefault();
            }

            if (tvItemSite == null)
            {
                return(ReturnError(string.Format(ServiceRes.CouldNotFind_With_Equal_, ServiceRes.MWQMSite, ServiceRes.MWQMSiteTVItemID, MWQMSiteTVItemID.ToString())));
            }

            using (CSSPDBEntities dd = new CSSPDBEntities())
            {
                List <MWQMSample> mwqmSampleList = (from t in dd.TVItems
                                                    from s in dd.MWQMSamples
                                                    where t.TVItemID == s.MWQMSiteTVItemID &&
                                                    t.TVItemID == MWQMSiteTVItemID &&
                                                    t.TVType == (int)TVTypeEnum.MWQMSite &&
                                                    s.SampleTypesText.Contains(RoutineTxt) &&
                                                    s.UseForOpenData == !UseForOpenData &&
                                                    s.SampleDateTime_Local >= StartDate &&
                                                    s.SampleDateTime_Local <= EndDate
                                                    select s).ToList();

                foreach (MWQMSample mwqmSample in mwqmSampleList)
                {
                    mwqmSample.UseForOpenData = UseForOpenData;
                }

                try
                {
                    dd.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(ReturnError(string.Format(ServiceRes.CouldNotUpdateError_, ex.Message + " InnerException: " + (ex.InnerException != null ? ex.InnerException.Message : ""))));
                }
            }

            return(ReturnError(""));
        }
Example #4
0
        public OpenDataStat GetOpenDataStatDB(int TVItemID)
        {
            string routineTxt = ((int)SampleTypeEnum.Routine).ToString() + ",";

            TVItemModel tvItemModel = _TVItemService.GetTVItemModelWithTVItemIDDB(TVItemID);

            if (!string.IsNullOrWhiteSpace(tvItemModel.Error))
            {
                return new OpenDataStat()
                       {
                           Error = tvItemModel.Error
                       }
            }
            ;

            using (CSSPDBEntities dd = new CSSPDBEntities())
            {
                OpenDataStat openDataStat = (from c in dd.TVItems
                                             let samples = (from d in dd.TVItems
                                                            from s in dd.MWQMSamples
                                                            where d.TVItemID == s.MWQMSiteTVItemID &&
                                                            d.TVPath.StartsWith(c.TVPath) &&
                                                            d.TVType == (int)TVTypeEnum.MWQMSite &&
                                                            s.SampleTypesText.Contains(routineTxt)
                                                            select new { s.UseForOpenData })
                                                           let totalSampleCount = (from s in samples select s).Count()
                                                                                  let useForOpenDataSampleCount = (from s in samples
                                                                                                                   where s.UseForOpenData == true
                                                                                                                   select s).Count()
                                                                                                                  where c.TVItemID == TVItemID
                                                                                                                  select new OpenDataStat
                {
                    Error = "",
                    TotalNumberOfSamples = totalSampleCount,
                    NumberOfUseForOpenDataSamples = useForOpenDataSampleCount,
                }).FirstOrDefault <OpenDataStat>();

                return(openDataStat);
            }
        }
        private bool GenerateHTMLSUBSECTOR_POLLUTION_SOURCE_SITES_COMPACT(StringBuilder sbTemp)
        {
            int          Percent  = 10;
            string       NotUsed  = "";
            LanguageEnum language = _TaskRunnerBaseService._BWObj.appTaskModel.Language;

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, Percent);
            _TaskRunnerBaseService.SendStatusTextToDB(_TaskRunnerBaseService.GetTextLanguageFormat1List("Creating_", ReportGenerateObjectsKeywordEnum.SUBSECTOR_POLLUTION_SOURCE_SITES_COMPACT.ToString()));

            TVItemModel tvItemModelSubsector = _TVItemService.GetTVItemModelWithTVItemIDDB(TVItemID);

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

            string ServerPath = _TVFileService.GetServerFilePath(tvItemModelSubsector.TVItemID);

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 5);

            List <TVItemModel>                    tvItemModelListPolSourceSite       = _TVItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.PolSourceSite);
            List <PolSourceSiteModel>             polSourceSiteModelList             = _PolSourceSiteService.GetPolSourceSiteModelListWithSubsectorTVItemIDDB(TVItemID).OrderBy(c => c.Site).ToList();
            List <PolSourceObservationModel>      polSourceObservationModelList      = _PolSourceObservationService.GetPolSourceObservationModelListWithSubsectorTVItemIDDB(TVItemID);
            List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = _PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithSubsectorTVItemIDDB(TVItemID);
            List <int> TVItemIDPolSourceSiteActiveList = tvItemModelListPolSourceSite.Where(c => c.IsActive == true).Select(c => c.TVItemID).ToList();

            List <MapInfo>      mapInfoActiveList      = new List <MapInfo>();
            List <MapInfoPoint> mapInfoPointActiveList = new List <MapInfoPoint>();

            //using (CSSPDBEntities db2 = new CSSPDBEntities())
            //{
            //    mapInfoActiveList = (from c in db2.MapInfos
            //                         from a in TVItemIDPolSourceSiteActiveList
            //                         where c.TVItemID == a
            //                         select c).ToList();

            //    List<int> mapInfoIDActiveList = mapInfoActiveList.Select(c => c.MapInfoID).ToList();

            //    mapInfoPointActiveList = (from c in db2.MapInfoPoints
            //                              from a in mapInfoIDActiveList
            //                              where c.MapInfoID == a
            //                              select c).ToList();

            //}

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 10);

            sbTemp.AppendLine($@"|||TableCaption| { TaskRunnerServiceRes.PollutionSourcesSiteInventory }|||");

            sbTemp.AppendLine($@"<table class=""PolSourceSiteCompact"">");
            sbTemp.AppendLine($@"   <tr> ");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Site }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.IN }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Type }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Path }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Prob }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Risk }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Lat }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.Long }</th>");
            sbTemp.AppendLine($@"       <th class=""allBordersNoWrap"">{ TaskRunnerServiceRes.ObsDate }</th>");
            sbTemp.AppendLine($@"   </tr>");

            using (CSSPDBEntities db = new CSSPDBEntities())
            {
                var tvItemSS = (from t in db.TVItems
                                from tl in db.TVItemLanguages
                                where t.TVItemID == tl.TVItemID &&
                                tl.Language == (int)language &&
                                t.TVType == (int)TVTypeEnum.Subsector &&
                                t.IsActive == true &&
                                t.TVItemID == TVItemID
                                select new { t, tl }).FirstOrDefault();

                var PollutionSourceSiteList = (from t in db.TVItems
                                               from tl in db.TVItemLanguages
                                               from mi in db.MapInfos
                                               from mip in db.MapInfoPoints
                                               from pss in db.PolSourceSites
                                               let address = (from a in db.Addresses
                                                              let muni = (from cl in db.TVItemLanguages where cl.TVItemID == a.MunicipalityTVItemID && cl.Language == (int)LanguageEnum.en select cl.TVText).FirstOrDefault <string>()
                                                                         let add = a.StreetNumber + " " + a.StreetName + " --- " + muni
                                                                                   where a.AddressTVItemID == t.TVItemID
                                                                                   select new { add }).FirstOrDefault()
                                                             let pso = (from pso in db.PolSourceObservations
                                                                        where pso.PolSourceSiteID == pss.PolSourceSiteID
                                                                        orderby pso.ObservationDate_Local descending
                                                                        select new { pso }).FirstOrDefault()
                                                                       let psi = (from psi in db.PolSourceObservationIssues
                                                                                  where psi.PolSourceObservationID == pso.pso.PolSourceObservationID
                                                                                  orderby psi.Ordinal ascending
                                                                                  select new { psi }).ToList()
                                                                                 where t.TVItemID == tl.TVItemID &&
                                                                                 mi.TVItemID == t.TVItemID &&
                                                                                 mip.MapInfoID == mi.MapInfoID &&
                                                                                 t.TVItemID == pss.PolSourceSiteTVItemID &&
                                                                                 tl.Language == (int)LanguageEnum.en &&
                                                                                 t.TVPath.StartsWith(tvItemSS.t.TVPath + "p") &&
                                                                                 t.TVType == (int)TVTypeEnum.PolSourceSite &&
                                                                                 t.IsActive == true &&
                                                                                 mi.MapInfoDrawType == (int)MapInfoDrawTypeEnum.Point &&
                                                                                 mi.TVType == (int)TVTypeEnum.PolSourceSite
                                                                                 orderby tl.TVText
                                                                                 select new { t, tl, mip, address.add, pss, pso, psi }).ToList();

                foreach (var polSourceSite in PollutionSourceSiteList.Where(c => c.t.ParentID == tvItemSS.t.TVItemID))
                {
                    string SS   = tvItemSS.tl.TVText.Replace(",", "_");
                    string Desc = "";
                    if (SS.Contains(" "))
                    {
                        Desc = SS.Substring(SS.IndexOf(" "));
                        Desc = Desc.Trim();
                        Desc = Desc.Replace("(", "").Replace(")", "");
                        SS   = SS.Substring(0, SS.IndexOf(" "));
                    }
                    string   PSS     = "P" + (polSourceSite.pss != null && polSourceSite.pss.Site != null ? polSourceSite.pss.Site.ToString().Replace(",", "_") : "");
                    string   OBSDate = (polSourceSite.pso != null && polSourceSite.pso.pso.ObservationDate_Local != null ? polSourceSite.pso.pso.ObservationDate_Local.ToString("yyyy-MM-dd") : "");
                    string   PSTVT   = polSourceSite.tl.TVText;
                    string[] PSArr   = PSTVT.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToArray();
                    string   PSType  = "";
                    string   PSPath  = "";
                    string   PSProb  = "";
                    string   PSRisk  = "";
                    if (PSArr.Length > 0)
                    {
                        PSType = PSArr[0];
                        if (PSType.Contains(" - "))
                        {
                            PSType = PSType.Substring(PSType.IndexOf(" - ") + 3);
                        }
                    }
                    if (PSArr.Length > 1)
                    {
                        PSPath = PSArr[1];
                    }
                    if (PSArr.Length > 2)
                    {
                        PSRisk = PSArr[2];
                    }
                    string Lat = (polSourceSite.mip != null ? polSourceSite.mip.Lat.ToString("F5") : "");
                    string Lng = (polSourceSite.mip != null ? polSourceSite.mip.Lng.ToString("F5") : "");
                    string URL = @"http://131.235.1.167/csspwebtools/en-CA/#!View/a|||" + polSourceSite.t.TVItemID.ToString() + @"|||30010100004000000000000000000000";

                    string TVText = "";

                    int IN = 0;
                    foreach (var psi in polSourceSite.psi)
                    {
                        if (psi != null && psi.psi != null)
                        {
                            IN += 1;
                            List <string> ObservationInfoList = (string.IsNullOrWhiteSpace(psi.psi.ObservationInfo) ? new List <string>() : psi.psi.ObservationInfo.Trim().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList());

                            for (int i = 0, countObs = ObservationInfoList.Count; i < countObs; i++)
                            {
                                string Temp = _BaseEnumService.GetEnumText_PolSourceObsInfoReportEnum((PolSourceObsInfoEnum)int.Parse(ObservationInfoList[i]));
                                switch (ObservationInfoList[i].Substring(0, 3))
                                {
                                case "101":
                                {
                                    Temp = Temp.Replace("Source", "     Source");
                                }
                                break;

                                case "250":
                                {
                                    Temp = Temp.Replace("Pathway", "     Pathway");
                                }
                                break;

                                case "900":
                                {
                                    Temp = Temp.Replace("Status", "     Status");
                                    if (!string.IsNullOrWhiteSpace(Temp))
                                    {
                                        PSProb = Temp.Replace("Status:", "");
                                        PSProb = PSProb.Trim();
                                        if (PSProb.Contains(" "))
                                        {
                                            PSProb = PSProb.Substring(0, PSProb.IndexOf(" "));
                                        }
                                    }
                                }
                                break;

                                case "910":
                                {
                                    Temp = Temp.Replace("Risk", "     Risk");
                                }
                                break;

                                default:
                                    break;
                                }
                                TVText = TVText + Temp;
                            }
                        }

                        string TVT = (polSourceSite.pso != null && polSourceSite.pso.pso.Observation_ToBeDeleted != null ? polSourceSite.pso.pso.Observation_ToBeDeleted : "");

                        string TempISS = (!string.IsNullOrWhiteSpace(TVT) ? TVT.Replace(",", "_") + " ----- " : "") + TVText;

                        string ISS = TempISS.Replace("\r", "   ").Replace("\n", "").Replace("empty", "").Replace("Empty", "").Replace("\r", "   ").Replace("\n", "");

                        if (SS.Length == 0)
                        {
                            SS = " ";
                        }
                        if (Desc.Length == 0)
                        {
                            Desc = " ";
                        }
                        if (PSS.Length == 0)
                        {
                            PSS = " ";
                        }
                        if (PSType.Length == 0)
                        {
                            PSType = " ";
                        }
                        if (PSPath.Length == 0)
                        {
                            PSPath = " ";
                        }
                        if (PSProb.Length == 0)
                        {
                            PSProb = " ";
                        }
                        if (Lat.Length == 0)
                        {
                            Lat = " ";
                        }
                        if (Lng.Length == 0)
                        {
                            Lng = " ";
                        }
                        if (OBSDate.Length == 0)
                        {
                            OBSDate = " ";
                        }
                        if (URL.Length == 0)
                        {
                            URL = " ";
                        }

                        sbTemp.AppendLine($@"   <tr>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ PSS }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ IN }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ PSType }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ PSPath }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ PSProb }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ PSRisk }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ Lat }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ Lng }</td>");
                        sbTemp.AppendLine($@"       <td class=""allBordersNoWrap"">{ OBSDate }</td>");
                        sbTemp.AppendLine($@"   </tr>");
                    }
                }
            }

            sbTemp.AppendLine($@"</table>");

            Percent = 98;
            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, Percent);

            return(true);
        }
Example #6
0
        private bool GenerateHTMLSUBSECTOR_POLLUTION_SOURCE_SITES(StringBuilder sbTemp)
        {
            int          Percent  = 10;
            string       NotUsed  = "";
            LanguageEnum language = _TaskRunnerBaseService._BWObj.appTaskModel.Language;

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, Percent);
            _TaskRunnerBaseService.SendStatusTextToDB(_TaskRunnerBaseService.GetTextLanguageFormat1List("Creating_", ReportGenerateObjectsKeywordEnum.SUBSECTOR_POLLUTION_SOURCE_SITES.ToString()));


            //sbTemp.AppendLine("<h2>SUBSECTOR_POLLUTION_SOURCE_SITES - Not implemented</h2>");

            List <string> ParamValueList = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            // TVItemID and Year already loaded

            TVItemModel tvItemModelSubsector = _TVItemService.GetTVItemModelWithTVItemIDDB(TVItemID);

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

            string ServerPath = _TVFileService.GetServerFilePath(tvItemModelSubsector.TVItemID);

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 5);

            List <TVItemModel>                    tvItemModelListPolSourceSite       = _TVItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.PolSourceSite);
            List <PolSourceSiteModel>             polSourceSiteModelList             = _PolSourceSiteService.GetPolSourceSiteModelListWithSubsectorTVItemIDDB(TVItemID).OrderBy(c => c.Site).ToList();
            List <PolSourceObservationModel>      polSourceObservationModelList      = _PolSourceObservationService.GetPolSourceObservationModelListWithSubsectorTVItemIDDB(TVItemID);
            List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = _PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithSubsectorTVItemIDDB(TVItemID);
            List <int> TVItemIDPolSourceSiteActiveList   = tvItemModelListPolSourceSite.Where(c => c.IsActive == true).Select(c => c.TVItemID).ToList();
            List <int> TVItemIDPolSourceSiteInactiveList = tvItemModelListPolSourceSite.Where(c => c.IsActive == false).Select(c => c.TVItemID).ToList();
            List <int> TVItemIDCivicAddressList          = polSourceSiteModelList.Where(c => c.CivicAddressTVItemID != null && c.CivicAddressTVItemID != 0).Where(c => c != null).Select(c => (int)c.CivicAddressTVItemID).ToList();
            List <int> TVItemIDContactList = polSourceObservationModelList.Select(c => c.ContactTVItemID).ToList();

            List <Address>        addressList              = new List <Address>();
            List <MapInfo>        mapInfoActiveList        = new List <MapInfo>();
            List <MapInfo>        mapInfoInactiveList      = new List <MapInfo>();
            List <MapInfoPoint>   mapInfoPointActiveList   = new List <MapInfoPoint>();
            List <MapInfoPoint>   mapInfoPointInactiveList = new List <MapInfoPoint>();
            List <TVItemLanguage> countryList              = new List <TVItemLanguage>();
            List <TVItemLanguage> provinceList             = new List <TVItemLanguage>();
            List <TVItemLanguage> municipalityList         = new List <TVItemLanguage>();
            List <TVItemLanguage> contactList              = new List <TVItemLanguage>();

            using (CSSPDBEntities db2 = new CSSPDBEntities())
            {
                addressList = (from c in db2.Addresses
                               from a in TVItemIDCivicAddressList
                               where c.AddressTVItemID == a
                               select c).ToList();

                List <int> countryTVItemIDList      = addressList.Select(c => c.CountryTVItemID).ToList();
                List <int> provinceTVItemIDList     = addressList.Select(c => c.ProvinceTVItemID).ToList();
                List <int> municipalityTVItemIDList = addressList.Select(c => c.MunicipalityTVItemID).ToList();

                countryList = (from c in db2.TVItemLanguages
                               from a in countryTVItemIDList
                               where c.TVItemID == a &&
                               c.Language == (int)language
                               select c).ToList();

                provinceList = (from c in db2.TVItemLanguages
                                from a in provinceTVItemIDList
                                where c.TVItemID == a &&
                                c.Language == (int)language
                                select c).ToList();

                municipalityList = (from c in db2.TVItemLanguages
                                    from a in municipalityTVItemIDList
                                    where c.TVItemID == a &&
                                    c.Language == (int)language
                                    select c).ToList();

                contactList = (from c in db2.TVItemLanguages
                               from a in TVItemIDContactList
                               where c.TVItemID == a &&
                               c.Language == (int)language
                               select c).ToList();


                mapInfoActiveList = (from c in db2.MapInfos
                                     from a in TVItemIDPolSourceSiteActiveList
                                     where c.TVItemID == a
                                     select c).ToList();

                mapInfoInactiveList = (from c in db2.MapInfos
                                       from a in TVItemIDPolSourceSiteInactiveList
                                       where c.TVItemID == a
                                       select c).ToList();

                List <int> mapInfoIDActiveList = mapInfoActiveList.Select(c => c.MapInfoID).ToList();

                mapInfoPointActiveList = (from c in db2.MapInfoPoints
                                          from a in mapInfoIDActiveList
                                          where c.MapInfoID == a
                                          select c).ToList();

                List <int> mapInfoIDInactiveList = mapInfoInactiveList.Select(c => c.MapInfoID).ToList();

                mapInfoPointInactiveList = (from c in db2.MapInfoPoints
                                            from a in mapInfoIDInactiveList
                                            where c.MapInfoID == a
                                            select c).ToList();
            }

            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 10);

            //sbTemp.AppendLine(@"<p>|||PAGE_BREAK|||</p>");
            //sbTemp.AppendLine("");
            //sbTemp.AppendLine($@"<h1 style=""text-align: center"">{ tvItemModelSubsector.TVText }</h1>");
            //sbTemp.AppendLine($@"<h2 style=""text-align: center"">{ TaskRunnerServiceRes.ActivePollutionSourceSites }</h2>");
            foreach (TVItemModel tvItemModelPSSActive in tvItemModelListPolSourceSite.Where(c => c.IsActive == true))
            {
                PolSourceSiteModel polSourceSiteModel = polSourceSiteModelList.Where(c => c.PolSourceSiteTVItemID == tvItemModelPSSActive.TVItemID).FirstOrDefault();

                if (polSourceSiteModel != null)
                {
                    sbTemp.AppendLine($@"<div>");
                    sbTemp.AppendLine($@"<p>");
                    sbTemp.AppendLine($@"<strong>{ TaskRunnerServiceRes.Site }</strong>: { polSourceSiteModel.Site }&nbsp;&nbsp;&nbsp;&nbsp;");

                    MapInfo mapInfo = mapInfoActiveList.Where(c => c.TVItemID == tvItemModelPSSActive.TVItemID).FirstOrDefault();
                    if (mapInfo != null)
                    {
                        List <MapInfoPoint> mapInfoPointListCurrent = mapInfoPointActiveList.Where(c => c.MapInfoID == mapInfo.MapInfoID).ToList();
                        if (mapInfoPointListCurrent.Count > 0)
                        {
                            sbTemp.AppendLine($@"<span><strong>{ TaskRunnerServiceRes.Lat } { TaskRunnerServiceRes.Long }</strong>: { mapInfoPointListCurrent[0].Lat.ToString("F5") } { mapInfoPointListCurrent[0].Lng.ToString("F5") }</span>");
                        }
                    }
                    else
                    {
                        sbTemp.AppendLine($@"<span><strong>{ TaskRunnerServiceRes.Lat } { TaskRunnerServiceRes.Long }</strong>: --- ---</span>");
                    }
                    sbTemp.AppendLine($@"</p>");


                    if (polSourceSiteModel.CivicAddressTVItemID != null)
                    {
                        if (polSourceSiteModel.CivicAddressTVItemID != 0)
                        {
                            Address address = addressList.Where(c => c.AddressTVItemID == ((int)polSourceSiteModel.CivicAddressTVItemID)).FirstOrDefault();
                            if (address != null)
                            {
                                sbTemp.AppendLine($@"<p>");
                                if (_TaskRunnerBaseService._BWObj.appTaskModel.Language == LanguageEnum.fr)
                                {
                                    string CountryText      = countryList.Where(c => c.TVItemID == address.CountryTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string ProvinceText     = provinceList.Where(c => c.TVItemID == address.ProvinceTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string MunicipalityText = municipalityList.Where(c => c.TVItemID == address.MunicipalityTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string StreetTypeText   = _BaseEnumService.GetEnumText_StreetTypeEnum((StreetTypeEnum)address.StreetType);
                                    string AddressText      = $" { address.StreetNumber} { address.StreetName } { StreetTypeText }, { MunicipalityText }, { ProvinceText }, { CountryText }";
                                    sbTemp.AppendLine($@"<strong>{ TaskRunnerServiceRes.CivicAddress }</strong>: { AddressText }");
                                }
                                else
                                {
                                    string CountryText      = countryList.Where(c => c.TVItemID == address.CountryTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string ProvinceText     = provinceList.Where(c => c.TVItemID == address.ProvinceTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string MunicipalityText = municipalityList.Where(c => c.TVItemID == address.MunicipalityTVItemID).Select(c => c.TVText).FirstOrDefault();
                                    string StreetTypeText   = _BaseEnumService.GetEnumText_StreetTypeEnum((StreetTypeEnum)address.StreetType);
                                    string AddressText      = $" { address.StreetNumber}, { StreetTypeText } { address.StreetName }, { MunicipalityText }, { ProvinceText }, { CountryText }";
                                    sbTemp.AppendLine($@"<strong>{ TaskRunnerServiceRes.CivicAddress }</strong>: { AddressText }");
                                }
                                sbTemp.AppendLine($@"</p>");
                            }
                        }
                    }

                    PolSourceObservationModel polSourceObservationModel = polSourceObservationModelList.Where(c => c.PolSourceSiteID == polSourceSiteModel.PolSourceSiteID).OrderByDescending(c => c.ObservationDate_Local).FirstOrDefault();

                    if (polSourceObservationModel != null)
                    {
                        sbTemp.AppendLine($@"<p>");
                        string ContactObsText = contactList.Where(c => c.TVItemID == polSourceObservationModel.ContactTVItemID).Select(c => c.TVText).FirstOrDefault();
                        sbTemp.AppendLine($@"<strong>{ TaskRunnerServiceRes.LastObservationDate }</strong>: { polSourceObservationModel.ObservationDate_Local.ToString("yyyy MMMM dd") } <strong>{ TaskRunnerServiceRes.by }</strong>: { ContactObsText }");
                        sbTemp.AppendLine($@"</p>");

                        int IssueNumber = 0;
                        foreach (PolSourceObservationIssueModel polSourceObservationIssueModel in polSourceObservationIssueModelList.Where(c => c.PolSourceObservationID == polSourceObservationModel.PolSourceObservationID).OrderBy(c => c.Ordinal).ToList())
                        {
                            IssueNumber += 1;
                            string TVText = "";
                            sbTemp.AppendLine($@"<p><strong>{ TaskRunnerServiceRes.Issue }</strong>: { IssueNumber }</p>");
                            sbTemp.AppendLine($@"<blockquote>");
                            List <string> ObservationInfoList = (string.IsNullOrWhiteSpace(polSourceObservationIssueModel.ObservationInfo) ? new List <string>() : polSourceObservationIssueModel.ObservationInfo.Trim().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList());

                            for (int i = 0, countObs = ObservationInfoList.Count; i < countObs; i++)
                            {
                                string Temp = _BaseEnumService.GetEnumText_PolSourceObsInfoReportEnum((PolSourceObsInfoEnum)int.Parse(ObservationInfoList[i]));
                                switch (ObservationInfoList[i].Substring(0, 3))
                                {
                                case "101":
                                {
                                    Temp = Temp.Replace("Source", "<br /><strong>Source</strong>");
                                }
                                break;

                                //case "153":
                                //    {
                                //        Temp = Temp.Replace("Dilution Analyses", "     Dilution Analyses");
                                //    }
                                //    break;
                                case "250":
                                {
                                    Temp = Temp.Replace("Pathway", "<br /><strong>Pathway</strong>");
                                }
                                break;

                                case "900":
                                {
                                    Temp = Temp.Replace("Status", "<br /><strong>Status</strong>");
                                }
                                break;

                                case "910":
                                {
                                    Temp = Temp.Replace("Risk", "<br /><strong>Risk</strong>");
                                }
                                break;

                                case "110":
                                case "120":
                                case "122":
                                case "151":
                                case "152":
                                case "153":
                                case "155":
                                case "156":
                                case "157":
                                case "163":
                                case "166":
                                case "167":
                                case "170":
                                case "171":
                                case "172":
                                case "173":
                                case "176":
                                case "178":
                                case "181":
                                case "182":
                                case "183":
                                case "185":
                                case "186":
                                case "187":
                                case "190":
                                case "191":
                                case "192":
                                case "193":
                                case "194":
                                case "196":
                                case "198":
                                case "199":
                                case "220":
                                case "930":
                                {
                                    //Temp = @"<span class=""hidden"">" + Temp + "</span>";
                                }
                                break;

                                default:
                                    break;
                                }
                                TVText = TVText + Temp;
                            }

                            sbTemp.AppendLine($@"{ TVText }");
                            if (polSourceObservationIssueModel.ExtraComment != null)
                            {
                                if (polSourceObservationIssueModel.ExtraComment.Length > 0)
                                {
                                    sbTemp.AppendLine($@"<p><strong>{ TaskRunnerServiceRes.ExtraComment }</strong></p>");
                                    sbTemp.AppendLine($@"<p>");
                                    sbTemp.AppendLine($@"{ polSourceObservationIssueModel.ExtraComment }");
                                    sbTemp.AppendLine($@"</p>");
                                }
                            }
                            sbTemp.AppendLine($@"</blockquote>");
                        }
                    }

                    sbTemp.AppendLine($@"</div>");
                    sbTemp.AppendLine($@"<hr />");
                }
            }

            Percent = 98;
            _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, Percent);

            return(true);
        }
Example #7
0
        public bool CreateSamplesBC()
        {
            lblStatus.Text = "Starting ... CreateSamplesBC";
            Application.DoEvents();

            TVItemService   tvItemServiceR  = new TVItemService(LanguageEnum.en, user);
            MWQMRunService  mwqmRunService  = new MWQMRunService(LanguageEnum.en, user);
            MWQMSiteService mwqmSiteService = new MWQMSiteService(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 tvItemModelProv = tvItemServiceR.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelCanada.TVItemID, "British Columbia", TVTypeEnum.Province);

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

            List <TVItemModel> BCSubSectorLangList = tvItemServiceR.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProv.TVItemID, TVTypeEnum.Subsector);

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

            List <BCStation> BCWQMSiteList         = new List <BCStation>();
            TVItemModel      BCSubSector           = new TVItemModel();
            List <TT>        tideTextInDBList      = new List <TT>();
            List <AM>        analyseMethodInDBList = new List <AM>();
            List <Mat>       matrixInDBList        = new List <Mat>();
            List <Lab>       labInDBList           = new List <Lab>();

            int StartBCCreateSamplesBC = int.Parse(textBoxBCCreateSamplesBC.Text);

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

            foreach (TVItemModel tvItemModelSubsector in BCSubSectorLangList)
            {
                if (Cancel)
                {
                    return(false);
                }

                Count          += 1;
                lblStatus.Text  = (Count * 100 / TotalCount).ToString() + " ... CreateSamplesBC of " + tvItemModelSubsector.TVText;
                lblStatus2.Text = Count + " of " + TotalCount;
                Application.DoEvents();

                textBoxBCCreateSamplesBC.Text = Count.ToString();

                if (StartBCCreateSamplesBC > Count)
                {
                    continue;
                }

                List <MWQMRunModel> BCRunModelList = mwqmRunService.GetMWQMRunModelListWithSubsectorTVItemIDDB(tvItemModelSubsector.TVItemID);
                if (BCRunModelList.Count == 0)
                {
                    continue;
                }

                List <TVItemModel> tvItemModelList = tvItemServiceR.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.MWQMSite);
                if (tvItemModelList.Count == 0)
                {
                    return(false);
                }

                MWQMSampleService mwqmSampleService = new MWQMSampleService(LanguageEnum.en, user);

                List <MWQMSample> mwqmSampleList = new List <MWQMSample>();
                using (CSSPDBEntities dd = new CSSPDBEntities())
                {
                    mwqmSampleList = (from c in dd.MWQMSamples
                                      from ts in dd.TVItems
                                      from tr in dd.TVItems
                                      where c.MWQMSiteTVItemID == ts.TVItemID &&
                                      c.MWQMRunTVItemID == tr.TVItemID &&
                                      ts.ParentID == tvItemModelSubsector.TVItemID &&
                                      tr.ParentID == tvItemModelSubsector.TVItemID
                                      select c).Distinct().ToList();
                }

                // doing land samples

                List <TempData.BCLandSampleStation> bcLandSampleStation = new List <TempData.BCLandSampleStation>();

                using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
                {
                    string TVText = tvItemModelSubsector.TVText.Substring(0, 4);
                    bcLandSampleStation = (from c in dbDT.BCLandSampleStations
                                           where c.SS_STATION == TVText
                                           orderby c.BCLandSampleStationID
                                           select c).ToList <TempData.BCLandSampleStation>();
                }

                int countSta = 0;
                int totalSta = bcLandSampleStation.Count;
                foreach (TempData.BCLandSampleStation bcmss in bcLandSampleStation)
                {
                    if (Cancel)
                    {
                        return(false);
                    }

                    countSta       += 1;
                    lblStatus2.Text = "Doing Land Station " + bcmss.SS_STATION + " --- " + countSta + " of " + totalSta;
                    Application.DoEvents();

                    string TVText = bcmss.SS_STATION;

                    BCSubSector = (from c in BCSubSectorLangList where c.TVText.StartsWith(bcmss.SS_SHELLFI) select c).FirstOrDefault();
                    if (!CheckModelOK <TVItemModel>(BCSubSector))
                    {
                        continue;
                    }

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

                    TVItemModel tvItemModelMWQMSite = tvItemModelList.Where(c => c.TVText == TVText).FirstOrDefault();
                    if (tvItemModelMWQMSite == null)
                    {
                        richTextBoxStatus.AppendText("Could not find MWQMSite [" + TVText + "]");
                        return(false);
                    }

                    List <TempData.BCLandSample> bcLandSampleList = new List <TempData.BCLandSample>();

                    using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
                    {
                        bcLandSampleList = (from c in dbDT.BCLandSamples
                                            where c.SR_STATION_CODE == bcmss.SS_STATION
                                            orderby c.SR_READING_DATE
                                            select c).ToList <TempData.BCLandSample>();
                    }

                    int countSample = 0;
                    int TotalSample = bcLandSampleList.Count;
                    foreach (TempData.BCLandSample bcms in bcLandSampleList)
                    {
                        if (Cancel)
                        {
                            return(false);
                        }
                        countSample    += 1;
                        lblStatus2.Text = "Doing Marine Station " + bcms.SR_STATION_CODE + " --- " + countSta + " of " + totalSta + " Sample " + countSample + " of " + TotalSample;
                        Application.DoEvents();

                        try
                        {
                            DateTime DayOfSample = (DateTime)(bcms.SR_READING_DATE);
                            string   SampleTime  = bcms.SR_READING_TIME;

                            if (SampleTime == null)
                            {
                                SampleTime = "0000";
                            }

                            DateTime SampleDate = new DateTime(DayOfSample.Year, DayOfSample.Month, DayOfSample.Day, (SampleTime.Length == 1 ? 0 : (SampleTime.Length == 3 ? (int.Parse(SampleTime.Substring(0, 1))) : (int.Parse(SampleTime.Substring(0, 1))))), (SampleTime.Length == 1 ? 0 : (SampleTime.Length == 3 ? (int.Parse(SampleTime.Substring(1, 2))) : (SampleTime.Substring(2, 2) == "60" ? 59 : (int.Parse(SampleTime.Substring(2, 2)))))), 0);

                            int FecCol = 0;
                            if (bcms.SR_FECAL_COLIFORM_IND == "<" && bcms.SR_FECAL_COLIFORM == 2)
                            {
                                FecCol = 1;
                            }
                            else
                            {
                                if (bcms.SR_FECAL_COLIFORM == null)
                                {
                                    continue;
                                }

                                FecCol = (int)bcms.SR_FECAL_COLIFORM;
                            }

                            MWQMRunModel mwqmRunModel = (from c in BCRunModelList
                                                         where c.SubsectorTVItemID == BCSubSector.TVItemID &&
                                                         c.DateTime_Local.Year == SampleDate.Year &&
                                                         c.DateTime_Local.Month == SampleDate.Month &&
                                                         c.DateTime_Local.Day == SampleDate.Day
                                                         select c).FirstOrDefault();

                            if (mwqmRunModel == null)
                            {
                                richTextBoxStatus.AppendText("Could not find run for date [" + SampleDate.ToString("yyyy MMM dd") + "] for subsector [" + BCSubSector.TVText + "]\r\n");
                                continue;
                                //return false;
                            }

                            bool SampleExist = (from c in mwqmSampleList
                                                where c.MWQMSiteTVItemID == tvItemModelMWQMSite.TVItemID &&
                                                c.MWQMRunTVItemID == mwqmRunModel.MWQMRunTVItemID &&
                                                c.SampleDateTime_Local == SampleDate &&
                                                c.FecCol_MPN_100ml == FecCol &&
                                                c.Salinity_PPT == null &&
                                                c.WaterTemp_C == null &&
                                                c.SampleTypesText.Contains(((int)SampleTypeEnum.Routine).ToString())
                                                select c).Any();

                            if (!SampleExist)
                            {
                                MWQMSampleModel mwqmSampleModelNew = new MWQMSampleModel()
                                {
                                    MWQMSiteTVItemID     = tvItemModelMWQMSite.TVItemID,
                                    MWQMRunTVItemID      = mwqmRunModel.MWQMRunTVItemID,
                                    SampleDateTime_Local = SampleDate,
                                    Depth_m          = null,
                                    FecCol_MPN_100ml = FecCol,
                                    Salinity_PPT     = null,
                                    MWQMSampleNote   = (string.IsNullOrWhiteSpace(bcms.SR_OBS) == true ? "--" : bcms.SR_OBS.Trim()),
                                    WaterTemp_C      = null,
                                    SampleTypesText  = ((int)SampleTypeEnum.Routine).ToString() + ",",
                                    SampleTypeList   = new List <SampleTypeEnum>()
                                    {
                                        SampleTypeEnum.Routine
                                    },
                                };

                                MWQMSampleModel mwqmSampleModelRet = mwqmSampleService.GetMWQMSampleModelExistDB(mwqmSampleModelNew);
                                if (!string.IsNullOrWhiteSpace(mwqmSampleModelRet.Error))
                                {
                                    mwqmSampleModelRet = mwqmSampleService.PostAddMWQMSampleDB(mwqmSampleModelNew);
                                    if (!CheckModelOK <MWQMSampleModel>(mwqmSampleModelRet))
                                    {
                                        return(false);
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }

                // doing water samples
                List <TempData.BCMarineSampleStation> bcMarineSampleStation = new List <TempData.BCMarineSampleStation>();

                using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
                {
                    string TVText = tvItemModelSubsector.TVText.Substring(0, 4);
                    bcMarineSampleStation = (from c in dbDT.BCMarineSampleStations
                                             where c.SS_SHELLFI == TVText
                                             orderby c.BCMarineSampleStationID
                                             select c).ToList <TempData.BCMarineSampleStation>();
                }

                countSta = 0;
                totalSta = bcMarineSampleStation.Count;
                foreach (TempData.BCMarineSampleStation bcmss in bcMarineSampleStation)
                {
                    if (Cancel)
                    {
                        return(false);
                    }

                    countSta       += 1;
                    lblStatus2.Text = "Doing Marine Sample " + countSta + " of " + totalSta;
                    Application.DoEvents();

                    string TVText = bcmss.SS_STATION;

                    BCSubSector = (from c in BCSubSectorLangList where c.TVText.StartsWith(bcmss.SS_SHELLFI) select c).FirstOrDefault();
                    if (!CheckModelOK <TVItemModel>(BCSubSector))
                    {
                        return(false);
                    }

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

                    TVItemModel tvItemModelMWQMSite = tvItemModelList.Where(c => c.TVText == TVText).FirstOrDefault();
                    if (tvItemModelMWQMSite == null)
                    {
                        richTextBoxStatus.AppendText("Could not find MWQMSite [" + TVText + "]");
                        return(false);
                    }

                    List <TempData.BCMarineSample> bcMarineSampleList = new List <TempData.BCMarineSample>();

                    using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
                    {
                        bcMarineSampleList = (from c in dbDT.BCMarineSamples
                                              where c.SR_STATION_CODE == bcmss.SS_STATION
                                              orderby c.SR_READING_DATE
                                              select c).ToList <TempData.BCMarineSample>();
                    }

                    int countSample = 0;
                    int TotalSample = bcMarineSampleList.Count;
                    foreach (TempData.BCMarineSample bcms in bcMarineSampleList)
                    {
                        if (Cancel)
                        {
                            return(false);
                        }
                        countSample    += 1;
                        lblStatus2.Text = "Doing Marine station " + bcms.SR_STATION_CODE + " ----" + countSta + " of " + totalSta + " Sample " + countSample + " of " + TotalSample;
                        Application.DoEvents();

                        try
                        {
                            DateTime DayOfSample = (DateTime)(bcms.SR_READING_DATE);
                            string   SampleTime  = bcms.SR_READING_TIME;

                            if (SampleTime == null)
                            {
                                SampleTime = "0000";
                            }

                            if (SampleTime == "093")
                            {
                                SampleTime = "0930";
                            }
                            if (SampleTime == "080")
                            {
                                SampleTime = "0800";
                            }
                            if (SampleTime == "073")
                            {
                                SampleTime = "0730";
                            }
                            if (SampleTime == "060")
                            {
                                SampleTime = "0600";
                            }

                            DateTime SampleDate = new DateTime(DayOfSample.Year, DayOfSample.Month, DayOfSample.Day, (SampleTime.Length == 1 ? 0 : (SampleTime.Length == 3 ? (int.Parse(SampleTime.Substring(0, 1))) : (int.Parse(SampleTime.Substring(0, 1))))), (SampleTime.Length == 1 ? 0 : (SampleTime.Length == 3 ? (int.Parse(SampleTime.Substring(1, 2))) : (SampleTime.Substring(2, 2) == "60" ? 59 : (int.Parse(SampleTime.Substring(2, 2)))))), 0);

                            int FecCol = 0;
                            if (bcms.SR_FECAL_COLIFORM_IND == "<" && bcms.SR_FECAL_COLIFORM == 2)
                            {
                                FecCol = 1;
                            }
                            else
                            {
                                FecCol = (int)bcms.SR_FECAL_COLIFORM;
                            }

                            MWQMRunModel mwqmRunModel = (from c in BCRunModelList
                                                         where c.SubsectorTVItemID == BCSubSector.TVItemID &&
                                                         c.DateTime_Local.Year == SampleDate.Year &&
                                                         c.DateTime_Local.Month == SampleDate.Month &&
                                                         c.DateTime_Local.Day == SampleDate.Day
                                                         select c).FirstOrDefault();

                            if (mwqmRunModel == null)
                            {
                                richTextBoxStatus.AppendText("Could not find run for date [" + SampleDate.ToString("yyyy MMM dd") + "] for subsector [" + BCSubSector.TVText + "]\r\n");
                                continue;
                                //return false;
                            }

                            bool SampleExist = (from c in mwqmSampleList
                                                where c.MWQMSiteTVItemID == tvItemModelMWQMSite.TVItemID &&
                                                c.MWQMRunTVItemID == mwqmRunModel.MWQMRunTVItemID &&
                                                c.SampleDateTime_Local == SampleDate &&
                                                c.FecCol_MPN_100ml == FecCol &&
                                                c.Salinity_PPT == bcms.SR_SALINITY &&
                                                c.WaterTemp_C == bcms.SR_TEMPERATURE &&
                                                c.SampleTypesText.Contains(((int)SampleTypeEnum.Routine).ToString())
                                                select c).Any();

                            if (!SampleExist)
                            {
                                MWQMSampleModel mwqmSampleModelNew = new MWQMSampleModel()
                                {
                                    MWQMSiteTVItemID     = tvItemModelMWQMSite.TVItemID,
                                    MWQMRunTVItemID      = mwqmRunModel.MWQMRunTVItemID,
                                    SampleDateTime_Local = SampleDate,
                                    Depth_m          = bcms.SR_SAMPLE_DEPTH,
                                    FecCol_MPN_100ml = FecCol,
                                    Salinity_PPT     = bcms.SR_SALINITY,
                                    MWQMSampleNote   = (string.IsNullOrWhiteSpace(bcms.SR_OBS) == true ? "--" : bcms.SR_OBS.Trim()),
                                    WaterTemp_C      = bcms.SR_TEMPERATURE,
                                    SampleTypesText  = ((int)SampleTypeEnum.Routine).ToString() + ",",
                                    SampleTypeList   = new List <SampleTypeEnum>()
                                    {
                                        SampleTypeEnum.Routine
                                    },
                                };

                                MWQMSampleModel mwqmSampleModelRet = mwqmSampleService.GetMWQMSampleModelExistDB(mwqmSampleModelNew);
                                if (!string.IsNullOrWhiteSpace(mwqmSampleModelRet.Error))
                                {
                                    mwqmSampleModelRet = mwqmSampleService.PostAddMWQMSampleDB(mwqmSampleModelNew);
                                    if (!CheckModelOK <MWQMSampleModel>(mwqmSampleModelRet))
                                    {
                                        return(false);
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }

            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);
        }
        private bool GenerateHTMLAllWQDataXlsx()
        {
            string NotUsed = "";

            int SubsectorTVItemID = 0;

            List <string> ParamValueList = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            string tempVal = GetParameters("TVItemID", ParamValueList);

            if (string.IsNullOrWhiteSpace(tempVal))
            {
                NotUsed = string.Format(TaskRunnerServiceRes._IsRequired, "TVItemID");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_IsRequired", "TVItemID");
            }
            SubsectorTVItemID = int.Parse(tempVal);

            using (CSSPDBEntities db2 = new CSSPDBEntities())
            {
                var subsectorItem = (from c in db2.TVItems
                                     from cl in db2.TVItemLanguages
                                     where c.TVItemID == cl.TVItemID &&
                                     c.TVItemID == SubsectorTVItemID &&
                                     cl.Language == (int)LanguageEnum.en
                                     select new { c, cl }).FirstOrDefault();


                string tvText  = subsectorItem.cl.TVText;
                string locator = tvText;
                string name    = tvText;

                if (tvText.Contains(" "))
                {
                    locator = tvText.Substring(0, tvText.IndexOf(" "));
                    name    = tvText.Substring(tvText.IndexOf(" ") + 1);
                }

                name = name.Trim();

                if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                {
                    name = name.Substring(1);
                }
                if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                {
                    name = name.Substring(1);
                }

                if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                {
                    name = name.Substring(0, name.Length - 1);
                }
                if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                {
                    name = name.Substring(0, name.Length - 1);
                }

                NotUsed = string.Format(TaskRunnerServiceRes.Creating_, $"{ locator } AllWQData.html");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("Creating_", $"{ locator } AllWQData.html");

                _TaskRunnerBaseService.SendStatusTextToDB(TextLanguageList);

                _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 10);

                sb.AppendLine("<!DOCTYPE html>");
                sb.AppendLine("");
                sb.AppendLine(@"<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">");
                sb.AppendLine("<head>");
                sb.AppendLine(@"    <meta charset=""utf-8"" />");
                sb.AppendLine("    <title></title>");
                //sb.AppendLine(@"    <style type=""text/css"">");
                //sb.AppendLine("        th,td {");
                //sb.AppendLine("            border: 1px solid black;");
                //sb.AppendLine("        }");
                //sb.AppendLine("    </style>");
                sb.AppendLine("</head>");
                sb.AppendLine("<body>");
                sb.AppendLine("<table>");
                sb.AppendLine("<tr>");
                sb.AppendLine("<th colspan=7>");
                sb.AppendLine($"{ tvText } Water Quality Data");
                sb.AppendLine("</th>");
                sb.AppendLine("</tr>");
                sb.AppendLine("<tr>");
                sb.AppendLine("<th>");
                sb.AppendLine("Site");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Date");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Time");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Type");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("FC");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sal");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Temp");
                sb.AppendLine("</th>");
                sb.AppendLine("</tr>");

                List <MWQMSite> mwqmSiteList = (from c in db2.TVItems
                                                from s in db2.MWQMSites
                                                where c.TVItemID == s.MWQMSiteTVItemID &&
                                                c.TVType == (int)TVTypeEnum.MWQMSite &&
                                                c.TVPath.Contains(subsectorItem.c.TVPath + "p")
                                                orderby s.MWQMSiteNumber ascending
                                                select s).ToList();

                List <TVItemLanguage> tvItemLanguageList = (from c in db2.TVItems
                                                            from cl in db2.TVItemLanguages
                                                            where c.TVItemID == cl.TVItemID &&
                                                            c.TVType == (int)TVTypeEnum.MWQMSite &&
                                                            c.TVPath.Contains(subsectorItem.c.TVPath + "p") &&
                                                            c.ParentID == SubsectorTVItemID &&
                                                            cl.Language == (int)LanguageEnum.en
                                                            select cl).ToList();

                foreach (MWQMSite mwqmSite in mwqmSiteList)
                {
                    string mwqmSiteTVText = (from c in tvItemLanguageList
                                             where c.TVItemID == mwqmSite.MWQMSiteTVItemID
                                             select c.TVText).FirstOrDefault();

                    List <MWQMSample> mwqmSampleList = (from s in db2.MWQMSamples
                                                        where s.MWQMSiteTVItemID == mwqmSite.MWQMSiteTVItemID
                                                        orderby s.SampleDateTime_Local descending
                                                        select s).ToList();

                    foreach (MWQMSample mwqmSample in mwqmSampleList)
                    {
                        sb.AppendLine("<tr>");
                        sb.AppendLine("<th>");
                        sb.AppendLine($"{ mwqmSiteTVText }");
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        sb.AppendLine($"{ mwqmSample.SampleDateTime_Local.ToString("yyyy-MM-dd") }");
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        sb.AppendLine($"{ mwqmSample.SampleDateTime_Local.ToString("hh:mm") }");
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        string type = "";
                        if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Routine).ToString() },"))
                        {
                            type = "Routine";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.RainCMP).ToString() },"))
                        {
                            type = "RainCMP";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.RainRun).ToString() },"))
                        {
                            type = "RainRun";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.DailyDuplicate).ToString() },"))
                        {
                            type = "DailyDuplicate";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Infrastructure).ToString() },"))
                        {
                            type = "Infrastructure";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.IntertechDuplicate).ToString() },"))
                        {
                            type = "IntertechDuplicate";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.IntertechRead).ToString() },"))
                        {
                            type = "IntertechRead";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.ReopeningEmergencyRain).ToString() },"))
                        {
                            type = "ReopeningEmergencyRain";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.ReopeningSpill).ToString() },"))
                        {
                            type = "ReopeningSpill";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Sanitary).ToString() },"))
                        {
                            type = "Sanitary";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Study).ToString() },"))
                        {
                            type = "Study";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Sediment).ToString() },"))
                        {
                            type = "Sediment";
                        }
                        else if (mwqmSample.SampleTypesText.Contains($"{ ((int)SampleTypeEnum.Bivalve).ToString() },"))
                        {
                            type = "Bivalve";
                        }
                        else
                        {
                            type = "Error";
                        }
                        sb.AppendLine($"{ type }");
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        sb.AppendLine($"{ mwqmSample.FecCol_MPN_100ml }");
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        sb.AppendLine(mwqmSample.Salinity_PPT == null ? "" : mwqmSample.Salinity_PPT.Value.ToString("F1"));
                        sb.AppendLine("</th>");
                        sb.AppendLine("<th>");
                        sb.AppendLine(mwqmSample.WaterTemp_C == null ? "" : mwqmSample.WaterTemp_C.Value.ToString("F1"));
                        sb.AppendLine("</th>");
                        sb.AppendLine("</tr>");
                    }
                }

                sb.AppendLine("</table>");
                sb.AppendLine("</body>");
                sb.AppendLine("</html>");

                FileInfo fi = new FileInfo($@"C:\CSSP\{ locator } AllWQData.html");

                StreamWriter sw = fi.CreateText();
                sw.WriteLine(sb.ToString());
                sw.Close();

                return(true);
            }
        }
        private bool GenerateHTMLWQMSitesPhotoAlbumDocx()
        {
            string NotUsed = "";

            int SubsectorTVItemID = 0;

            List <string> ParamValueList = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            string tempVal = GetParameters("TVItemID", ParamValueList);

            if (string.IsNullOrWhiteSpace(tempVal))
            {
                NotUsed = string.Format(TaskRunnerServiceRes._IsRequired, "TVItemID");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_IsRequired", "TVItemID");
            }
            SubsectorTVItemID = int.Parse(tempVal);

            using (CSSPDBEntities db2 = new CSSPDBEntities())
            {
                var subsectorItem = (from c in db2.TVItems
                                     from cl in db2.TVItemLanguages
                                     where c.TVItemID == cl.TVItemID &&
                                     c.TVItemID == SubsectorTVItemID &&
                                     cl.Language == (int)LanguageEnum.en
                                     select new { c, cl }).FirstOrDefault();


                string tvText  = subsectorItem.cl.TVText;
                string locator = tvText;
                string name    = tvText;

                if (tvText.Contains(" "))
                {
                    locator = tvText.Substring(0, tvText.IndexOf(" "));
                    name    = tvText.Substring(tvText.IndexOf(" ") + 1);
                }

                name = name.Trim();

                if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                {
                    name = name.Substring(1);
                }
                if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                {
                    name = name.Substring(1);
                }

                if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                {
                    name = name.Substring(0, name.Length - 1);
                }
                if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                {
                    name = name.Substring(0, name.Length - 1);
                }

                NotUsed = string.Format(TaskRunnerServiceRes.Creating_, $"{ locator } SitePhotoAlbum.html");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("Creating_", $"{ locator } SitePhotoAlbum.html");

                _TaskRunnerBaseService.SendStatusTextToDB(TextLanguageList);

                _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 10);

                sb.AppendLine("<!DOCTYPE html>");
                sb.AppendLine("");
                sb.AppendLine(@"<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">");
                sb.AppendLine("<head>");
                sb.AppendLine(@"    <meta charset=""utf-8"" />");
                sb.AppendLine($"    <title>{ tvText }</title>");
                sb.AppendLine("</head>");
                sb.AppendLine("<body>");

                var tvItemList = (from c in db2.TVItems
                                  from cl in db2.TVItemLanguages
                                  from ms in db2.MWQMSites
                                  where c.TVItemID == cl.TVItemID &&
                                  c.TVItemID == ms.MWQMSiteTVItemID &&
                                  c.TVType == (int)TVTypeEnum.MWQMSite &&
                                  c.TVPath.Contains(subsectorItem.c.TVPath + "p") &&
                                  cl.Language == (int)LanguageEnum.en &&
                                  c.IsActive == true
                                  orderby cl.TVText ascending
                                  select new { c, cl, ms }).ToList();

                var tvFileList = (from c in db2.TVItems
                                  from cf in db2.TVFiles
                                  where c.TVItemID == cf.TVFileTVItemID &&
                                  c.TVType == (int)TVTypeEnum.File &&
                                  c.TVPath.Contains(subsectorItem.c.TVPath + "p")
                                  select new { c, cf }).ToList();

                int TotalPageCount = (int)Math.Ceiling((tvItemList.Count / 6.0D));
                int PageCount      = 0;
                for (int i = 0, count = tvItemList.Count; i < count; i += 6)
                {
                    PageCount++;

                    sb.AppendLine($"<h3>{ tvText }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;({ PageCount }/{ TotalPageCount })</h3>");
                    sb.AppendLine(@"<table style=""width: 95%; height: 95%;"">");
                    sb.AppendLine(@"<tr style=""height: 32%"">");

                    for (int j = 0; j < 6; j++)
                    {
                        if ((i + j) < tvItemList.Count)
                        {
                            var tvFileItem = (from c in tvFileList
                                              where c.c.TVPath.Contains(tvItemList[i + j].c.TVPath + "p") &&
                                              c.cf.ServerFileName.ToLower().Contains("monitoring.jpg")
                                              select c).FirstOrDefault();

                            if (tvFileItem == null)
                            {
                                sb.AppendLine(@"<td style=""width: 45%;"">");
                                sb.AppendLine("<br><br>");
                                sb.AppendLine($@"<span style=""font-size: 10px"">{ tvItemList[i + j].cl.TVText } No Image</span>");
                                sb.AppendLine("<br><br>");
                                sb.AppendLine($@"<span style=""font-size: 10px"">with name ending with monitoring.jpg</span>");
                                sb.AppendLine("</td>");
                            }
                            else
                            {
                                sb.AppendLine(@"<td style=""width: 45%;"">");
                                sb.AppendLine($@"|||Image|FileName,{ tvFileItem.cf.ServerFilePath }{ tvFileItem.cf.ServerFileName }|width,224|height,190|||");
                                sb.AppendLine("<br>");
                                if (tvItemList[i + j].ms.MWQMSiteDescription.Length > 50)
                                {
                                    sb.AppendLine($@"<span style=""font-size: 10px"">{ tvItemList[i + j].cl.TVText } --- { tvItemList[i + j].ms.MWQMSiteDescription.Substring(0, 50) } ...</span>");
                                }
                                else
                                {
                                    sb.AppendLine($@"<span style=""font-size: 10px"">{ tvItemList[i + j].cl.TVText } --- { tvItemList[i + j].ms.MWQMSiteDescription }</span>");
                                }
                                sb.AppendLine("<br>");
                                sb.AppendLine("</td>");
                            }
                        }
                        else
                        {
                            sb.AppendLine(@"<td style=""width: 45%;"">");
                            sb.AppendLine("<br><br><br>");
                            sb.AppendLine($@"&nbsp;");
                            sb.AppendLine("</td>");
                        }
                        if (j % 2 != 0)
                        {
                            sb.AppendLine("</tr>");
                            if (j != 5)
                            {
                                sb.AppendLine(@"<tr style=""height: 32%"">");
                            }
                        }
                        if (j == 5)
                        {
                            sb.AppendLine("</tr>");
                            sb.AppendLine("</table>");
                        }
                    }
                }

                sb.AppendLine("</body>");
                sb.AppendLine("</html>");

                FileInfo fi = new FileInfo($@"C:\CSSP\{ locator } SitePhotoAlbum.html");

                StreamWriter sw = fi.CreateText();
                sw.WriteLine(sb.ToString());
                sw.Close();

                return(true);
            }
        }
        private bool GenerateHTMLProvincialSubsectorsReviewXlsx()
        {
            string NotUsed    = "";
            bool   ErrorInDoc = false;

            int  ProvinceTVItemID     = 7;
            int  AfterYear            = 1989;
            int  NumberOfRuns         = 30;
            bool OnlyActiveSubsectors = true;
            bool OnlyActiveMWQMSites  = true;
            bool FullYear             = true;

            List <string> ParamValueList = Parameters.Split("|||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            string tempVal = GetParameters("TVItemID", ParamValueList);

            if (string.IsNullOrWhiteSpace(tempVal))
            {
                NotUsed = string.Format(TaskRunnerServiceRes._IsRequired, "TVItemID");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_IsRequired", "TVItemID");
            }
            ProvinceTVItemID = int.Parse(tempVal);
            tempVal          = GetParameters("AfterYear", ParamValueList);
            if (string.IsNullOrWhiteSpace(tempVal))
            {
                NotUsed = string.Format(TaskRunnerServiceRes._IsRequired, "AfterYear");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_IsRequired", "AfterYear");
            }
            tempVal = GetParameters("NumberOfRuns", ParamValueList);
            if (string.IsNullOrWhiteSpace(tempVal))
            {
                NotUsed = string.Format(TaskRunnerServiceRes._IsRequired, "NumberOfRuns");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("_IsRequired", "NumberOfRuns");
            }
            NumberOfRuns         = int.Parse(tempVal);
            OnlyActiveSubsectors = GetParameters("OnlyActiveSubsectors", ParamValueList) == "" ? false : true;
            OnlyActiveMWQMSites  = GetParameters("OnlyActiveMWQMSites", ParamValueList) == "" ? false : true;
            FullYear             = GetParameters("FullYear", ParamValueList) == "" ? false : true;

            string provInit = "";
            string prov     = "";

            List <string> ProvInitList = new List <string>()
            {
                "BC", "ME", "NB", "NL", "NS", "PE", "QC",
            };
            List <string> ProvList = new List <string>()
            {
                "British Columbia", "Maine", "New Brunswick", "Newfoundland and Labrador", "Nova Scotia", "Prince Edward Island", "Québec",
            };

            using (CSSPDBEntities db2 = new CSSPDBEntities())
            {
                var provItem = (from c in db2.TVItems
                                from cl in db2.TVItemLanguages
                                where c.TVItemID == cl.TVItemID &&
                                c.TVItemID == ProvinceTVItemID &&
                                cl.Language == (int)LanguageEnum.en
                                select new { c, cl }).FirstOrDefault();

                for (int i = 0; i < ProvList.Count; i++)
                {
                    if (ProvList[i] == provItem.cl.TVText)
                    {
                        provInit = ProvInitList[i];
                        prov     = ProvList[i];
                        break;
                    }
                }

                if (string.IsNullOrEmpty(provInit))
                {
                    return(false);
                }

                NotUsed = string.Format(TaskRunnerServiceRes.Creating_, $"{ provInit } Subsector Review.html");
                List <TextLanguage> TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("Creating_", $"{ provInit } Subsector Review.html");

                _TaskRunnerBaseService.SendStatusTextToDB(TextLanguageList);

                _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, 10);

                sb.AppendLine("<!DOCTYPE html>");
                sb.AppendLine("");
                sb.AppendLine(@"<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">");
                sb.AppendLine("<head>");
                sb.AppendLine(@"    <meta charset=""utf-8"" />");
                sb.AppendLine("    <title></title>");
                sb.AppendLine(@"    <style type=""text/css"">");
                sb.AppendLine("        th,td {");
                sb.AppendLine("            border: 1px solid black;");
                sb.AppendLine("        }");
                sb.AppendLine("    </style>");
                sb.AppendLine("</head>");
                sb.AppendLine("<body>");
                sb.AppendLine("<table>");
                sb.AppendLine("<tr>");
                sb.AppendLine("<th colspan=19>");
                sb.AppendLine("Data extrated from Webtools on DATE  (All-All-All, N= 30, Full year)");
                sb.AppendLine("</th>");
                sb.AppendLine("</tr>");
                sb.AppendLine("<tr>");
                sb.AppendLine("<th>");
                sb.AppendLine("Locator");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Name");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Max <br/># Samples");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Max-Min<br/>Years");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Approved <br/>with Red A to F rating");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Approved <br/>with Green F rating");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Restricted or Conditional Restricted <br/>with red F rating");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Restricted or Conditional Restricted <br/>with purple A-F rating");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Restricted or Conditional Restricted <br/>with green A to D rating");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Sites Classified as <br/>Unclassified");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("# Rain runs<br/> &ge; 12mm <br/>on Run day");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("# Rain runs<br/> &ge; 12mm <br/>0-24 hrs");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("# Rain runs<br/> &ge; 12mm <br/>24-48 hrs");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("# Rain runs<br/> &ge; 25mm <br/>0-24 hrs");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Missing Rain data <br/>in Webtools <br/>(Yes/No)");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Last Relay<br/>request year");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Last depuration<br/>request year");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("More Rain Runs Needed");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Action suggested");
                sb.AppendLine("</th>");
                sb.AppendLine("<th>");
                sb.AppendLine("Initials/Date reviewed");
                sb.AppendLine("</th>");
                sb.AppendLine("</tr>");

                sb2.AppendLine("<!DOCTYPE html>");
                sb2.AppendLine("");
                sb2.AppendLine(@"<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">");
                sb2.AppendLine("<head>");
                sb2.AppendLine(@"    <meta charset=""utf-8"" />");
                sb2.AppendLine("    <title></title>");
                sb2.AppendLine(@"    <style type=""text/css"">");
                sb2.AppendLine("        th,td {");
                sb2.AppendLine("            border: 1px solid black;");
                sb2.AppendLine("        }");
                sb2.AppendLine("    </style>");
                sb2.AppendLine("</head>");
                sb2.AppendLine("<body>");
                sb2.AppendLine("<table>");
                sb2.AppendLine("<tr>");
                sb2.AppendLine("<th colspan=8>");
                sb2.AppendLine("Data extrated from Webtools on DATE  (All-All-All, N= 30, Full year) by site");
                sb2.AppendLine("</th>");
                sb2.AppendLine("</tr>");
                sb2.AppendLine("<tr>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Locator");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Name");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("# Samples");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Years");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Site");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Currently <br/>Classified");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Stat <br/>Color");
                sb2.AppendLine("</th>");
                sb2.AppendLine("<th>");
                sb2.AppendLine("Stat <br/>Letter");
                sb2.AppendLine("</th>");
                sb2.AppendLine("</tr>");

                TVItem tvItemProv = (from c in db2.TVItems
                                     from cl in db2.TVItemLanguages
                                     where c.TVItemID == cl.TVItemID &&
                                     cl.Language == (int)LanguageEnum.en &&
                                     c.TVType == (int)TVTypeEnum.Province &&
                                     cl.TVText == prov
                                     select c).FirstOrDefault();

                var subsectorList = (from c in db2.TVItems
                                     from cl in db2.TVItemLanguages
                                     where c.TVItemID == cl.TVItemID &&
                                     cl.Language == (int)LanguageEnum.en &&
                                     c.TVType == (int)TVTypeEnum.Subsector &&
                                     c.TVPath.Contains(tvItemProv.TVPath + "p") &&
                                     (c.IsActive == true ||
                                      c.IsActive == OnlyActiveSubsectors)
                                     orderby cl.TVText ascending
                                     select new { c, cl }).ToList();

                int SSCount = 0;
                foreach (var subsector in subsectorList)
                {
                    SSCount += 1;

                    string tvText  = subsector.cl.TVText;
                    string locator = tvText;
                    string name    = tvText;

                    if (tvText.Contains(" "))
                    {
                        locator = tvText.Substring(0, tvText.IndexOf(" "));
                        name    = tvText.Substring(tvText.IndexOf(" ") + 1);
                    }

                    name = name.Trim();

                    if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                    {
                        name = name.Substring(1);
                    }
                    if (!string.IsNullOrWhiteSpace(name) && name.StartsWith("("))
                    {
                        name = name.Substring(1);
                    }

                    if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                    {
                        name = name.Substring(0, name.Length - 1);
                    }
                    if (!string.IsNullOrWhiteSpace(name) && name.EndsWith(")"))
                    {
                        name = name.Substring(0, name.Length - 1);
                    }

                    if (SSCount % 10 == 0)
                    {
                        NotUsed          = string.Format(TaskRunnerServiceRes.Doing_, tvText);
                        TextLanguageList = _TaskRunnerBaseService.GetTextLanguageFormat1List("Doing_", tvText);
                        _TaskRunnerBaseService.SendStatusTextToDB(TextLanguageList);
                        _TaskRunnerBaseService.SendPercentToDB(_TaskRunnerBaseService._BWObj.appTaskModel.AppTaskID, (int)(10 + (80.0D * ((double)SSCount / (double)subsectorList.Count))));
                    }

                    List <MWQMSite> mwqmSiteList = (from c in db2.TVItems
                                                    from s in db2.MWQMSites
                                                    where c.TVItemID == s.MWQMSiteTVItemID &&
                                                    c.TVType == (int)TVTypeEnum.MWQMSite &&
                                                    c.TVPath.Contains(subsector.c.TVPath + "p") &&
                                                    (c.IsActive == true ||
                                                     c.IsActive == OnlyActiveMWQMSites)
                                                    orderby s.MWQMSiteNumber ascending
                                                    select s).ToList();

                    List <int> mwqmSiteTVItemIDList = (from c in mwqmSiteList
                                                       select c.MWQMSiteTVItemID).Distinct().ToList();

                    string            routine        = $"{ (int)SampleTypeEnum.Routine },";
                    List <MWQMSample> mwqmSampleList = (from s in db2.MWQMSamples
                                                        from c in mwqmSiteTVItemIDList
                                                        where s.MWQMSiteTVItemID == c &&
                                                        s.SampleTypesText.Contains(routine) &&
                                                        s.SampleDateTime_Local.Year > AfterYear
                                                        select s).ToList();

                    List <int> mwqmRunTVItemIDList = (from c in mwqmSampleList
                                                      select c.MWQMRunTVItemID).Distinct().ToList();

                    List <MWQMRun> mwqmRunList = (from r in db2.MWQMRuns
                                                  from c in mwqmRunTVItemIDList
                                                  where r.MWQMRunTVItemID == c &&
                                                  r.DateTime_Local.Year > AfterYear &&
                                                  r.RunSampleType == (int)SampleTypeEnum.Routine
                                                  select r).Distinct().ToList();


                    List <MWQMSiteClassStat> MWQMSiteClassStatList = new List <MWQMSiteClassStat>();

                    int MaxNumberOfSample = 0;
                    int SampleMaxYear     = 0;
                    int SampleMinYear     = 100000;

                    foreach (MWQMSite mwqmSite in mwqmSiteList)
                    {
                        MWQMSiteClassStat mwqmSiteClassStat = new MWQMSiteClassStat();
                        mwqmSiteClassStat.MWQMSite = mwqmSite;

                        var mwqmSampleListForMWQMSite = (from c in mwqmSampleList
                                                         where c.MWQMSiteTVItemID == mwqmSite.MWQMSiteTVItemID
                                                         orderby c.SampleDateTime_Local descending
                                                         select c).ToList();

                        int count    = 0;
                        int lastYear = 0;
                        foreach (MWQMSample mwqmSample in mwqmSampleListForMWQMSite)
                        {
                            count += 1;

                            if (count > NumberOfRuns)
                            {
                                if (!FullYear)
                                {
                                    break;
                                }

                                if (lastYear != mwqmSample.SampleDateTime_Local.Year)
                                {
                                    break;
                                }
                            }

                            mwqmSiteClassStat.MWQMSampleList.Add(mwqmSample);

                            lastYear = mwqmSample.SampleDateTime_Local.Year;
                        }

                        mwqmSiteClassStat.MWQMRunList = (from c in mwqmSiteClassStat.MWQMSampleList
                                                         from r in mwqmRunList
                                                         where c.MWQMRunTVItemID == r.MWQMRunTVItemID &&
                                                         c.MWQMSiteTVItemID == mwqmSite.MWQMSiteTVItemID
                                                         select r).Distinct().ToList();

                        if (mwqmSampleList.Count > 3)
                        {
                            List <double> mwqmSampleFCList = (from c in mwqmSiteClassStat.MWQMSampleList
                                                              where c.MWQMSiteTVItemID == mwqmSite.MWQMSiteTVItemID
                                                              orderby c.SampleDateTime_Local descending
                                                              select(c.FecCol_MPN_100ml < 2 ? 1.9D : (double)c.FecCol_MPN_100ml)).ToList <double>();

                            if (mwqmSampleFCList.Count > 3)
                            {
                                if (MaxNumberOfSample < mwqmSampleFCList.Count)
                                {
                                    MaxNumberOfSample = mwqmSampleFCList.Count;
                                }

                                double P90         = _TVItemService.GetP90(mwqmSampleFCList);
                                double GeoMean     = _TVItemService.GeometricMean(mwqmSampleFCList);
                                double Median      = _TVItemService.GetMedian(mwqmSampleFCList);
                                double PercOver43  = ((((double)mwqmSiteClassStat.MWQMSampleList.Where(c => c.FecCol_MPN_100ml > 43).Count()) / (double)mwqmSampleFCList.Count()) * 100.0D);
                                double PercOver260 = ((((double)mwqmSiteClassStat.MWQMSampleList.Where(c => c.FecCol_MPN_100ml > 260).Count()) / (double)mwqmSampleFCList.Count()) * 100.0D);
                                int    MinYear     = mwqmSiteClassStat.MWQMSampleList.Select(c => c.SampleDateTime_Local).Min().Year;
                                int    MaxYear     = mwqmSiteClassStat.MWQMSampleList.Select(c => c.SampleDateTime_Local).Max().Year;

                                if (SampleMaxYear < MaxYear)
                                {
                                    SampleMaxYear = MaxYear;
                                }

                                if (SampleMinYear > MinYear)
                                {
                                    SampleMinYear = MinYear;
                                }

                                LetterColorName letterColorName = new LetterColorName();

                                if ((GeoMean > 88) || (Median > 88) || (P90 > 260) || (PercOver260 > 10))
                                {
                                    if ((GeoMean > 181) || (Median > 181) || (P90 > 460) || (PercOver260 > 18))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "F", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                    else if ((GeoMean > 163) || (Median > 163) || (P90 > 420) || (PercOver260 > 17))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "E", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                    else if ((GeoMean > 144) || (Median > 144) || (P90 > 380) || (PercOver260 > 15))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "D", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                    else if ((GeoMean > 125) || (Median > 125) || (P90 > 340) || (PercOver260 > 13))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "C", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                    else if ((GeoMean > 107) || (Median > 107) || (P90 > 300) || (PercOver260 > 12))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "B", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                    else
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "A", Color = "Purple", Name = "NoDepuration"
                                        };
                                    }
                                }
                                else if ((GeoMean > 14) || (Median > 14) || (P90 > 43) || (PercOver43 > 10))
                                {
                                    if ((GeoMean > 76) || (Median > 76) || (P90 > 224) || (PercOver43 > 27))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "F", Color = "Red", Name = "Fail"
                                        };
                                    }
                                    else if ((GeoMean > 63) || (Median > 63) || (P90 > 188) || (PercOver43 > 23))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "E", Color = "Red", Name = "Fail"
                                        };
                                    }
                                    else if ((GeoMean > 51) || (Median > 51) || (P90 > 152) || (PercOver43 > 20))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "D", Color = "Red", Name = "Fail"
                                        };
                                    }
                                    else if ((GeoMean > 39) || (Median > 39) || (P90 > 115) || (PercOver43 > 17))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "C", Color = "Red", Name = "Fail"
                                        };
                                    }
                                    else if ((GeoMean > 26) || (Median > 26) || (P90 > 79) || (PercOver43 > 13))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "B", Color = "Red", Name = "Fail"
                                        };
                                    }
                                    else
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "A", Color = "Red", Name = "Fail"
                                        };
                                    }
                                }
                                else
                                {
                                    if ((GeoMean > 12) || (Median > 12) || (P90 > 36) || (PercOver43 > 8))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "F", Color = "Green", Name = "Pass"
                                        };
                                    }
                                    else if ((GeoMean > 9) || (Median > 9) || (P90 > 29) || (PercOver43 > 7))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "E", Color = "Green", Name = "Pass"
                                        };
                                    }
                                    else if ((GeoMean > 7) || (Median > 7) || (P90 > 22) || (PercOver43 > 5))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "D", Color = "Green", Name = "Pass"
                                        };
                                    }
                                    else if ((GeoMean > 5) || (Median > 5) || (P90 > 14) || (PercOver43 > 3))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "C", Color = "Green", Name = "Pass"
                                        };
                                    }
                                    else if ((GeoMean > 2) || (Median > 2) || (P90 > 7) || (PercOver43 > 2))
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "B", Color = "Green", Name = "Pass"
                                        };
                                    }
                                    else
                                    {
                                        letterColorName = new LetterColorName()
                                        {
                                            Letter = "A", Color = "Green", Name = "Pass"
                                        };
                                    }
                                }

                                mwqmSiteClassStat.LetterColorName = letterColorName;

                                sb2.AppendLine("<tr>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ locator }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ name }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ mwqmSampleFCList.Count }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ MaxYear }-{ MinYear }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber) }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ ((MWQMSiteLatestClassificationEnum)mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification).ToString() }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ mwqmSiteClassStat.LetterColorName.Color }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ mwqmSiteClassStat.LetterColorName.Letter }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("</tr>");
                            }
                            else
                            {
                                mwqmSiteClassStat.LetterColorName = new LetterColorName()
                                {
                                    Color = "ND", Letter = "ND", Name = "ND"
                                };

                                sb2.AppendLine("<tr>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ locator }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine($"{ name }");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("<th>");
                                sb2.AppendLine("ND");
                                sb2.AppendLine("</th>");
                                sb2.AppendLine("</tr>");
                            }
                        }
                        else
                        {
                            mwqmSiteClassStat.LetterColorName = new LetterColorName()
                            {
                                Color = "ND", Letter = "ND", Name = "ND"
                            };

                            sb2.AppendLine("<tr>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine($"{ locator }");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine($"{ name }");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("<th>");
                            sb2.AppendLine("ND");
                            sb2.AppendLine("</th>");
                            sb2.AppendLine("</tr>");
                        }

                        MWQMSiteClassStatList.Add(mwqmSiteClassStat);
                    }

                    sb.AppendLine("<tr>");
                    sb.AppendLine("<td>");
                    sb.Append($@"<a href=""http://131.235.1.167/csspwebtools/en-CA/#!View/a|||");
                    sb.Append($@"{ subsector.c.TVItemID }|||00000000001000000000000000000000"">{ locator }</a>");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ name }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ MaxNumberOfSample }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ SampleMaxYear }-{ SampleMinYear }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    if (mwqmSampleList.Count > 3)
                    {
                        foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                        {
                            if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Approved)
                            {
                                if (mwqmSiteClassStat.LetterColorName.Color == "Red")
                                {
                                    sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.AppendLine("ND");
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    if (mwqmSampleList.Count > 3)
                    {
                        foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                        {
                            if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Approved)
                            {
                                if (mwqmSiteClassStat.LetterColorName.Color == "Green" && mwqmSiteClassStat.LetterColorName.Letter == "F")
                                {
                                    sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.AppendLine("ND");
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    if (mwqmSampleList.Count > 3)
                    {
                        foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                        {
                            if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Restricted ||
                                mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.ConditionallyRestricted)
                            {
                                if (mwqmSiteClassStat.LetterColorName.Color == "Red" && mwqmSiteClassStat.LetterColorName.Letter == "F")
                                {
                                    sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.AppendLine("ND");
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    if (mwqmSampleList.Count > 3)
                    {
                        foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                        {
                            if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Restricted ||
                                mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.ConditionallyRestricted)
                            {
                                if (mwqmSiteClassStat.LetterColorName.Color == "Purple")
                                {
                                    sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.AppendLine("ND");
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    if (mwqmSampleList.Count > 3)
                    {
                        foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                        {
                            if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Restricted ||
                                mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.ConditionallyRestricted)
                            {
                                if (mwqmSiteClassStat.LetterColorName.Color == "Green" && !(mwqmSiteClassStat.LetterColorName.Letter == "F"))
                                {
                                    sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.AppendLine("ND");
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                    {
                        if (mwqmSiteClassStat.MWQMSite.MWQMSiteLatestClassification == (int)MWQMSiteLatestClassificationEnum.Error)
                        {
                            sb.Append($"{ RemoveStart0(mwqmSiteClassStat.MWQMSite.MWQMSiteNumber)},");
                        }
                    }
                    sb.AppendLine("</td>");
                    int  countRainDay            = 0;
                    int  countRainDay24h         = 0;
                    int  countRainDay24hOver25mm = 0;
                    int  countRainDay48h         = 0;
                    bool rainDataMissing         = false;

                    List <MWQMRun> MWQMRunList = new List <MWQMRun>();

                    foreach (MWQMSiteClassStat mwqmSiteClassStat in MWQMSiteClassStatList)
                    {
                        foreach (MWQMSample mwqmSample in mwqmSiteClassStat.MWQMSampleList)
                        {
                            MWQMRun mwqmRun = (from c in mwqmSiteClassStat.MWQMRunList
                                               where c.MWQMRunTVItemID == mwqmSample.MWQMRunTVItemID
                                               select c).FirstOrDefault();

                            if (mwqmRun != null)
                            {
                                if (!MWQMRunList.Where(c => c.MWQMRunTVItemID == mwqmRun.MWQMRunTVItemID).Any())
                                {
                                    MWQMRunList.Add(mwqmRun);
                                }
                            }
                        }
                    }

                    foreach (MWQMRun mwqmRun in MWQMRunList)
                    {
                        if (mwqmRun.RainDay0_mm == null || mwqmRun.RainDay1_mm == null || mwqmRun.RainDay2_mm == null)
                        {
                            rainDataMissing = true;
                        }

                        if (mwqmRun.RainDay0_mm >= 12)
                        {
                            countRainDay += 1;
                        }

                        if (mwqmRun.RainDay1_mm >= 12)
                        {
                            countRainDay24h += 1;
                        }

                        if (mwqmRun.RainDay1_mm >= 25)
                        {
                            countRainDay24hOver25mm += 1;
                        }

                        if (mwqmRun.RainDay2_mm >= 12)
                        {
                            countRainDay48h += 1;
                        }
                    }

                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ countRainDay }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ countRainDay24h }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ countRainDay48h }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine($"{ countRainDay24hOver25mm }");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine(rainDataMissing ? "Yes" : "No");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("");
                    sb.AppendLine("</td>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("");
                    sb.AppendLine("</td>");
                    sb.AppendLine("</tr>");
                }

                sb.AppendLine("</table>");
                sb.AppendLine("</body>");
                sb.AppendLine("</html>");

                //FileInfo fi = new FileInfo($@"C:\CSSP\{ provInit } Subsector Review.html");

                //StreamWriter sw = fi.CreateText();
                //sw.WriteLine(sb.ToString());
                //sw.Close();

                //FileInfo fiSite = new FileInfo($@"C:\CSSP\{ provInit } Subsector Review By Site.html");

                //StreamWriter swSite = fiSite.CreateText();
                //swSite.WriteLine(sb2.ToString());
                //swSite.Close();

                return(true);
            }
        }
Example #12
0
        public bool CreateStationsQC()
        {
            TVItemService         tvItemService         = new TVItemService(LanguageEnum.en, user);
            TVItemLanguageService tvItemLanguageService = new TVItemLanguageService(LanguageEnum.en, user);
            MapInfoService        mapInfoService        = new MapInfoService(LanguageEnum.en, user);
            MWQMSiteService       mwqmSiteService       = new MWQMSiteService(LanguageEnum.en, user);

            TVItemModel tvItemModelRoot = tvItemService.GetRootTVItemModelDB();

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

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

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

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

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

            List <TVItemModel> tvItemModelSubsectorQCList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelQC.TVItemID, TVTypeEnum.Subsector);

            if (tvItemModelSubsectorQCList.Count == 0)
            {
                richTextBoxStatus.AppendText("Could not find TVItem Subsector under British Columbia\r\n");
                return(false);
            }

            lblStatus.Text = "Starting ... CreateStationsQC";
            Application.DoEvents();

            int StartQCCreateStationQC = int.Parse(textBoxQCCreateStationsQC.Text);

            List <Obs>          obsTypeList                     = new List <Obs>();
            List <string>       sectorList                      = new List <string>();
            List <TT>           tideTextInDBList                = new List <TT>();
            List <AM>           analyseMethodInDBList           = new List <AM>();
            List <Mat>          matrixInDBList                  = new List <Mat>();
            List <Lab>          labInDBList                     = new List <Lab>();
            List <SampleStatus> sampleStatusInDBList            = new List <SampleStatus>();
            List <TempData.QCSubsectorAssociation> qcSubAssList = new List <TempData.QCSubsectorAssociation>();

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

            using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
            {
                sectorList = (from s in dbQC.geo_stations_p
                              where s.secteur != null
                              select s.secteur).Distinct().OrderBy(c => c).ToList();
            }

            List <TVItemModel> tvItemModelSubsectorList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelQC.TVItemID, TVTypeEnum.Subsector);
            List <TVItemModel> tvItemModelSiteList      = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelQC.TVItemID, TVTypeEnum.MWQMSite);

            TempData.QCSubsectorAssociation qcSubsectAss = new TempData.QCSubsectorAssociation();

            // doing every sector with the exception of MS__

            List <PCCSM.geo_stations_p> staQCList = new List <PCCSM.geo_stations_p>();

            using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
            {
                staQCList = (from c in dbQC.geo_stations_p
                             where (c.x != null && c.y != null) &&
                             c.secteur != null
                             orderby c.secteur, c.station
                             select c).ToList <PCCSM.geo_stations_p>();
            }

            List <TVItemLanguage> tvItemSiteLanguageList = new List <TVItemLanguage>();
            int TVItemIDSSOld = 0;
            int count         = 0;
            int total         = staQCList.Count;

            foreach (PCCSM.geo_stations_p geoStat in staQCList)
            {
                if (Cancel)
                {
                    return(false);
                }

                textBoxQCCreateStationsQC.Text = count.ToString();

                if (StartQCCreateStationQC > count)
                {
                    continue;
                }

                qcSubsectAss = (from c in qcSubAssList
                                where c.QCSectorText == geoStat.secteur
                                select c).FirstOrDefault <TempData.QCSubsectorAssociation>();

                if (qcSubsectAss == null)
                {
                    richTextBoxStatus.AppendText(geoStat.secteur + " does not exist\r\n");
                    //return false;
                    continue;
                }

                TVItemModel tvItemModelSubsector = (from c in tvItemModelSubsectorList
                                                    where c.TVText.StartsWith(qcSubsectAss.SubsectorText)
                                                    select c).FirstOrDefault();

                if (TVItemIDSSOld != tvItemModelSubsector.TVItemID)
                {
                    using (CSSPDBEntities db2 = new CSSPDBEntities())
                    {
                        tvItemSiteLanguageList = (from c in db2.TVItems
                                                  from cl in db2.TVItemLanguages
                                                  where c.TVItemID == cl.TVItemID &&
                                                  c.ParentID == tvItemModelSubsector.TVItemID &&
                                                  c.TVType == (int)TVTypeEnum.MWQMSite
                                                  select cl).ToList();
                    }

                    TVItemIDSSOld = tvItemModelSubsector.TVItemID;
                }

                if (tvItemModelSubsector == null)
                {
                    richTextBoxStatus.AppendText("could not find subsector" + geoStat.secteur + "\r\n");
                    //return false;
                    continue;
                }

                bool IsActive = true;
                if (geoStat.status != null)
                {
                    IsActive = (geoStat.status.Substring(0, 1) == "i" ? false : true);
                }

                string PreText = "";
                if (geoStat.secteur.Length < qcSubsectAss.SubsectorText.Length)
                {
                    PreText = "";
                }
                else
                {
                    if (geoStat.secteur.StartsWith(qcSubsectAss.SubsectorText))
                    {
                        PreText = geoStat.secteur.Substring(qcSubsectAss.SubsectorText.Length) + "_";
                    }
                    else
                    {
                        PreText = geoStat.secteur + "_";
                    }
                }
                if (PreText.StartsWith(".") || PreText.StartsWith("_"))
                {
                    PreText = PreText.Substring(1);
                }

                string MWQMSiteTVText = PreText + "0000".Substring(0, 4 - geoStat.station.ToString().Length) + geoStat.station.ToString();

                string subsector = tvItemModelSubsector.TVText;
                if (subsector.Contains(" "))
                {
                    subsector = subsector.Substring(0, subsector.IndexOf(" "));
                }

                count         += 1;
                lblStatus.Text = $"{subsector} --- {MWQMSiteTVText} --- { count.ToString()}/{total.ToString()}";
                Application.DoEvents();


                List <MapInfoModel> mapInfoModelList = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)geoStat.y, (float)geoStat.x, TVTypeEnum.Subsector);
                if (mapInfoModelList.Count == 0)
                {
                    //return false;
                    continue;
                }

                TVItemModel tvItemModel = (from c in tvItemModelSiteList
                                           where c.ParentID == tvItemModelSubsector.TVItemID &&
                                           c.TVText.EndsWith(MWQMSiteTVText)
                                           select c).FirstOrDefault();

                //TVItemModel tvItemModel = tvItemModelMWQMSiteList.Where(c => c.TVText.EndsWith(MWQMSiteTVText)).FirstOrDefault();
                if (tvItemModel == null)
                {
                    TVItemModel tvItemModelRet = tvItemService.PostCreateTVItem(tvItemModelSubsector.TVItemID, MWQMSiteTVText, MWQMSiteTVText, TVTypeEnum.MWQMSite);
                    if (!CheckModelOK <TVItemModel>(tvItemModelRet))
                    {
                        //return false;
                        continue;
                    }

                    if (geoStat.status == null)
                    {
                        tvItemModelRet.IsActive = false;
                    }
                    else
                    {
                        tvItemModelRet.IsActive = (geoStat.status.Substring(0, 1) == "i" ? false : true);
                    }

                    TVItemModel tvItemModelRet2 = tvItemService.PostUpdateTVItemDB(tvItemModelRet);
                    if (!CheckModelOK <TVItemModel>(tvItemModelRet2))
                    {
                        //return false;
                        continue;
                    }

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

                    MapInfoModel mapInfoModelRet = mapInfoService.CreateMapInfoObjectDB(coordList2, MapInfoDrawTypeEnum.Point, TVTypeEnum.MWQMSite, tvItemModelRet2.TVItemID);
                    if (!CheckModelOK <MapInfoModel>(mapInfoModelRet))
                    {
                        //return false;
                        continue;
                    }

                    // should add the QC station to WQMSite
                    MWQMSiteModel mwqmSiteModelNew = new MWQMSiteModel()
                    {
                        MWQMSiteTVItemID    = tvItemModelRet2.TVItemID,
                        MWQMSiteNumber      = geoStat.station.ToString(),
                        Ordinal             = (int)geoStat.station,
                        MWQMSiteTVText      = MWQMSiteTVText,
                        MWQMSiteDescription = "--"
                    };

                    MWQMSiteModel mwqmSiteModelRet = mwqmSiteService.PostAddMWQMSiteDB(mwqmSiteModelNew);
                    if (!CheckModelOK <MWQMSiteModel>(mwqmSiteModelRet))
                    {
                        //return false;
                        continue;
                    }
                }
                else
                {
                    TVItemLanguage tvItemLanguageEN = (from c in tvItemSiteLanguageList
                                                       where c.TVItemID == tvItemModel.TVItemID &&
                                                       c.Language == (int)LanguageEnum.en
                                                       select c).FirstOrDefault();

                    TVItemLanguage tvItemLanguageFR = (from c in tvItemSiteLanguageList
                                                       where c.TVItemID == tvItemModel.TVItemID &&
                                                       c.Language == (int)LanguageEnum.fr
                                                       select c).FirstOrDefault();

                    if (tvItemLanguageEN.TVText != MWQMSiteTVText || tvItemLanguageFR.TVText != MWQMSiteTVText)
                    {
                        foreach (LanguageEnum language in new List <LanguageEnum>()
                        {
                            LanguageEnum.en, LanguageEnum.fr
                        })
                        {
                            TVItemLanguageModel tvItemLanguageModel = tvItemLanguageService.GetTVItemLanguageModelWithTVItemIDAndLanguageDB(tvItemModel.TVItemID, language);
                            if (!CheckModelOK <TVItemLanguageModel>(tvItemLanguageModel))
                            {
                                //return false;
                                continue;
                            }

                            if (tvItemLanguageModel.TVText != MWQMSiteTVText)
                            {
                                tvItemLanguageModel.TVText = MWQMSiteTVText;

                                TVItemLanguageModel tvItemLanguageModelRet = tvItemLanguageService.PostUpdateTVItemLanguageDB(tvItemLanguageModel);
                                if (!CheckModelOK <TVItemLanguageModel>(tvItemLanguageModelRet))
                                {
                                    //return false;
                                    continue;
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }