public void DrawPolSourceSitesPoints_test()
        {
            csspWebToolsTaskRunner = new CSSPWebToolsTaskRunner();
            MapInfoService mapInfoService = new MapInfoService(LanguageEnum.en, csspWebToolsTaskRunner._TaskRunnerBaseService._User);
            TVItemService  tvItemService  = new TVItemService(LanguageEnum.en, csspWebToolsTaskRunner._TaskRunnerBaseService._User);

            Bitmap   bitmap        = new Bitmap(1280, 1200);
            Graphics g             = Graphics.FromImage(bitmap);
            int      GraphicWidth  = bitmap.Width;
            int      GraphicHeight = bitmap.Height;

            CoordMap coordMap = new CoordMap()
            {
                NorthEast = new Coord()
                {
                    Lat = 46.5364151f, Lng = -64.55215f, Ordinal = 0
                },
                SouthWest = new Coord()
                {
                    Lat = 46.23907f, Lng = -64.99161f, Ordinal = 0
                },
            };

            int SubsectorTVItemID = 635;

            List <MapInfoPointModel> mapInfoPointModelPolSourceSiteList = new List <MapInfoPointModel>();
            List <TVItemModel>       tvItemModelPolSourceSiteList       = new List <TVItemModel>();

            mapInfoPointModelPolSourceSiteList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithParentIDAndTVTypeAndMapInfoDrawTypeDB(SubsectorTVItemID, TVTypeEnum.PolSourceSite, MapInfoDrawTypeEnum.Point);
            tvItemModelPolSourceSiteList       = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(SubsectorTVItemID, TVTypeEnum.PolSourceSite).Where(c => c.IsActive == true).ToList();

            GoogleMapToPNG googleMapToPNG = new GoogleMapToPNG(); // (new TaskRunnerBaseService(new List<BWObj>()), "", "", "", "");

            googleMapToPNG.DrawPolSourceSitesPoints(g, GraphicWidth, GraphicHeight, coordMap, mapInfoPointModelPolSourceSiteList, tvItemModelPolSourceSiteList);
        }
        private void GenerateMunicipalityDocument(Document document)
        {
            Body      body      = new Body();
            Paragraph paragraph = new Paragraph();
            Run       run       = new Run();
            Table     table     = new Table();
            TableRow  tableRow  = new TableRow();
            TableCell tableCell = new TableCell();
            string    URL       = "";

            TVItemService     tvItemService     = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemStatService tvItemStatService = new TVItemStatService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

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

            if (!string.IsNullOrWhiteSpace(tvItemModelMunicipality.Error))
            {
                paragraph = DocxBase.AddParagraph(body);
                DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemModelMunicipality.Error);
            }

            //tvItemStatService.SetTVItemStatForTVItemIDAndParentsTVItemID(tvItemModelMunicipality.TVItemID);

            DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Heading1;
            DocxBase.CurrentJustificationValue = JustificationValues.Center;
            paragraph = DocxBase.AddParagraph(body);

            URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelMunicipality);
            run = DocxBase.AddRunHyperlink(paragraph, URL, tvItemModelMunicipality.TVText);

            List <TVItemModel> tvItemModelInfrastructureList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelMunicipality.TVItemID, TVTypeEnum.Infrastructure);

            foreach (TVItemModel tvItemModelInfrastructure in tvItemModelInfrastructureList)
            {
                DocxBase.CurrentParagraphStyle = ParagraphStyleEnum.Heading2;
                paragraph = DocxBase.AddParagraph(body);

                URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelInfrastructure);
                run = DocxBase.AddRunHyperlink(paragraph, URL, tvItemModelInfrastructure.TVText);
            }

            DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Normal;
            DocxBase.CurrentJustificationValue = JustificationValues.Left;
            paragraph = DocxBase.AddParagraph(body);

            paragraph = DocxBase.AddParagraph(body);

            DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "Etc ... ");

            DocxBase.AddSectionProp(body);

            document.Append(body);
        }
Exemplo n.º 3
0
        public void Generate(FileInfo fi)
        {
            TVItemService  tvItemService  = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MapInfoService mapInfoService = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            if (_TaskRunnerBaseService._BWObj.appTaskModel.Language == "fr")
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("fr-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
            }
            else
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");
            }

            TVFileService tvFileService  = new TVFileService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            string        ServerFilePath = tvFileService.GetServerFilePath(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            DirectoryInfo di = new DirectoryInfo(ServerFilePath);

            if (!di.Exists)
            {
                di.Create();
            }

            if (fi.Exists)
            {
                fi.Delete();
            }

            StringBuilder sbKMZ = new StringBuilder();

            sbKMZ.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
            sbKMZ.AppendLine(@"<kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom"">");
            sbKMZ.AppendLine(@"<Document>");
            sbKMZ.AppendLine(@"	<name>" + _TaskRunnerBaseService.generateDocParams.FileName + "</name>");

            sbKMZ.AppendLine(@"    <StyleMap id=""msn_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<Pair>");
            sbKMZ.AppendLine(@"			<key>normal</key>");
            sbKMZ.AppendLine(@"			<styleUrl>#sn_ylw-pushpin</styleUrl>");
            sbKMZ.AppendLine(@"		</Pair>");
            sbKMZ.AppendLine(@"		<Pair>");
            sbKMZ.AppendLine(@"			<key>highlight</key>");
            sbKMZ.AppendLine(@"			<styleUrl>#sh_ylw-pushpin</styleUrl>");
            sbKMZ.AppendLine(@"		</Pair>");
            sbKMZ.AppendLine(@"	</StyleMap>");
            sbKMZ.AppendLine(@"	<Style id=""sh_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<IconStyle>");
            sbKMZ.AppendLine(@"			<scale>1.2</scale>");
            sbKMZ.AppendLine(@"		</IconStyle>");
            sbKMZ.AppendLine(@"		<LineStyle>");
            sbKMZ.AppendLine(@"			<color>ff00ff00</color>");
            sbKMZ.AppendLine(@"			<width>1.5</width>");
            sbKMZ.AppendLine(@"		</LineStyle>");
            sbKMZ.AppendLine(@"		<PolyStyle>");
            sbKMZ.AppendLine(@"			<color>0000ff00</color>");
            sbKMZ.AppendLine(@"		</PolyStyle>");
            sbKMZ.AppendLine(@"	</Style>");
            sbKMZ.AppendLine(@"	<Style id=""sn_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<LineStyle>");
            sbKMZ.AppendLine(@"			<color>ff00ff00</color>");
            sbKMZ.AppendLine(@"			<width>1.5</width>");
            sbKMZ.AppendLine(@"		</LineStyle>");
            sbKMZ.AppendLine(@"		<PolyStyle>");
            sbKMZ.AppendLine(@"			<color>0000ff00</color>");
            sbKMZ.AppendLine(@"		</PolyStyle>");
            sbKMZ.AppendLine(@"	</Style>");

            TVItemModel tvItemModelProvince = tvItemService.GetTVItemModelWithTVItemIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);
            List <MapInfoPointModel> mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelProvince.TVItemID, TVTypeEnum.Province, MapInfoDrawTypeEnum.Point);

            sbKMZ.AppendLine(@"	<Folder>");
            sbKMZ.AppendLine(@"	<name>Province</name>");

            // Doing Point
            sbKMZ.AppendLine(@"	<Placemark>");
            sbKMZ.AppendLine(@"	<name>" + tvItemModelProvince.TVText + "</name>");
            sbKMZ.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
            //sbKMZ.AppendLine(@"	<description>");
            //sbKMZ.AppendLine(@"<![CDATA[");
            //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelRoot) + @""">" + tvItemModelRoot.TVText + "</a>");
            //sbKMZ.AppendLine(@"]]>");
            //sbKMZ.AppendLine(@"	</description>");
            sbKMZ.AppendLine(@"	<Point>");
            sbKMZ.AppendLine(@"		<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
            sbKMZ.AppendLine(@"	</Point>");
            sbKMZ.AppendLine(@"	</Placemark>");

            // Doing Polygon
            sbKMZ.AppendLine(@"	<Placemark>");
            sbKMZ.AppendLine(@"		<name>"+ tvItemModelProvince.TVText + " (poly)</name>");
            sbKMZ.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
            //sbKMZ.AppendLine(@"	<description>");
            //sbKMZ.AppendLine(@"<![CDATA[");
            //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelRoot) + @""">" + tvItemModelRoot.TVText + "</a>");
            //sbKMZ.AppendLine(@"]]>");
            //sbKMZ.AppendLine(@"	</description>");
            sbKMZ.AppendLine(@"		<Polygon>");
            sbKMZ.AppendLine(@"			<outerBoundaryIs>");
            sbKMZ.AppendLine(@"				<LinearRing>");
            sbKMZ.AppendLine(@"					<coordinates>");
            sbKMZ.AppendLine(@"		"+ (mapInfoPointModelList[0].Lng - 0.1) + "," + (mapInfoPointModelList[0].Lat - 0.1) + ",0");
            sbKMZ.AppendLine(@"		"+ (mapInfoPointModelList[0].Lng + 0.1) + "," + (mapInfoPointModelList[0].Lat - 0.1) + ",0");
            sbKMZ.AppendLine(@"		"+ (mapInfoPointModelList[0].Lng + 0.1) + "," + (mapInfoPointModelList[0].Lat + 0.1) + ",0");
            sbKMZ.AppendLine(@"		"+ (mapInfoPointModelList[0].Lng - 0.1) + "," + (mapInfoPointModelList[0].Lat + 0.1) + ",0");
            sbKMZ.AppendLine(@"		"+ (mapInfoPointModelList[0].Lng - 0.1) + "," + (mapInfoPointModelList[0].Lat - 0.1) + ",0");
            sbKMZ.AppendLine(@"					</coordinates>");
            sbKMZ.AppendLine(@"				</LinearRing>");
            sbKMZ.AppendLine(@"			</outerBoundaryIs>");
            sbKMZ.AppendLine(@"		</Polygon>");
            sbKMZ.AppendLine(@"	</Placemark>");

            sbKMZ.AppendLine(@" <Folder>");
            sbKMZ.AppendLine(@"	<name>Areas</name>");
            List <TVItemModel> tvItemModelAreaList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProvince.TVItemID, TVTypeEnum.Area);

            foreach (TVItemModel tvItemModelArea in tvItemModelAreaList)
            {
                // Doing point
                sbKMZ.AppendLine(@"	<Placemark>");
                sbKMZ.AppendLine(@"	<name>" + tvItemModelArea.TVText + "</name>");
                sbKMZ.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                //sbKMZ.AppendLine(@"	<description>");
                //sbKMZ.AppendLine(@"<![CDATA[");
                //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                //sbKMZ.AppendLine(@"]]>");
                //sbKMZ.AppendLine(@"	</description>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelArea.TVItemID, TVTypeEnum.Area, MapInfoDrawTypeEnum.Point);

                sbKMZ.AppendLine(@"		<Point>");
                sbKMZ.AppendLine(@"			<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
                sbKMZ.AppendLine(@"		</Point>");
                sbKMZ.AppendLine(@"	</Placemark>");

                // Doing Polygon
                sbKMZ.AppendLine(@"	<Placemark>");
                sbKMZ.AppendLine(@"		<name>"+ tvItemModelArea.TVText + " (poly)</name>");
                sbKMZ.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                //sbKMZ.AppendLine(@"	<description>");
                //sbKMZ.AppendLine(@"<![CDATA[");
                //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                //sbKMZ.AppendLine(@"]]>");
                //sbKMZ.AppendLine(@"	</description>");
                sbKMZ.AppendLine(@"		<Polygon>");
                sbKMZ.AppendLine(@"			<outerBoundaryIs>");
                sbKMZ.AppendLine(@"				<LinearRing>");
                sbKMZ.AppendLine(@"					<coordinates>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelArea.TVItemID, TVTypeEnum.Area, MapInfoDrawTypeEnum.Polygon);
                foreach (MapInfoPointModel mapInfoPointModel in mapInfoPointModelList)
                {
                    sbKMZ.AppendLine(mapInfoPointModel.Lng + "," + mapInfoPointModel.Lat + ",0 ");
                }

                sbKMZ.AppendLine(@"					</coordinates>");
                sbKMZ.AppendLine(@"				</LinearRing>");
                sbKMZ.AppendLine(@"			</outerBoundaryIs>");
                sbKMZ.AppendLine(@"		</Polygon>");
                sbKMZ.AppendLine(@"	</Placemark>");
            }
            sbKMZ.AppendLine(@" </Folder>");

            sbKMZ.AppendLine(@"	</Folder>");

            sbKMZ.AppendLine(@"</Document>");
            sbKMZ.AppendLine(@"</kml>");

            StreamWriter sw = fi.CreateText();

            sw.Write(sbKMZ.ToString());

            sw.Close();
        }
Exemplo n.º 4
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 Generate(FileInfo fi)
        {
            if (_TaskRunnerBaseService._BWObj.appTaskModel.Language == "fr")
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("fr-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
            }
            else
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");
            }

            TVFileService tvFileService  = new TVFileService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            string        ServerFilePath = tvFileService.GetServerFilePath(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            DirectoryInfo di = new DirectoryInfo(ServerFilePath);

            if (!di.Exists)
            {
                di.Create();
            }

            if (fi.Exists)
            {
                fi.Delete();
            }

            StringBuilder sbHTML = new StringBuilder();

            TVItemService tvItemService   = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemModel   tvItemModelRoot = tvItemService.GetRootTVItemModelDB();

            sbHTML.AppendLine(@"<!DOCTYPE html>");
            sbHTML.AppendLine(@"<html xmlns=""http://www.w3.org/1999/xhtml"">");
            sbHTML.AppendLine(@"<head>");
            sbHTML.AppendLine(@"<meta charset=""utf-8"">");
            sbHTML.AppendLine(@"<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">");
            sbHTML.AppendLine(@"<title>");
            sbHTML.AppendLine(tvItemModelRoot.TVText);
            sbHTML.AppendLine(@"</title>");
            sbHTML.AppendLine(@"</head>");
            sbHTML.AppendLine(@"<body>");

            List <TVItemModel> tvItemModelList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelRoot.TVItemID, TVTypeEnum.Country);

            sbHTML.AppendLine(@"<ul>");
            foreach (TVItemModel tvItemModelCountry in tvItemModelList)
            {
                sbHTML.AppendLine(@"<li>");
                sbHTML.AppendLine(@"" + tvItemModelCountry.TVText + "");
                sbHTML.AppendLine(@"</li>");
            }
            sbHTML.AppendLine(@"</ul>");
            sbHTML.AppendLine(@"</body>");
            sbHTML.AppendLine(@"</html>");

            StreamWriter sw = fi.CreateText();

            sw.Write(sbHTML.ToString());

            sw.Close();
        }
        private void GenerateSubsectorFaecalColiformDensitiesDocument(Document document)
        {
            Body      body      = new Body();
            Paragraph paragraph = new Paragraph();
            Run       run       = new Run();
            Table     table     = new Table();
            TableRow  tableRow  = new TableRow();
            TableCell tableCell = new TableCell();
            //string URL = "";

            BaseEnumService      baseEnumService      = new BaseEnumService(_TaskRunnerBaseService._BWObj.appTaskModel.Language);
            TVItemService        tvItemService        = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemStatService    tvItemStatService    = new TVItemStatService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MWQMSampleService    mwqmSampleService    = new MWQMSampleService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MWQMSiteService      mwqmSiteService      = new MWQMSiteService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TideSiteService      tideSiteService      = new TideSiteService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TideDataValueService tideDataValueService = new TideDataValueService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

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

            if (!string.IsNullOrWhiteSpace(tvItemModelSubsector.Error))
            {
                paragraph = DocxBase.AddParagraph(body);
                DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemModelSubsector.Error);
            }

            //tvItemStatService.SetTVItemStatForTVItemIDAndParentsTVItemID(tvItemModelSubsector.TVItemID);

            TVItemModel tvItemModelTideSite = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.TideSite).FirstOrDefault();

            if (tvItemModelTideSite == null)
            {
                if (!string.IsNullOrWhiteSpace(tvItemModelSubsector.Error))
                {
                    paragraph = DocxBase.AddParagraph(body);
                    DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes.CoundNotFindTideSite);
                    return;
                }
            }

            List <TVItemModel> tvItemModelMWQMList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.MWQMSite);

            List <StationDateValue> stationDateValueList = new List <StationDateValue>();
            List <DateTime>         DateWithDataList     = new List <DateTime>();
            List <string>           StationList          = new List <string>();

            foreach (TVItemModel tvItemModelMWQM in tvItemModelMWQMList)
            {
                string Station = mwqmSiteService.GetMWQMSiteModelWithMWQMSiteTVItemIDDB(tvItemModelMWQM.TVItemID).MWQMSiteNumber;

                StationList.Add(Station);

                List <MWQMSampleModel> mwqmSampleModelList = mwqmSampleService.GetMWQMSampleModelListWithMWQMSiteTVItemIDDB(tvItemModelMWQM.TVItemID);

                foreach (MWQMSampleModel mwqmSampleModel in mwqmSampleModelList.OrderByDescending(c => c.SampleDateTime_Local))
                {
                    StationDateValue stationDateValue = new StationDateValue()
                    {
                        Station = Station,
                        Date    = new DateTime(mwqmSampleModel.SampleDateTime_Local.Year, mwqmSampleModel.SampleDateTime_Local.Month, mwqmSampleModel.SampleDateTime_Local.Day),
                        Value   = mwqmSampleModel.FecCol_MPN_100ml,
                    };

                    if (!DateWithDataList.Contains(stationDateValue.Date))
                    {
                        DateWithDataList.Add(stationDateValue.Date);
                    }

                    stationDateValueList.Add(stationDateValue);
                }
            }

            DateWithDataList = DateWithDataList.OrderBy(c => c).ToList();
            StationList      = StationList.OrderBy(c => c).ToList();

            for (int i = 0, count = DateWithDataList.Count; i < count; i = i + 15)
            {
                DocxBase.CurrentFontName           = FontNameEnum.Arial;
                DocxBase.CurrentFontSize           = 16;
                DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Caption;
                DocxBase.CurrentJustificationValue = JustificationValues.Left;
                paragraph = DocxBase.AddParagraph(body);
                paragraph = DocxBase.AddParagraph(body);

                string TableTitle = DocxServiceSubsectorFCDensitiesRes.Table + "1B-" + ((int)(i / 15) + 1).ToString() + "." + DocxServiceSubsectorFCDensitiesRes.FaecalColiformDensitiesMPNPer100 +
                                    " " + DocxServiceSubsectorFCDensitiesRes.For + " " + tvItemModelSubsector.TVText;
                run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, TableTitle);

                DocxBase.CurrentTableStyle = TableStyleEnum.PlainTable1;
                DocxBase.CurrentFontName   = FontNameEnum.Arial;
                DocxBase.CurrentFontSize   = 10;
                table    = DocxBase.AddTableStyle(body);
                tableRow = DocxBase.AddTableRow(table);

                List <DateTime> dateTimeNext15 = (from c in DateWithDataList
                                                  where c >= DateWithDataList[i]
                                                  select c).Take(15).ToList <DateTime>();

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, " ");
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes.Station);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, dateTime.ToString("yyyy"));
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, dateTime.ToString("dd MMM"));
                }

                List <StationDateValue> StationDateValueDataList = (from c in stationDateValueList
                                                                    orderby c.Station
                                                                    select c).ToList <StationDateValue>();

                foreach (string station in StationList)
                {
                    tableRow = DocxBase.AddTableRow(table);

                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, station);

                    foreach (DateTime dateTime in dateTimeNext15)
                    {
                        StationDateValue stationDateValueForDate = (from c in stationDateValueList
                                                                    where c.Station == station &&
                                                                    c.Date.Year == dateTime.Year &&
                                                                    c.Date.Month == dateTime.Month &&
                                                                    c.Date.Day == dateTime.Day
                                                                    select c).FirstOrDefault();

                        tableCell = DocxBase.AddTableCell(tableRow);
                        paragraph = DocxBase.AddTableCellParagraph(tableCell);
                        run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, (stationDateValueForDate == null ? " " : (stationDateValueForDate.Value < 2 ? "<2" : stationDateValueForDate.Value.ToString("F0"))));
                    }
                }

                // Tide Row
                tableRow = DocxBase.AddTableRow(table);

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes.Tide);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    TideDataValueModel tideDataValueModel = tideDataValueService.GetTideDataValueModelWithTideSiteTVItemIDAndDateDB(tvItemModelTideSite.TVItemID, dateTime);

                    string TideStartAccronym = GetTideTextAccronym(tideDataValueModel.TideStart);
                    string TideEndAccronym   = GetTideTextAccronym(tideDataValueModel.TideEnd);

                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, TideStartAccronym + "-" + TideEndAccronym);
                }

                // Rain (mm) Row
                tableRow = DocxBase.AddTableRow(table);

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes.Rain_mm);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "");
                }

                // 0-24 h Row
                tableRow = DocxBase.AddTableRow(table);

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes._0_24h);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "ToDo");
                }

                // 0-48 h Row
                tableRow = DocxBase.AddTableRow(table);

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes._0_48h);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "ToDo");
                }

                // 0-72 h Row
                tableRow = DocxBase.AddTableRow(table);

                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, DocxServiceSubsectorFCDensitiesRes._0_72h);

                foreach (DateTime dateTime in dateTimeNext15)
                {
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "ToDo");
                }
            }


            DocxBase.CurrentParagraphStyle = ParagraphStyleEnum.Quote;
            paragraph = DocxBase.AddParagraph(body);
            string NoteTxt = DocxServiceSubsectorFCDensitiesRes.Note + " : ";

            for (int i = 1, count = Enum.GetNames(typeof(TideTextEnum)).Length; i < count; i++)
            {
                NoteTxt = GetTideTextAccronym((TideTextEnum)i) + " = " + baseEnumService.GetEnumText_TideTextEnum((TideTextEnum)i) + " | ";
            }

            DocxBase.AddRunWithCurrentParagraphStyle(paragraph, NoteTxt);

            DocxBase.AddSectionProp(body);

            document.Append(body);
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        private void GenerateCountryDocument(Document document)
        {
            Body      body      = new Body();
            Paragraph paragraph = new Paragraph();
            Run       run       = new Run();
            Table     table     = new Table();
            TableRow  tableRow  = new TableRow();
            TableCell tableCell = new TableCell();
            string    URL       = "";

            BaseEnumService   baseEnumService   = new BaseEnumService(_TaskRunnerBaseService._BWObj.appTaskModel.Language);
            TVItemService     tvItemService     = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemStatService tvItemStatService = new TVItemStatService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

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

            if (!string.IsNullOrWhiteSpace(tvItemModelCounty.Error))
            {
                paragraph = DocxBase.AddParagraph(body);
                DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemModelCounty.Error);
            }

            DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Heading1;
            DocxBase.CurrentJustificationValue = JustificationValues.Center;
            paragraph = DocxBase.AddParagraph(body);

            URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCounty);
            run = DocxBase.AddRunHyperlink(paragraph, URL, tvItemModelCounty.TVText);

            List <TVItemModel> tvItemModelProvinceList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelCounty.TVItemID, TVTypeEnum.Province);

            foreach (TVItemModel tvItemModelProvince in tvItemModelProvinceList)
            {
                //tvItemStatService.SetTVItemStatForTVItemIDAndParentsTVItemID(tvItemModelProvince.TVItemID);

                DocxBase.CurrentParagraphStyle = ParagraphStyleEnum.Heading2;
                paragraph = DocxBase.AddParagraph(body);

                URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelProvince);
                run = DocxBase.AddRunHyperlink(paragraph, URL, tvItemModelProvince.TVText);

                DocxBase.CurrentTableStyle = TableStyleEnum.ListTable7Colorful_Accent5;
                table    = DocxBase.AddTableStyle(body);
                tableRow = DocxBase.AddTableRow(table);

                // Doing Items
                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "Items");

                // Doing Count
                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "Count");

                List <TVItemStatModel> tvItemStatModelList = tvItemStatService.GetTVItemStatModelListWithTVItemIDDB(tvItemModelProvince.TVItemID);

                int count = 0;
                foreach (TVItemStatModel tvItemStatModel in tvItemStatModelList)
                {
                    count   += 1;
                    tableRow = DocxBase.AddTableRow(table);

                    // Doing Item
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, baseEnumService.GetEnumText_TVTypeEnum(tvItemStatModel.TVType));

                    // Doing number
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);

                    run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemStatModel.ChildCount.ToString());
                }
            }

            DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Normal;
            DocxBase.CurrentJustificationValue = JustificationValues.Left;
            paragraph = DocxBase.AddParagraph(body);

            paragraph = DocxBase.AddParagraph(body);

            DocxBase.AddRunWithCurrentParagraphStyle(paragraph, "Etc ... ");

            DocxBase.AddSectionProp(body);

            document.Append(body);
        }
Exemplo n.º 9
0
        public bool CreateSanitaryBC()
        {
            lblStatus.Text = "Starting ... CreateSanitaryBC";
            Application.DoEvents();

            if (Cancel)
            {
                return(false);
            }

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

            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 tvItemModelBC = tvItemServiceR.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelCanada.TVItemID, "British Columbia", TVTypeEnum.Province);

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

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

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

            List <TempData.BCPolSource> bcPolSourceList = new List <TempData.BCPolSource>();

            using (TempData.TempDataToolDBEntities dbDT = new TempData.TempDataToolDBEntities())
            {
                bcPolSourceList = (from c in dbDT.BCPolSources
                                   orderby c.BCPolSourceID
                                   select c).ToList <TempData.BCPolSource>();
            }

            int StartBCCreateSanitarysBC = int.Parse(textBoxBCCreateSanitaryBC.Text);

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

            foreach (TempData.BCPolSource bcps in bcPolSourceList)
            {
                if (Cancel)
                {
                    return(false);
                }

                Count         += 1;
                lblStatus.Text = Count + " of " + TotalCount + " ... LoadSanitary BC";
                Application.DoEvents();

                textBoxBCCreateSanitaryBC.Text = Count.ToString();

                if (StartBCCreateSanitarysBC > Count)
                {
                    continue;
                }

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

                PolSourceSiteModel polSourceSiteModelNew = new PolSourceSiteModel();

                polSourceSiteModelNew.Oldsiteid = int.Parse(bcps.Key_.Substring(2));

                string LCODE = tvItemService.CleanText(bcps.LCode);
                string ICODE = tvItemService.CleanText(bcps.ICode);

                if (LCODE.Trim() == "")
                {
                    LCODE = "--";
                }

                if (ICODE.Trim() == "")
                {
                    ICODE = "--";
                }

                List <PolSourceObsInfoEnum> polSourceObsInfoList = GetPolSourceType(LCODE.Trim(), ICODE.Trim(), "BC");

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

                List <MapInfoModel> mapInfoModelListSubsector = new List <MapInfoModel>();
                if (bcps.Y_calc == 48.984828948974609f && bcps.X_calc == -123.02297973632812f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB(49.01f, (float)bcps.X_calc, TVTypeEnum.Subsector);
                }
                else if (bcps.Y_calc == 49.3099250793457f && bcps.X_calc == -121.77302551269531f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)-122.2, TVTypeEnum.Subsector);
                }
                else if (bcps.Y_calc == 48.3582878112793f && bcps.X_calc == -123.73906707763672f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)-123.72, TVTypeEnum.Subsector);
                }
                else if (bcps.Y_calc == 51.266487121582031f && bcps.X_calc == -128.20162963867187f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)-128, TVTypeEnum.Subsector);
                }
                else if (bcps.Y_calc == 55.91217041015625f && bcps.X_calc == -130.01992797851562f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)-129, TVTypeEnum.Subsector);
                }
                else if (bcps.Y_calc == 55.912052154541016f && bcps.X_calc == -130.01669311523437f)
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)-129, TVTypeEnum.Subsector);
                }
                else
                {
                    mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)bcps.Y_calc, (float)bcps.X_calc, TVTypeEnum.Subsector);
                }

                if (mapInfoModelListSubsector.Count == 0)
                {
                    richTextBoxStatus.AppendText("GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB did not find anything\r\n");
                    return(false);
                }

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

                int Site = (int)bcps.OBJECTID;

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

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

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

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

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

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

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

                List <Coord> coordList = new List <Coord>()
                {
                    new Coord()
                    {
                        Lat = (float)bcps.Y_calc,
                        Lng = (float)bcps.X_calc,
                    }
                };

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

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

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

                PolSourceObservationModel polSourceObservationModelNew = new PolSourceObservationModel();
                if (bcps.yyyymmdd == null)
                {
                    polSourceObservationModelNew.ObservationDate_Local = new DateTime(2050, 1, 1);
                }
                else
                {
                    polSourceObservationModelNew.ObservationDate_Local = (DateTime)bcps.yyyymmdd;
                }

                string Inspector = "unknown";
                if (!string.IsNullOrWhiteSpace(bcps.Verified))
                {
                    Inspector = bcps.Verified + " - (BC)";
                }

                string TVTextInspectorEN = "Inspector " + Inspector;
                string TVTextInspectorFR = "Inspecteur " + Inspector;

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

                polSourceObservationModelNew.ContactTVItemID = tvItemModelContactRet.TVItemID;
                string Observation = "(empty)";
                if (!string.IsNullOrWhiteSpace(bcps.Remarks))
                {
                    Observation = LCODE.Trim().ToUpper() + " - " + ICODE.Trim().ToUpper() + " - " + bcps.Remarks;
                }
                polSourceObservationModelNew.Observation_ToBeDeleted = Observation;
                polSourceObservationModelNew.PolSourceSiteID         = polSourceSiteModelRet.PolSourceSiteID;

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

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

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

            return(true);
        }
Exemplo n.º 10
0
        public bool CreateStationsBC()
        {
            if (Cancel)
            {
                return(false);
            }

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

            TVItemModel tvItemModelRoot = tvItemServiceR.GetRootTVItemModelDB();

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

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

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

            TVItemModel tvItemModelBC = tvItemServiceR.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelCanada.TVItemID, "British Columbia", TVTypeEnum.Province);

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

            List <TVItemModel> tvItemModelSubsectorBCList = tvItemServiceR.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelBC.TVItemID, TVTypeEnum.Subsector);

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

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

            int StartBCCreateStationBC = int.Parse(textBoxBCCreateStationsBC.Text);

            List <BCStation> BCWQMSiteList          = new List <BCStation>();
            TVItemModel      TVItemModelSubsectorBC = 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 TotalCount = tvItemModelSubsectorBCList.Count();
            int Count      = 0;

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

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

                textBoxBCCreateStationsBC.Text = Count.ToString();

                if (StartBCCreateStationBC > Count)
                {
                    continue;
                }

                // doing Land base stations

                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_SHELLFI == TVText
                                           orderby c.BCLandSampleStationID
                                           select c).ToList <TempData.BCLandSampleStation>();
                }

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

                    CountSta       += 1;
                    lblStatus2.Text = "Doing Land Base ... " + CountSta + " of " + TotalCountSta;
                    Application.DoEvents();

                    string TVText = bcmss.SS_STATION;

                    TVItemService   tvItemService   = new TVItemService(LanguageEnum.en, user);
                    MapInfoService  mapInfoService  = new MapInfoService(LanguageEnum.en, user);
                    MWQMSiteService mwqmSiteService = new MWQMSiteService(LanguageEnum.en, user);

                    TVItemModel tvItemModelMWQMSite = tvItemService.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelSubsector.TVItemID, TVText, TVTypeEnum.MWQMSite);
                    if (!string.IsNullOrWhiteSpace(tvItemModelMWQMSite.Error))
                    {
                        tvItemModelMWQMSite = tvItemService.PostCreateTVItem(tvItemModelSubsector.TVItemID, TVText, TVText, TVTypeEnum.MWQMSite);
                        if (!CheckModelOK <TVItemModel>(tvItemModelMWQMSite))
                        {
                            return(false);
                        }

                        List <Coord> coordList2 = new List <Coord>()
                        {
                            new Coord()
                            {
                                Lat = (float)(bcmss.LAT == null ? 50.0f : bcmss.LAT),
                                Lng = (float)(bcmss.LON == null ? -132.0f : bcmss.LON),
                            }
                        };

                        if (coordList2[0].Lat == 124.40966796875 && coordList2[0].Lng == -48.585498809814453)
                        {
                            coordList2[0].Lat = 48.585498809814453f;
                            coordList2[0].Lng = -124.40966796875f;
                        }

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

                        MWQMSiteModel mwqmSiteModelNew = new MWQMSiteModel()
                        {
                            MWQMSiteTVItemID    = tvItemModelMWQMSite.TVItemID,
                            MWQMSiteNumber      = bcmss.SS_STATION.ToString(),
                            MWQMSiteTVText      = TVText,
                            MWQMSiteDescription = "empty",
                        };

                        MWQMSiteModel mwqmSiteModelRet = mwqmSiteService.PostAddMWQMSiteDB(mwqmSiteModelNew);
                        if (!CheckModelOK <MWQMSiteModel>(mwqmSiteModelRet))
                        {
                            return(false);
                        }
                    }
                }

                // doing Marine base stations

                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;
                TotalCountSta = bcMarineSampleStation.Count;
                foreach (TempData.BCMarineSampleStation bcmss in bcMarineSampleStation)
                {
                    if (Cancel)
                    {
                        return(false);
                    }

                    CountSta       += 1;
                    lblStatus2.Text = "Doing Marine Base ... " + CountSta + " of " + TotalCountSta;
                    Application.DoEvents();

                    string TVText = bcmss.SS_STATION;

                    TVItemService   tvItemService   = new TVItemService(LanguageEnum.en, user);
                    MapInfoService  mapInfoService  = new MapInfoService(LanguageEnum.en, user);
                    MWQMSiteService mwqmSiteService = new MWQMSiteService(LanguageEnum.en, user);

                    TVItemModel tvItemModelMWQMSite = tvItemService.GetChildTVItemModelWithParentIDAndTVTextAndTVTypeDB(tvItemModelSubsector.TVItemID, TVText, TVTypeEnum.MWQMSite);
                    if (!string.IsNullOrWhiteSpace(tvItemModelMWQMSite.Error))
                    {
                        tvItemModelMWQMSite = tvItemService.PostCreateTVItem(tvItemModelSubsector.TVItemID, TVText, TVText, TVTypeEnum.MWQMSite);
                        if (!CheckModelOK <TVItemModel>(tvItemModelMWQMSite))
                        {
                            return(false);
                        }

                        List <Coord> coordList2 = new List <Coord>()
                        {
                            new Coord()
                            {
                                Lat = (float)(bcmss.LAT == null ? 50.0f : bcmss.LAT),
                                Lng = (float)(bcmss.LON == null ? -132.0f : bcmss.LON),
                            }
                        };

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

                        MWQMSiteModel mwqmSiteModelNew = new MWQMSiteModel()
                        {
                            MWQMSiteTVItemID    = tvItemModelMWQMSite.TVItemID,
                            MWQMSiteNumber      = bcmss.SS_STATION.ToString(),
                            MWQMSiteTVText      = TVText,
                            MWQMSiteDescription = "empty",
                        };

                        MWQMSiteModel mwqmSiteModelRet = mwqmSiteService.PostAddMWQMSiteDB(mwqmSiteModelNew);
                        if (!CheckModelOK <MWQMSiteModel>(mwqmSiteModelRet))
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
        public void Generate(FileInfo fi)
        {
            BaseEnumService       baseEnumService       = new BaseEnumService(_TaskRunnerBaseService._BWObj.appTaskModel.Language);
            TVItemService         tvItemService         = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MapInfoService        mapInfoService        = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            PolSourceSiteService  polSourceSiteService  = new PolSourceSiteService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            InfrastructureService infrastructureService = new InfrastructureService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            if (_TaskRunnerBaseService._BWObj.appTaskModel.Language == "fr")
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("fr-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
            }
            else
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");
            }

            TVFileService tvFileService  = new TVFileService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            string        ServerFilePath = tvFileService.GetServerFilePath(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            DirectoryInfo di = new DirectoryInfo(ServerFilePath);

            if (!di.Exists)
            {
                di.Create();
            }

            if (fi.Exists)
            {
                fi.Delete();
            }

            StringBuilder sbKML = new StringBuilder();

            sbKML.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
            sbKML.AppendLine(@"<kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom"">");
            sbKML.AppendLine(@"<Document>");
            sbKML.AppendLine(@"	<name>" + _TaskRunnerBaseService.generateDocParams.FileName + "</name>");

            sbKML.AppendLine(@"    <StyleMap id=""msn_ylw-pushpin"">");
            sbKML.AppendLine(@"		<Pair>");
            sbKML.AppendLine(@"			<key>normal</key>");
            sbKML.AppendLine(@"			<styleUrl>#sn_ylw-pushpin</styleUrl>");
            sbKML.AppendLine(@"		</Pair>");
            sbKML.AppendLine(@"		<Pair>");
            sbKML.AppendLine(@"			<key>highlight</key>");
            sbKML.AppendLine(@"			<styleUrl>#sh_ylw-pushpin</styleUrl>");
            sbKML.AppendLine(@"		</Pair>");
            sbKML.AppendLine(@"	</StyleMap>");
            sbKML.AppendLine(@"	<Style id=""sh_ylw-pushpin"">");
            sbKML.AppendLine(@"		<IconStyle>");
            sbKML.AppendLine(@"			<scale>1.2</scale>");
            sbKML.AppendLine(@"		</IconStyle>");
            sbKML.AppendLine(@"		<LineStyle>");
            sbKML.AppendLine(@"			<color>ff00ff00</color>");
            sbKML.AppendLine(@"			<width>1.5</width>");
            sbKML.AppendLine(@"		</LineStyle>");
            sbKML.AppendLine(@"		<PolyStyle>");
            sbKML.AppendLine(@"			<color>0000ff00</color>");
            sbKML.AppendLine(@"		</PolyStyle>");
            sbKML.AppendLine(@"	</Style>");
            sbKML.AppendLine(@"	<Style id=""sn_ylw-pushpin"">");
            sbKML.AppendLine(@"		<LineStyle>");
            sbKML.AppendLine(@"			<color>ff00ff00</color>");
            sbKML.AppendLine(@"			<width>1.5</width>");
            sbKML.AppendLine(@"		</LineStyle>");
            sbKML.AppendLine(@"		<PolyStyle>");
            sbKML.AppendLine(@"			<color>0000ff00</color>");
            sbKML.AppendLine(@"		</PolyStyle>");
            sbKML.AppendLine(@"	</Style>");

            sbKML.AppendLine(@"    <StyleMap id=""msn_grn-pushpin"">");
            sbKML.AppendLine(@"		<Pair>");
            sbKML.AppendLine(@"			<key>normal</key>");
            sbKML.AppendLine(@"			<styleUrl>#sn_grn-pushpin</styleUrl>");
            sbKML.AppendLine(@"		</Pair>");
            sbKML.AppendLine(@"		<Pair>");
            sbKML.AppendLine(@"			<key>highlight</key>");
            sbKML.AppendLine(@"			<styleUrl>#sh_grn-pushpin</styleUrl>");
            sbKML.AppendLine(@"		</Pair>");
            sbKML.AppendLine(@"	</StyleMap>");
            sbKML.AppendLine(@"	<Style id=""sh_grn-pushpin"">");
            sbKML.AppendLine(@"		<IconStyle>");
            sbKML.AppendLine(@"			<scale>1.2</scale>");
            sbKML.AppendLine(@"		</IconStyle>");
            sbKML.AppendLine(@"		<LineStyle>");
            sbKML.AppendLine(@"			<color>ff0000ff</color>");
            sbKML.AppendLine(@"			<width>1.5</width>");
            sbKML.AppendLine(@"		</LineStyle>");
            sbKML.AppendLine(@"		<PolyStyle>");
            sbKML.AppendLine(@"			<color>000000ff</color>");
            sbKML.AppendLine(@"		</PolyStyle>");
            sbKML.AppendLine(@"	</Style>");
            sbKML.AppendLine(@"	<Style id=""sn_grn-pushpin"">");
            sbKML.AppendLine(@"		<LineStyle>");
            sbKML.AppendLine(@"			<color>ff0000ff</color>");
            sbKML.AppendLine(@"			<width>1.5</width>");
            sbKML.AppendLine(@"		</LineStyle>");
            sbKML.AppendLine(@"		<PolyStyle>");
            sbKML.AppendLine(@"			<color>000000ff</color>");
            sbKML.AppendLine(@"		</PolyStyle>");
            sbKML.AppendLine(@"	</Style>");

            TVItemModel tvItemModelSubsector = tvItemService.GetTVItemModelWithTVItemIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);
            List <MapInfoPointModel> mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.Subsector, MapInfoDrawTypeEnum.Point);

            sbKML.AppendLine(@"	<Folder>");
            sbKML.AppendLine(@"	<name>Subsector</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");

            // Doing Point
            sbKML.AppendLine(@"	<Placemark>");
            sbKML.AppendLine(@"	<name>" + tvItemModelSubsector.TVText + "</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");
            sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
            //sbKMZ.AppendLine(@"	<description>");
            //sbKMZ.AppendLine(@"<![CDATA[");
            //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelRoot) + @""">" + tvItemModelRoot.TVText + "</a>");
            //sbKMZ.AppendLine(@"]]>");
            //sbKMZ.AppendLine(@"	</description>");
            sbKML.AppendLine(@"	<Point>");
            sbKML.AppendLine(@"		<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
            sbKML.AppendLine(@"	</Point>");
            sbKML.AppendLine(@"	</Placemark>");

            // Doing Polygon
            sbKML.AppendLine(@"	<Placemark>");
            sbKML.AppendLine(@"		<name>"+ tvItemModelSubsector.TVText + " (poly)</name>");
            sbKML.AppendLine(@"	    <visibility>0</visibility>");
            sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
            //sbKMZ.AppendLine(@"	<description>");
            //sbKMZ.AppendLine(@"<![CDATA[");
            //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
            //sbKMZ.AppendLine(@"]]>");
            //sbKMZ.AppendLine(@"	</description>");
            sbKML.AppendLine(@"		<Polygon>");
            sbKML.AppendLine(@"			<outerBoundaryIs>");
            sbKML.AppendLine(@"				<LinearRing>");
            sbKML.AppendLine(@"					<coordinates>");

            mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.Subsector, MapInfoDrawTypeEnum.Polygon);
            foreach (MapInfoPointModel mapInfoPointModel in mapInfoPointModelList)
            {
                sbKML.AppendLine(mapInfoPointModel.Lng + "," + mapInfoPointModel.Lat + ",0 ");
            }

            sbKML.AppendLine(@"					</coordinates>");
            sbKML.AppendLine(@"				</LinearRing>");
            sbKML.AppendLine(@"			</outerBoundaryIs>");
            sbKML.AppendLine(@"		</Polygon>");
            sbKML.AppendLine(@"	</Placemark>");

            // Doing Municipalities
            sbKML.AppendLine(@" <Folder>");
            sbKML.AppendLine(@"	<name>Municipalities</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");
            List <TVItemModel> tvItemModelMunicipalityList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.Municipality);

            foreach (TVItemModel tvItemModelMunicipality in tvItemModelMunicipalityList)
            {
                sbKML.AppendLine(@" <Folder>");
                sbKML.AppendLine(@"	<name>" + tvItemModelMunicipality.TVText + "</name>");
                sbKML.AppendLine(@"	<visibility>0</visibility>");
                // Doing point
                sbKML.AppendLine(@"	<Placemark>");
                sbKML.AppendLine(@"	<name>" + tvItemModelMunicipality.TVText + " ( Point)</name>");
                sbKML.AppendLine(@"	<visibility>0</visibility>");
                sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelMunicipality.TVItemID, TVTypeEnum.Municipality, MapInfoDrawTypeEnum.Point);

                sbKML.AppendLine(@"		<Point>");
                sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
                sbKML.AppendLine(@"		</Point>");
                sbKML.AppendLine(@"	</Placemark>");

                List <TVItemModel> tvItemModelInfrastructureList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelMunicipality.TVItemID, TVTypeEnum.Infrastructure);

                List <InfrastructureModel> infrastructureModelList = new List <InfrastructureModel>();

                foreach (TVItemModel tvItemModelInfrastructure in tvItemModelInfrastructureList)
                {
                    infrastructureModelList.Add(infrastructureService.GetInfrastructureModelWithInfrastructureTVItemIDDB(tvItemModelInfrastructure.TVItemID));
                }

                // Doing WWTP
                foreach (InfrastructureModel infrastructureModel in infrastructureModelList.Where(c => c.InfrastructureType == InfrastructureTypeEnum.WWTP).ToList())
                {
                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>" + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");

                    sbKML.AppendLine(@"	<description>");
                    sbKML.AppendLine(@"<![CDATA[");
                    sbKML.AppendLine(@"<pre>");
                    sbKML.AppendLine(@"Alarm System Type: " + baseEnumService.GetEnumText_AlarmSystemTypeEnum(infrastructureModel.AlarmSystemType) + "\r\n");
                    sbKML.AppendLine(@"Can overflow: " + infrastructureModel.CanOverflow.ToString() + "\r\n");
                    sbKML.AppendLine(@"Category: " + infrastructureModel.InfrastructureCategory + "\r\n");
                    sbKML.AppendLine(@"Collection System Type: " + baseEnumService.GetEnumText_CollectionSystemTypeEnum(infrastructureModel.CollectionSystemType) + "\r\n");
                    sbKML.AppendLine(@"Comments: " + infrastructureModel.Comment + "\r\n");
                    sbKML.AppendLine(@"DesignFlow (m3/day): " + infrastructureModel.DesignFlow_m3_day + "\r\n");
                    sbKML.AppendLine(@"Disinfection Type: " + baseEnumService.GetEnumText_DisinfectionTypeEnum(infrastructureModel.DisinfectionType) + "\r\n");
                    sbKML.AppendLine(@"Infrastructure Type: " + baseEnumService.GetEnumText_InfrastructureTypeEnum(infrastructureModel.InfrastructureType) + "\r\n");
                    sbKML.AppendLine(@"Average Flow (m3/day): " + infrastructureModel.AverageFlow_m3_day + "\r\n");
                    sbKML.AppendLine(@"AverageFlow_m3_day: " + infrastructureModel.PeakFlow_m3_day + "\r\n");
                    sbKML.AppendLine(@"Percent Flow Of Total (%): " + infrastructureModel.PercFlowOfTotal + "\r\n");
                    sbKML.AppendLine(@"Population Served: " + infrastructureModel.PopServed + "\r\n");
                    sbKML.AppendLine(@"Time Zone: " + infrastructureModel.TimeOffset_hour + "\r\n");
                    sbKML.AppendLine(@"Treatment Type: " + baseEnumService.GetEnumText_TreatmentTypeEnum(infrastructureModel.TreatmentType) + "\r\n");

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.WasteWaterTreatmentPlant, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureList.Count > 0)
                    {
                        sbKML.AppendLine(@"Latitude Longitude: " + mapInfoPointModelInfrastructureList[0].Lat + " " + mapInfoPointModelInfrastructureList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Latitude Longitude: \r\n");
                    }

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureOutfallList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureOutfallList.Count > 0)
                    {
                        sbKML.AppendLine(@"Outfall: Latitude Longitude: " + mapInfoPointModelInfrastructureOutfallList[0].Lat + " " + mapInfoPointModelInfrastructureOutfallList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Outfall: Latitude Longitude: \r\n");
                    }
                    sbKML.AppendLine("\r\n\r\n");
                    sbKML.AppendLine("Outfall Information\r\n\r\n");
                    sbKML.AppendLine(@"Average Depth (m): " + infrastructureModel.AverageDepth_m + "\r\n");
                    sbKML.AppendLine(@"Decay Rate (/day): " + infrastructureModel.DecayRate_per_day + "\r\n");
                    sbKML.AppendLine(@"Distance From Shore (m): " + infrastructureModel.DistanceFromShore_m + "\r\n");
                    sbKML.AppendLine(@"Far Field Velocity (m/s): " + infrastructureModel.FarFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Horizontal Angle (deg): " + infrastructureModel.HorizontalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"Near Field Velocity (m/s): " + infrastructureModel.NearFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Number Of Ports: " + infrastructureModel.NumberOfPorts + "\r\n");
                    sbKML.AppendLine(@"Port Diameter (m): " + infrastructureModel.PortDiameter_m + "\r\n");
                    sbKML.AppendLine(@"Port Elevation (m): " + infrastructureModel.PortElevation_m + "\r\n");
                    sbKML.AppendLine(@"Port Spacing (m): " + infrastructureModel.PortSpacing_m + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Concentration (FC /100 ml): " + infrastructureModel.ReceivingWater_MPN_per_100ml + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Salinity (PSU): " + infrastructureModel.ReceivingWaterSalinity_PSU + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Temperature (ºC): " + infrastructureModel.ReceivingWaterTemperature_C + "\r\n");
                    sbKML.AppendLine(@"Vertical Angle (deg): " + infrastructureModel.VerticalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"</pre>");
                    sbKML.AppendLine(@"]]>");
                    sbKML.AppendLine(@"	</description>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureList[0].Lng + "," + mapInfoPointModelInfrastructureList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");

                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>Outfall " + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_grn-pushpin</styleUrl>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureOutfallList[0].Lng + "," + mapInfoPointModelInfrastructureOutfallList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");
                }

                // Doing LS
                foreach (InfrastructureModel infrastructureModel in infrastructureModelList.Where(c => c.InfrastructureType == InfrastructureTypeEnum.LiftStation).ToList())
                {
                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>" + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");

                    sbKML.AppendLine(@"	<description>");
                    sbKML.AppendLine(@"<![CDATA[");
                    sbKML.AppendLine(@"<pre>");
                    sbKML.AppendLine(@"Alarm System Type: " + baseEnumService.GetEnumText_AlarmSystemTypeEnum(infrastructureModel.AlarmSystemType) + "\r\n");
                    sbKML.AppendLine(@"Can overflow: " + infrastructureModel.CanOverflow.ToString() + "\r\n");
                    sbKML.AppendLine(@"Category: " + infrastructureModel.InfrastructureCategory + "\r\n");
                    sbKML.AppendLine(@"Collection System Type: " + baseEnumService.GetEnumText_CollectionSystemTypeEnum(infrastructureModel.CollectionSystemType) + "\r\n");
                    sbKML.AppendLine(@"Comments: " + infrastructureModel.Comment + "\r\n");
                    sbKML.AppendLine(@"Infrastructure Type: " + baseEnumService.GetEnumText_InfrastructureTypeEnum(infrastructureModel.InfrastructureType) + "\r\n");
                    sbKML.AppendLine(@"Percent Flow Of Total (%): " + infrastructureModel.PercFlowOfTotal + "\r\n");

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.LiftStation, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureList.Count > 0)
                    {
                        sbKML.AppendLine(@"Latitude Longitude: " + mapInfoPointModelInfrastructureList[0].Lat + " " + mapInfoPointModelInfrastructureList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Latitude Longitude: \r\n");
                    }

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureOutfallList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureOutfallList.Count > 0)
                    {
                        sbKML.AppendLine(@"Outfall: Latitude Longitude: " + mapInfoPointModelInfrastructureOutfallList[0].Lat + " " + mapInfoPointModelInfrastructureOutfallList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Outfall: Latitude Longitude: \r\n");
                    }
                    sbKML.AppendLine("\r\n\r\n");
                    sbKML.AppendLine("Outfall Information\r\n\r\n");
                    sbKML.AppendLine(@"Average Depth (m): " + infrastructureModel.AverageDepth_m + "\r\n");
                    sbKML.AppendLine(@"Decay Rate (/day): " + infrastructureModel.DecayRate_per_day + "\r\n");
                    sbKML.AppendLine(@"Distance From Shore (m): " + infrastructureModel.DistanceFromShore_m + "\r\n");
                    sbKML.AppendLine(@"Far Field Velocity (m/s): " + infrastructureModel.FarFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Horizontal Angle (deg): " + infrastructureModel.HorizontalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"Near Field Velocity (m/s): " + infrastructureModel.NearFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Number Of Ports: " + infrastructureModel.NumberOfPorts + "\r\n");
                    sbKML.AppendLine(@"Port Diameter (m): " + infrastructureModel.PortDiameter_m + "\r\n");
                    sbKML.AppendLine(@"Port Elevation (m): " + infrastructureModel.PortElevation_m + "\r\n");
                    sbKML.AppendLine(@"Port Spacing (m): " + infrastructureModel.PortSpacing_m + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Concentration (FC /100 ml): " + infrastructureModel.ReceivingWater_MPN_per_100ml + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Salinity (PSU): " + infrastructureModel.ReceivingWaterSalinity_PSU + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Temperature (ºC): " + infrastructureModel.ReceivingWaterTemperature_C + "\r\n");
                    sbKML.AppendLine(@"Vertical Angle (deg): " + infrastructureModel.VerticalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"</pre>");
                    sbKML.AppendLine(@"]]>");
                    sbKML.AppendLine(@"	</description>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureList[0].Lng + "," + mapInfoPointModelInfrastructureList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");

                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>Outfall " + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_grn-pushpin</styleUrl>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureOutfallList[0].Lng + "," + mapInfoPointModelInfrastructureOutfallList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");
                }

                // Doing Line Overflow
                foreach (InfrastructureModel infrastructureModel in infrastructureModelList.Where(c => c.InfrastructureType == InfrastructureTypeEnum.LineOverflow).ToList())
                {
                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>" + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");

                    sbKML.AppendLine(@"	<description>");
                    sbKML.AppendLine(@"<![CDATA[");
                    sbKML.AppendLine(@"<pre>");
                    sbKML.AppendLine(@"Alarm System Type: " + baseEnumService.GetEnumText_AlarmSystemTypeEnum(infrastructureModel.AlarmSystemType) + "\r\n");
                    sbKML.AppendLine(@"Can overflow: " + infrastructureModel.CanOverflow.ToString() + "\r\n");
                    sbKML.AppendLine(@"Category: " + infrastructureModel.InfrastructureCategory + "\r\n");
                    sbKML.AppendLine(@"Collection System Type: " + baseEnumService.GetEnumText_CollectionSystemTypeEnum(infrastructureModel.CollectionSystemType) + "\r\n");
                    sbKML.AppendLine(@"Comments: " + infrastructureModel.Comment + "\r\n");
                    sbKML.AppendLine(@"Infrastructure Type: " + baseEnumService.GetEnumText_InfrastructureTypeEnum(infrastructureModel.InfrastructureType) + "\r\n");
                    sbKML.AppendLine(@"Percent Flow Of Total (%): " + infrastructureModel.PercFlowOfTotal + "\r\n");

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.LineOverflow, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureList.Count > 0)
                    {
                        sbKML.AppendLine(@"Latitude Longitude: " + mapInfoPointModelInfrastructureList[0].Lat + " " + mapInfoPointModelInfrastructureList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Latitude Longitude: \r\n");
                    }

                    List <MapInfoPointModel> mapInfoPointModelInfrastructureOutfallList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(infrastructureModel.InfrastructureTVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);

                    if (mapInfoPointModelInfrastructureOutfallList.Count > 0)
                    {
                        sbKML.AppendLine(@"Outfall: Latitude Longitude: " + mapInfoPointModelInfrastructureOutfallList[0].Lat + " " + mapInfoPointModelInfrastructureOutfallList[0].Lng + "\r\n");
                    }
                    else
                    {
                        sbKML.AppendLine("Outfall: Latitude Longitude: \r\n");
                    }
                    sbKML.AppendLine("\r\n\r\n");
                    sbKML.AppendLine("Outfall Information\r\n\r\n");
                    sbKML.AppendLine(@"Average Depth (m): " + infrastructureModel.AverageDepth_m + "\r\n");
                    sbKML.AppendLine(@"Decay Rate (/day): " + infrastructureModel.DecayRate_per_day + "\r\n");
                    sbKML.AppendLine(@"Distance From Shore (m): " + infrastructureModel.DistanceFromShore_m + "\r\n");
                    sbKML.AppendLine(@"Far Field Velocity (m/s): " + infrastructureModel.FarFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Horizontal Angle (deg): " + infrastructureModel.HorizontalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"Near Field Velocity (m/s): " + infrastructureModel.NearFieldVelocity_m_s + "\r\n");
                    sbKML.AppendLine(@"Number Of Ports: " + infrastructureModel.NumberOfPorts + "\r\n");
                    sbKML.AppendLine(@"Port Diameter (m): " + infrastructureModel.PortDiameter_m + "\r\n");
                    sbKML.AppendLine(@"Port Elevation (m): " + infrastructureModel.PortElevation_m + "\r\n");
                    sbKML.AppendLine(@"Port Spacing (m): " + infrastructureModel.PortSpacing_m + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Concentration (FC /100 ml): " + infrastructureModel.ReceivingWater_MPN_per_100ml + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Salinity (PSU): " + infrastructureModel.ReceivingWaterSalinity_PSU + "\r\n");
                    sbKML.AppendLine(@"Receiving Water Temperature (ºC): " + infrastructureModel.ReceivingWaterTemperature_C + "\r\n");
                    sbKML.AppendLine(@"Vertical Angle (deg): " + infrastructureModel.VerticalAngle_deg + "\r\n");
                    sbKML.AppendLine(@"</pre>");
                    sbKML.AppendLine(@"]]>");
                    sbKML.AppendLine(@"	</description>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureList[0].Lng + "," + mapInfoPointModelInfrastructureList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");

                    sbKML.AppendLine(@"	<Placemark>");
                    sbKML.AppendLine(@"	<name>Outfall " + tvItemModelInfrastructureList.Where(c => c.TVItemID == infrastructureModel.InfrastructureTVItemID).Select(c => c.TVText).FirstOrDefault() + "</name>");
                    sbKML.AppendLine(@"	<visibility>0</visibility>");
                    sbKML.AppendLine(@"<styleUrl>#msn_grn-pushpin</styleUrl>");

                    sbKML.AppendLine(@"		<Point>");
                    sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelInfrastructureOutfallList[0].Lng + "," + mapInfoPointModelInfrastructureOutfallList[0].Lat + ",0</coordinates>");
                    sbKML.AppendLine(@"		</Point>");
                    sbKML.AppendLine(@"	</Placemark>");
                }
                sbKML.AppendLine(@" </Folder>");
            }
            sbKML.AppendLine(@" </Folder>");

            // Doing Short Pollution Source Site
            sbKML.AppendLine(@" <Folder>");
            sbKML.AppendLine(@"	<name>Short Pollution Source Sites</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");
            List <PolSourceSiteModel> polSourceSiteModelList = polSourceSiteService.GetPolSourceSiteModelListWithSubsectorTVItemIDDB(tvItemModelSubsector.TVItemID);

            foreach (PolSourceSiteModel polSourceSiteModel in polSourceSiteModelList.OrderBy(c => c.Site).ToList())
            {
                // Doing point
                sbKML.AppendLine(@"	<Placemark>");
                sbKML.AppendLine(@"	<name>" + polSourceSiteModel.Site.ToString() + "</name>");
                sbKML.AppendLine(@"	<visibility>0</visibility>");
                sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                sbKML.AppendLine(@"	<description>");
                sbKML.AppendLine(@"<![CDATA[");
                sbKML.AppendLine(@"<pre>");

                PolSourceObservationModel polSourceObservationModel = polSourceSiteService._PolSourceObservationService.GetPolSourceObservationModelLatestWithPolSourceSiteTVItemIDDB(polSourceSiteModel.PolSourceSiteTVItemID);
                if (polSourceObservationModel != null)
                {
                    List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = polSourceSiteService._PolSourceObservationService._PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithPolSourceObservationIDDB(polSourceObservationModel.PolSourceObservationID);

                    string SelectedObservation = "Selected: \r\n";
                    foreach (PolSourceObservationIssueModel polSourceObservationIssueModel in polSourceObservationIssueModelList)
                    {
                        foreach (PolSourceObsInfoEnum polSourceObsInfo in polSourceObservationIssueModel.PolSourceObsInfoList)
                        {
                            SelectedObservation += baseEnumService.GetEnumText_PolSourceObsInfoReportEnum(polSourceObsInfo);
                        }
                        SelectedObservation += "\r\n\r\n";
                    }

                    sbKML.AppendLine("Written: \r\n" + (string.IsNullOrWhiteSpace(polSourceObservationModel.Observation_ToBeDeleted) ? "" : polSourceObservationModel.Observation_ToBeDeleted.ToString()) + "\r\n\r\n" + SelectedObservation);
                }
                else
                {
                    string SelectedObservation = "Selected: \r\n";
                    sbKML.AppendLine("Written: \r\n\r\n" + SelectedObservation);
                }

                sbKML.AppendLine(@"</pre>");
                sbKML.AppendLine(@"]]>");
                sbKML.AppendLine(@"	</description>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(polSourceSiteModel.PolSourceSiteTVItemID, TVTypeEnum.PolSourceSite, MapInfoDrawTypeEnum.Point);

                sbKML.AppendLine(@"		<Point>");
                sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
                sbKML.AppendLine(@"		</Point>");
                sbKML.AppendLine(@"	</Placemark>");
            }
            sbKML.AppendLine(@" </Folder>");

            // Doing Long Pollution Source Site
            sbKML.AppendLine(@" <Folder>");
            sbKML.AppendLine(@"	<name>Long Pollution Source Sites</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");
            polSourceSiteModelList = polSourceSiteService.GetPolSourceSiteModelListWithSubsectorTVItemIDDB(tvItemModelSubsector.TVItemID);

            foreach (PolSourceSiteModel polSourceSiteModel in polSourceSiteModelList.OrderBy(c => c.Site).ToList())
            {
                TVItemModel tvItemModelPolSourceSite = tvItemService.GetTVItemModelWithTVItemIDDB(polSourceSiteModel.PolSourceSiteTVItemID);

                // Doing point
                sbKML.AppendLine(@"	<Placemark>");
                sbKML.AppendLine(@"	<name>" + tvItemModelPolSourceSite.TVText + "</name>");
                sbKML.AppendLine(@"	<visibility>0</visibility>");
                sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                sbKML.AppendLine(@"	<description>");
                sbKML.AppendLine(@"<![CDATA[");
                sbKML.AppendLine(@"<pre>");

                PolSourceObservationModel polSourceObservationModel = polSourceSiteService._PolSourceObservationService.GetPolSourceObservationModelLatestWithPolSourceSiteTVItemIDDB(polSourceSiteModel.PolSourceSiteTVItemID);
                if (polSourceObservationModel != null)
                {
                    List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = polSourceSiteService._PolSourceObservationService._PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithPolSourceObservationIDDB(polSourceObservationModel.PolSourceObservationID);

                    string SelectedObservation = "Selected: \r\n";
                    foreach (PolSourceObservationIssueModel polSourceObservationIssueModel in polSourceObservationIssueModelList)
                    {
                        foreach (PolSourceObsInfoEnum polSourceObsInfo in polSourceObservationIssueModel.PolSourceObsInfoList)
                        {
                            SelectedObservation += baseEnumService.GetEnumText_PolSourceObsInfoReportEnum(polSourceObsInfo);
                        }
                        SelectedObservation += "\r\n\r\n";
                    }

                    sbKML.AppendLine("Written: \r\n" + (string.IsNullOrWhiteSpace(polSourceObservationModel.Observation_ToBeDeleted) ? "" : polSourceObservationModel.Observation_ToBeDeleted.ToString()) + "\r\n\r\n" + SelectedObservation);
                }
                else
                {
                    string SelectedObservation = "Selected: \r\n";
                    sbKML.AppendLine("Written: \r\n\r\n" + SelectedObservation);
                }

                sbKML.AppendLine(@"</pre>");
                sbKML.AppendLine(@"]]>");
                sbKML.AppendLine(@"	</description>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelPolSourceSite.TVItemID, TVTypeEnum.PolSourceSite, MapInfoDrawTypeEnum.Point);

                sbKML.AppendLine(@"		<Point>");
                sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
                sbKML.AppendLine(@"		</Point>");
                sbKML.AppendLine(@"	</Placemark>");
            }
            sbKML.AppendLine(@" </Folder>");


            // Doing MWQM Site
            sbKML.AppendLine(@" <Folder>");
            sbKML.AppendLine(@"	<name>MWQM Sites</name>");
            sbKML.AppendLine(@"	<visibility>0</visibility>");
            List <TVItemModel> tvItemModelMWQMSiteList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.MWQMSite);

            foreach (TVItemModel tvItemModelMWQMSite in tvItemModelMWQMSiteList)
            {
                // Doing point
                sbKML.AppendLine(@"	<Placemark>");
                sbKML.AppendLine(@"	<name>" + tvItemModelMWQMSite.TVText + "</name>");
                sbKML.AppendLine(@"	<visibility>0</visibility>");
                sbKML.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");

                mapInfoPointModelList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelMWQMSite.TVItemID, TVTypeEnum.MWQMSite, MapInfoDrawTypeEnum.Point);

                sbKML.AppendLine(@"		<Point>");
                sbKML.AppendLine(@"			<coordinates>"+ mapInfoPointModelList[0].Lng + "," + mapInfoPointModelList[0].Lat + ",0</coordinates>");
                sbKML.AppendLine(@"		</Point>");
                sbKML.AppendLine(@"	</Placemark>");
            }
            sbKML.AppendLine(@" </Folder>");

            sbKML.AppendLine(@"	</Folder>");

            sbKML.AppendLine(@"</Document>");
            sbKML.AppendLine(@"</kml>");

            StreamWriter sw = fi.CreateText();

            sw.Write(sbKML.ToString());
            sw.Close();
        }
Exemplo n.º 12
0
        private void GenerateSubsectorFaecalColiformSummaryStatDocument(Document document)
        {
            Body      body      = new Body();
            Paragraph paragraph = new Paragraph();
            Run       run       = new Run();
            Table     table     = new Table();
            TableRow  tableRow  = new TableRow();
            TableCell tableCell = new TableCell();
            //string URL = "";

            TVItemService     tvItemService     = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemStatService tvItemStatService = new TVItemStatService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

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

            if (!string.IsNullOrWhiteSpace(tvItemModelSubsector.Error))
            {
                paragraph = DocxBase.AddParagraph(body);
                DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemModelSubsector.Error);
            }

            //tvItemStatService.SetTVItemStatForTVItemIDAndParentsTVItemID(tvItemModelSubsector.TVItemID);

            DocxBase.CurrentParagraphStyle     = ParagraphStyleEnum.Caption;
            DocxBase.CurrentJustificationValue = JustificationValues.Center;
            paragraph = DocxBase.AddParagraph(body);

            DocxBase.CurrentFontSize = 36;

            string TableTitle = DocxServiceSubsectorFCSummaryStatRes.Table + "1A-1." + DocxServiceSubsectorFCSummaryStatRes.SummaryStatOfFCDensitiesMPNPer100 +
                                " " + DocxServiceSubsectorFCSummaryStatRes.For + " " + tvItemModelSubsector.TVText;

            run = DocxBase.AddRunWithCurrentFontStyle(paragraph, TableTitle);

            DocxBase.CurrentTableStyle = TableStyleEnum.ListTable7Colorful_Accent5;
            table    = DocxBase.AddTableStyle(body);
            tableRow = DocxBase.AddTableRow(table);

            List <string> ColumnTitleList = new List <string>()
            {
                DocxServiceSubsectorFCSummaryStatRes.Station,
                DocxServiceSubsectorFCSummaryStatRes.Samples,
                DocxServiceSubsectorFCSummaryStatRes.Period,
                DocxServiceSubsectorFCSummaryStatRes.MinFC,
                DocxServiceSubsectorFCSummaryStatRes.MaxFC,
                DocxServiceSubsectorFCSummaryStatRes.GMean,
                DocxServiceSubsectorFCSummaryStatRes.Median,
                DocxServiceSubsectorFCSummaryStatRes.P90,
                DocxServiceSubsectorFCSummaryStatRes.PercBigger43,
            };

            // Doing Cell Title
            foreach (string cellTitle in ColumnTitleList)
            {
                tableCell = DocxBase.AddTableCell(tableRow);
                paragraph = DocxBase.AddTableCellParagraph(tableCell);
                run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, cellTitle);
            }

            List <TVItemModel> tvItemModelMWQMList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelSubsector.TVItemID, TVTypeEnum.MWQMSite);

            foreach (TVItemModel tvItemModelMWQM in tvItemModelMWQMList)
            {
                TVItemMoreInfoMWQMSiteModel tvItemMoreInfoMWQMSiteModel = new TVItemMoreInfoMWQMSiteModel();
                tvItemMoreInfoMWQMSiteModel = tvItemService.GetTVItemMoreInfoMWQMSiteTVItemIDDB(tvItemModelMWQM.TVItemID, 30);

                if (tvItemMoreInfoMWQMSiteModel.StatMaxYear > DateTime.Now.Year - 6)
                {
                    tableRow = DocxBase.AddTableRow(table);

                    // Doing Station
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    run       = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, tvItemModelMWQM.TVText);

                    // Doing Samples
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string SampCountTxt = (tvItemMoreInfoMWQMSiteModel.SampCount == null ? "" : tvItemMoreInfoMWQMSiteModel.SampCount.ToString());
                    run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, SampCountTxt);

                    // Doing Period
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string StatMinMaxYearTxt = tvItemMoreInfoMWQMSiteModel.StatMinYear.ToString() + "-" + tvItemMoreInfoMWQMSiteModel.StatMaxYear.ToString();
                    run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, StatMinMaxYearTxt);

                    // Doing MinFC
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string MinFCTxt = (tvItemMoreInfoMWQMSiteModel.MinFC == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.MinFC).ToString("F0"));
                    if (MinFCTxt == "1")
                    {
                        MinFCTxt = "< 2";
                    }
                    run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, MinFCTxt);

                    // Doing MaxFC
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string MaxFCTxt = (tvItemMoreInfoMWQMSiteModel.MaxFC == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.MaxFC).ToString("F0"));
                    if (MaxFCTxt == "1")
                    {
                        MaxFCTxt = "< 2";
                    }
                    run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, MaxFCTxt);

                    // Doing GMean
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string GMeanTxt = (tvItemMoreInfoMWQMSiteModel.GeoMean == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.GeoMean).ToString("F0"));
                    if (tvItemMoreInfoMWQMSiteModel.GeoMean > 14)
                    {
                        int?TempFS = (int)DocxBase.CurrentFontSize;
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.Yellow;
                        DocxBase.CurrentFontSize            = 22;
                        run = DocxBase.AddRunWithCurrentFontStyle(paragraph, GMeanTxt);
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.None;
                        DocxBase.CurrentFontSize            = TempFS;
                    }
                    else
                    {
                        run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, GMeanTxt);
                    }

                    // Doing Median
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string MedianTxt = (tvItemMoreInfoMWQMSiteModel.Median == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.Median).ToString("F0"));
                    if (tvItemMoreInfoMWQMSiteModel.Median > 14)
                    {
                        int?TempFS = (int)DocxBase.CurrentFontSize;
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.Yellow;
                        DocxBase.CurrentFontSize            = 22;
                        run = DocxBase.AddRunWithCurrentFontStyle(paragraph, MedianTxt);
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.None;
                        DocxBase.CurrentFontSize            = TempFS;
                    }
                    else
                    {
                        run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, MedianTxt);
                    }

                    // Doing P90
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string P90Txt = (tvItemMoreInfoMWQMSiteModel.P90 == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.P90).ToString("F0"));
                    if (tvItemMoreInfoMWQMSiteModel.P90 > 43)
                    {
                        int?TempFS = (int)DocxBase.CurrentFontSize;
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.Yellow;
                        DocxBase.CurrentFontSize            = 22;
                        run = DocxBase.AddRunWithCurrentFontStyle(paragraph, P90Txt);
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.None;
                        DocxBase.CurrentFontSize            = TempFS;
                    }
                    else
                    {
                        run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, P90Txt);
                    }

                    // Doing % > 43
                    tableCell = DocxBase.AddTableCell(tableRow);
                    paragraph = DocxBase.AddTableCellParagraph(tableCell);
                    string PercOver43Txt = (tvItemMoreInfoMWQMSiteModel.PercOver43 == null ? "" : ((float)tvItemMoreInfoMWQMSiteModel.PercOver43).ToString("F0"));
                    if (tvItemMoreInfoMWQMSiteModel.PercOver43 > 10)
                    {
                        int?TempFS = (int)DocxBase.CurrentFontSize;
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.Yellow;
                        DocxBase.CurrentFontSize            = 22;
                        run = DocxBase.AddRunWithCurrentFontStyle(paragraph, PercOver43Txt);
                        DocxBase.CurrentHighlightColorValue = HighlightColorValues.None;
                        DocxBase.CurrentFontSize            = TempFS;
                    }
                    else
                    {
                        run = DocxBase.AddRunWithCurrentParagraphStyle(paragraph, PercOver43Txt);
                    }
                }
            }

            DocxBase.CurrentParagraphStyle = ParagraphStyleEnum.Quote;
            paragraph = DocxBase.AddParagraph(body);
            string NoteTxt = DocxServiceSubsectorFCSummaryStatRes.Note + " : " + DocxServiceSubsectorFCSummaryStatRes.TheFollowingValuesHaveBeenShaded
                             + " : " + DocxServiceSubsectorFCSummaryStatRes.GeometricMeanBigger14 + ", " + DocxServiceSubsectorFCSummaryStatRes.MedianBigger14 + ", "
                             + DocxServiceSubsectorFCSummaryStatRes.PercBigger43More10Perc + ", " + DocxServiceSubsectorFCSummaryStatRes.Perc90Bigger43;

            DocxBase.AddRunWithCurrentParagraphStyle(paragraph, NoteTxt);

            DocxBase.AddSectionProp(body);

            document.Append(body);
        }
Exemplo n.º 13
0
        public void Generate(FileInfo fi)
        {
            TVItemService         tvItemService         = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            MapInfoService        mapInfoService        = new MapInfoService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            InfrastructureService infrastructureService = new InfrastructureService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            if (_TaskRunnerBaseService._BWObj.appTaskModel.Language == "fr")
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("fr-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
            }
            else
            {
                Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-CA");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");
            }

            TVFileService tvFileService  = new TVFileService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            string        ServerFilePath = tvFileService.GetServerFilePath(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            DirectoryInfo di = new DirectoryInfo(ServerFilePath);

            if (!di.Exists)
            {
                di.Create();
            }

            if (fi.Exists)
            {
                fi.Delete();
            }

            StringBuilder sbKMZ        = new StringBuilder();
            StringBuilder sbKMZWWTP    = new StringBuilder();
            StringBuilder sbKMZLS      = new StringBuilder();
            StringBuilder sbKMZOutfall = new StringBuilder();
            StringBuilder sbKMZOther   = new StringBuilder();

            sbKMZ.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
            sbKMZ.AppendLine(@"<kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom"">");
            sbKMZ.AppendLine(@"<Document>");
            sbKMZ.AppendLine(@"	<name>" + _TaskRunnerBaseService.generateDocParams.FileName + "</name>");

            sbKMZ.AppendLine(@"    <StyleMap id=""msn_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<Pair>");
            sbKMZ.AppendLine(@"			<key>normal</key>");
            sbKMZ.AppendLine(@"			<styleUrl>#sn_ylw-pushpin</styleUrl>");
            sbKMZ.AppendLine(@"		</Pair>");
            sbKMZ.AppendLine(@"		<Pair>");
            sbKMZ.AppendLine(@"			<key>highlight</key>");
            sbKMZ.AppendLine(@"			<styleUrl>#sh_ylw-pushpin</styleUrl>");
            sbKMZ.AppendLine(@"		</Pair>");
            sbKMZ.AppendLine(@"	</StyleMap>");
            sbKMZ.AppendLine(@"	<Style id=""sh_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<IconStyle>");
            sbKMZ.AppendLine(@"			<scale>1.2</scale>");
            sbKMZ.AppendLine(@"		</IconStyle>");
            sbKMZ.AppendLine(@"		<LineStyle>");
            sbKMZ.AppendLine(@"			<color>ff00ff00</color>");
            sbKMZ.AppendLine(@"			<width>1.5</width>");
            sbKMZ.AppendLine(@"		</LineStyle>");
            sbKMZ.AppendLine(@"		<PolyStyle>");
            sbKMZ.AppendLine(@"			<color>0000ff00</color>");
            sbKMZ.AppendLine(@"		</PolyStyle>");
            sbKMZ.AppendLine(@"	</Style>");
            sbKMZ.AppendLine(@"	<Style id=""sn_ylw-pushpin"">");
            sbKMZ.AppendLine(@"		<LineStyle>");
            sbKMZ.AppendLine(@"			<color>ff00ff00</color>");
            sbKMZ.AppendLine(@"			<width>1.5</width>");
            sbKMZ.AppendLine(@"		</LineStyle>");
            sbKMZ.AppendLine(@"		<PolyStyle>");
            sbKMZ.AppendLine(@"			<color>0000ff00</color>");
            sbKMZ.AppendLine(@"		</PolyStyle>");
            sbKMZ.AppendLine(@"	</Style>");

            TVItemModel tvItemModelMunicipality = tvItemService.GetTVItemModelWithTVItemIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);
            List <MapInfoPointModel> mapInfoPointModelMuniList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelMunicipality.TVItemID, TVTypeEnum.Municipality, MapInfoDrawTypeEnum.Point);

            sbKMZ.AppendLine(@"	<Folder>");
            sbKMZ.AppendLine(@"	<name>Municipality</name>");

            // Doing Point
            sbKMZ.AppendLine(@"	<Placemark>");
            sbKMZ.AppendLine(@"	<name>" + tvItemModelMunicipality.TVText + "</name>");
            sbKMZ.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
            //sbKMZ.AppendLine(@"	<description>");
            //sbKMZ.AppendLine(@"<![CDATA[");
            //sbKMZ.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelRoot) + @""">" + tvItemModelRoot.TVText + "</a>");
            //sbKMZ.AppendLine(@"]]>");
            //sbKMZ.AppendLine(@"	</description>");
            sbKMZ.AppendLine(@"	<Point>");
            sbKMZ.AppendLine(@"		<coordinates>"+ mapInfoPointModelMuniList[0].Lng + "," + mapInfoPointModelMuniList[0].Lat + ",0</coordinates>");
            sbKMZ.AppendLine(@"	</Point>");
            sbKMZ.AppendLine(@"	</Placemark>");

            // Doing Infrastructures
            sbKMZ.AppendLine(@" <Folder>");
            sbKMZ.AppendLine(@"	<name>Infrastructures</name>");

            sbKMZWWTP.AppendLine(@" <Folder>");
            sbKMZWWTP.AppendLine(@"	<name>Waste Water Treatment Plants</name>");
            sbKMZLS.AppendLine(@" <Folder>");
            sbKMZLS.AppendLine(@"	<name>Lift Stations</name>");
            sbKMZOutfall.AppendLine(@" <Folder>");
            sbKMZOutfall.AppendLine(@"	<name>Outfalls</name>");
            sbKMZOther.AppendLine(@" <Folder>");
            sbKMZOther.AppendLine(@"	<name>Others</name>");

            List <TVItemModel> tvItemModelInfrastructuresList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelMunicipality.TVItemID, TVTypeEnum.Infrastructure);

            foreach (TVItemModel tvItemModelInfrastructure in tvItemModelInfrastructuresList)
            {
                InfrastructureModel infrastructureModel = infrastructureService.GetInfrastructureModelWithInfrastructureTVItemIDDB(tvItemModelInfrastructure.TVItemID);

                List <MapInfoPointModel> mapInfoPointModelInfList    = new List <MapInfoPointModel>();
                List <MapInfoPointModel> mapInfoPointModelInfOutList = new List <MapInfoPointModel>();

                if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.WWTP)
                {
                    mapInfoPointModelInfList    = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.WasteWaterTreatmentPlant, MapInfoDrawTypeEnum.Point);
                    mapInfoPointModelInfOutList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);
                }
                else if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.LiftStation)
                {
                    mapInfoPointModelInfList    = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.LiftStation, MapInfoDrawTypeEnum.Point);
                    mapInfoPointModelInfOutList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);
                }
                else if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.Other)
                {
                    mapInfoPointModelInfList    = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.OtherInfrastructure, MapInfoDrawTypeEnum.Point);
                    mapInfoPointModelInfOutList = mapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(tvItemModelInfrastructure.TVItemID, TVTypeEnum.Outfall, MapInfoDrawTypeEnum.Point);
                }


                Coord coord = new Coord();
                if (mapInfoPointModelInfList.Count == 0)
                {
                    coord.Lat     = (float)mapInfoPointModelMuniList[0].Lat + 0.01f;
                    coord.Lng     = (float)mapInfoPointModelMuniList[0].Lng + 0.01f;
                    coord.Ordinal = 0;
                }
                else
                {
                    coord.Lat     = (float)mapInfoPointModelInfList[0].Lat;
                    coord.Lng     = (float)mapInfoPointModelInfList[0].Lng;
                    coord.Ordinal = 0;
                }

                Coord coord2 = new Coord();
                if (mapInfoPointModelInfOutList.Count == 0)
                {
                    coord2.Lat     = (float)mapInfoPointModelMuniList[0].Lat + 0.01f;
                    coord2.Lng     = (float)mapInfoPointModelMuniList[0].Lng + 0.01f;
                    coord2.Ordinal = 0;
                }
                else
                {
                    coord2.Lat     = (float)mapInfoPointModelInfOutList[0].Lat;
                    coord2.Lng     = (float)mapInfoPointModelInfOutList[0].Lng;
                    coord2.Ordinal = 0;
                }

                if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.WWTP)
                {
                    // Doing point Infr. WWTP
                    sbKMZWWTP.AppendLine(@"	<Placemark>");
                    sbKMZWWTP.AppendLine(@"	<name>" + tvItemModelInfrastructure.TVText + "</name>");
                    sbKMZWWTP.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                    //sbKMZWWTP.AppendLine(@"	<description>");
                    //sbKMZWWTP.AppendLine(@"<![CDATA[");
                    //sbKMZWWTP.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                    //sbKMZWWTP.AppendLine(@"]]>");
                    //sbKMZWWTP.AppendLine(@"	</description>");

                    sbKMZWWTP.AppendLine(@"		<Point>");
                    sbKMZWWTP.AppendLine(@"			<coordinates>"+ coord.Lng + "," + coord.Lat + ",0</coordinates>");
                    sbKMZWWTP.AppendLine(@"		</Point>");
                    sbKMZWWTP.AppendLine(@"	</Placemark>");
                }
                else if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.LiftStation)
                {
                    // Doing point Infr. LS
                    sbKMZLS.AppendLine(@"	<Placemark>");
                    sbKMZLS.AppendLine(@"	<name>"+ tvItemModelInfrastructure.TVText + "</name>");
                    sbKMZLS.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                    //sbKMZLS.AppendLine(@"	<description>");
                    //sbKMZLS.AppendLine(@"<![CDATA[");
                    //sbKMZLS.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                    //sbKMZLS.AppendLine(@"]]>");
                    //sbKMZLS.AppendLine(@"	</description>");

                    sbKMZLS.AppendLine(@"		<Point>");
                    sbKMZLS.AppendLine(@"			<coordinates>"+ coord.Lng + "," + coord.Lat + ",0</coordinates>");
                    sbKMZLS.AppendLine(@"		</Point>");
                    sbKMZLS.AppendLine(@"	</Placemark>");
                }
                else if (infrastructureModel.InfrastructureType == InfrastructureTypeEnum.Other)
                {
                    // Doing point Infr. WWTP
                    sbKMZOther.AppendLine(@"	<Placemark>");
                    sbKMZOther.AppendLine(@"	<name>"+ tvItemModelInfrastructure.TVText + "</name>");
                    sbKMZOther.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                    //sbKMZOther.AppendLine(@"	<description>");
                    //sbKMZOther.AppendLine(@"<![CDATA[");
                    //sbKMZOther.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                    //sbKMZOther.AppendLine(@"]]>");
                    //sbKMZOther.AppendLine(@"	</description>");

                    sbKMZOther.AppendLine(@"		<Point>");
                    sbKMZOther.AppendLine(@"			<coordinates>"+ coord.Lng + "," + coord.Lat + ",0</coordinates>");
                    sbKMZOther.AppendLine(@"		</Point>");
                    sbKMZOther.AppendLine(@"	</Placemark>");
                }
                else
                {
                }

                // Doing point Infr. outfall
                sbKMZOutfall.AppendLine(@"	<Placemark>");
                sbKMZOutfall.AppendLine(@"	<name>"+ tvItemModelInfrastructure.TVText + "</name>");
                sbKMZOutfall.AppendLine(@"<styleUrl>#msn_ylw-pushpin</styleUrl>");
                //sbKMZOutfall.AppendLine(@"	<description>");
                //sbKMZOutfall.AppendLine(@"<![CDATA[");
                //sbKMZOutfall.AppendLine(@"<a href=""" + _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelCountry) + @""">" + tvItemModelCountry.TVText + "</a>");
                //sbKMZOutfall.AppendLine(@"]]>");
                //sbKMZOutfall.AppendLine(@"	</description>");

                sbKMZOutfall.AppendLine(@"		<Point>");
                sbKMZOutfall.AppendLine(@"			<coordinates>"+ coord2.Lng + "," + coord2.Lat + ",0</coordinates>");
                sbKMZOutfall.AppendLine(@"		</Point>");
                sbKMZOutfall.AppendLine(@"	</Placemark>");
            }
            sbKMZWWTP.AppendLine(@" </Folder>");
            sbKMZLS.AppendLine(@" </Folder>");
            sbKMZOutfall.AppendLine(@" </Folder>");
            sbKMZOther.AppendLine(@" </Folder>");

            sbKMZ.Append(sbKMZWWTP.ToString());
            sbKMZ.Append(sbKMZLS.ToString());
            sbKMZ.Append(sbKMZOutfall.ToString());
            sbKMZ.Append(sbKMZOther.ToString());

            sbKMZ.AppendLine(@" </Folder>");

            sbKMZ.AppendLine(@"	</Folder>");

            sbKMZ.AppendLine(@"</Document>");
            sbKMZ.AppendLine(@"</kml>");

            StreamWriter sw = fi.CreateText();

            sw.Write(sbKMZ.ToString());

            sw.Close();
        }
Exemplo n.º 14
0
        public bool CreateQCPolSourceAll()
        {
            if (Cancel)
            {
                return(false);
            }

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

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

            TVItemModel tvItemModelRoot = tvItemServiceR.GetRootTVItemModelDB();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                textBoxQCCreateSanitaryQC.Text = Count.ToString();

                if (StartQCCreateSanitarysQC > Count)
                {
                    continue;
                }

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

                    TVItemModel tvItemModelSubsector = new TVItemModel();

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

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

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

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

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

                        PolSourceSiteModel polSourceSiteModelNew = new PolSourceSiteModel();

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

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

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

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

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

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

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

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

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

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

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

                                    break;
                                }
                            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        polSourceObservationModelNew.ContactTVItemID = tvItemModelContact.TVItemID;

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

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

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

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

                        // do historic PolSourceObservation

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

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

                            PolSourceObservationModel polSourceObservationModelNew2 = new PolSourceObservationModel();

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

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

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

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

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

                            polSourceObservationModelNew2.ContactTVItemID = tvItemModelContact.TVItemID;

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

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

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

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

            return(true);
        }
        private void GenerateWorksheetAContentSubsectorPollutionSourceFieldSheet(WorksheetPart worksheetPart, Workbook workbook, string SheetName, int SheetOrdinal, bool ActivePollutionSource)
        {
            BaseEnumService      baseEnumService      = new BaseEnumService(_TaskRunnerBaseService._BWObj.appTaskModel.Language);
            TVItemService        tvItemService        = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            PolSourceSiteService polSourceSiteService = new PolSourceSiteService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            //PolSourceObservationService polSourceObservationService = new PolSourceObservationService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            //MWQMSubsectorService mwqmSubsectorService = new MWQMSubsectorService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

            MergeCells mergeCells = new MergeCells();
            Row        row        = new Row();
            Cell       cell       = new Cell();
            Hyperlinks hyperlinks = new Hyperlinks();
            string     Id         = XlsxBase.sheetNameAndIDList[SheetOrdinal].SheetID;

            XlsxBase.CurrentColumn     = 0;
            XlsxBase.CurrentRow        = 0;
            XlsxBase.CurrentColumnProp = 0;
            Worksheet worksheet = new Worksheet()
            {
                MCAttributes = new MarkupCompatibilityAttributes()
                {
                    Ignorable = "x14ac"
                }
            };

            worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            worksheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            worksheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");

            SheetViews sheetViews = new SheetViews();

            SheetView sheetView = new SheetView()
            {
                TabSelected = true, WorkbookViewId = (UInt32Value)0U
            };
            Selection selection = new Selection()
            {
                ActiveCell = "A1", SequenceOfReferences = new ListValue <StringValue>()
                {
                    InnerText = "A1"
                }
            };

            sheetView.Append(selection);

            sheetViews.Append(sheetView);
            SheetFormatProperties sheetFormatProperties = new SheetFormatProperties()
            {
                DefaultRowHeight = 15D, DyDescent = 0.25D
            };

            Columns        columns         = new Columns();
            List <double?> columnWidthList = new List <double?>()
            {
                7D, 10D, 90D, 12D, 12D, 10D, 14D, 20D
            };

            foreach (double?width in columnWidthList)
            {
                Column colum = XlsxBase.AddColumnProp(columns, width);
            }

            SheetData sheetData = new SheetData();

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

            //MWQMSubsectorModel mwqmSubsectorModel = mwqmSubsectorService.GetMWQMSubsectorModelWithMWQMSubsectorTVItemIDDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID);

            XlsxBase.CurrentRowHeight = 28D;
            XlsxBase.CurrentFontSize  = 24;
            XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;
            XlsxBase.CurrentBorderStyleValue         = BorderStyleValues.Thin;
            XlsxBase.CurrentBottomBorder             = true;

            row = XlsxBase.AddRow();
            string URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelSubsector);

            XlsxBase.CurrentFontColor = System.Drawing.Color.Blue;
            cell = XlsxBase.AddCellHyperlink(hyperlinks, row, tvItemModelSubsector.TVText, URL);
            XlsxBase.CurrentFontColor = null;
            //cell = XlsxBase.AddCellString(row, tvItemModel.TVText);
            cell = XlsxBase.AddCellString(row, null);
            sheetData.Append(row);

            MergeCell mergeCell = new MergeCell()
            {
                Reference = "A" + XlsxBase.CurrentRow.ToString() + ":H" + XlsxBase.CurrentRow.ToString()
            };

            mergeCells.Append(mergeCell);

            List <TVItemModel> tvItemModelPolSourceList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(_TaskRunnerBaseService._BWObj.appTaskModel.TVItemID, TVTypeEnum.PolSourceSite);

            XlsxBase.CurrentRowHeight                = 24D;
            XlsxBase.CurrentFontSize                 = 18;
            XlsxBase.CurrentBorderStyleValue         = BorderStyleValues.Thin;
            XlsxBase.CurrentBottomBorder             = true;
            XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;

            row = XlsxBase.AddRow();
            XlsxBase.CurrentFontColor = null;
            cell = XlsxBase.AddCellString(row, "Site");
            cell = XlsxBase.AddCellString(row, "Type");
            cell = XlsxBase.AddCellString(row, "Observation");
            cell = XlsxBase.AddCellString(row, "Lat");
            cell = XlsxBase.AddCellString(row, "Lng");
            cell = XlsxBase.AddCellString(row, "Active");
            cell = XlsxBase.AddCellString(row, "Update");
            cell = XlsxBase.AddCellString(row, "Civic Address");
            sheetData.Append(row);

            XlsxBase.CurrentRowHeight = 160D;
            XlsxBase.CurrentFontSize  = 12;
            XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Left;

            List <PolSourceSiteModel> polSourceSiteModelList = polSourceSiteService.GetPolSourceSiteModelListWithSubsectorTVItemIDDB(tvItemModelSubsector.TVItemID);

            int countPolSourceSite = 0;

            foreach (PolSourceSiteModel polSourceSiteModel in polSourceSiteModelList.OrderBy(c => c.Site).ToList())
            {
                bool IsActive = (from c in tvItemModelPolSourceList
                                 where c.TVItemID == polSourceSiteModel.PolSourceSiteTVItemID
                                 select c.IsActive).FirstOrDefault();

                if (ActivePollutionSource != IsActive)
                {
                    continue;
                }

                countPolSourceSite += 1;
                PolSourceObservationModel polSourceObservationModel = polSourceSiteService._PolSourceObservationService.GetPolSourceObservationModelLatestWithPolSourceSiteTVItemIDDB(polSourceSiteModel.PolSourceSiteTVItemID);

                List <MapInfoPointModel> mapInfoPointModelList = polSourceSiteService._MapInfoService._MapInfoPointService.GetMapInfoPointModelListWithTVItemIDAndTVTypeAndMapInfoDrawTypeDB(polSourceSiteModel.PolSourceSiteTVItemID, TVTypeEnum.PolSourceSite, MapInfoDrawTypeEnum.Point);

                row = XlsxBase.AddRow();

                if (countPolSourceSite % 5 == 0)
                {
                    XlsxBase.CurrentBorderStyleValue = BorderStyleValues.Thin;
                    XlsxBase.CurrentBottomBorder     = true;
                }
                else
                {
                    XlsxBase.CurrentBorderStyleValue = null;
                    XlsxBase.CurrentBottomBorder     = false;
                }

                XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;
                cell = XlsxBase.AddCellString(row, polSourceSiteModel.Site.ToString());

                if (polSourceObservationModel != null)
                {
                    List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = polSourceSiteService._PolSourceObservationService._PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithPolSourceObservationIDDB(polSourceObservationModel.PolSourceObservationID);

                    string SelectedObservation = "Selected: \r\n";
                    int    PolSourceObsInfoInt = 0;
                    foreach (PolSourceObservationIssueModel polSourceObservationIssueModel in polSourceObservationIssueModelList)
                    {
                        List <int> observationInfoList = polSourceObservationIssueModel.ObservationInfo.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList().Select(c => int.Parse(c)).ToList();
                        PolSourceObsInfoInt = observationInfoList.Where(c => (c > 10500 && c < 10599) || (c > 15200 && c < 15299)).FirstOrDefault();

                        foreach (PolSourceObsInfoEnum polSourceObsInfo in polSourceObservationIssueModel.PolSourceObsInfoList)
                        {
                            SelectedObservation += baseEnumService.GetEnumText_PolSourceObsInfoReportEnum(polSourceObsInfo);
                        }
                        SelectedObservation += "\r\n\r\n";
                    }
                    if (PolSourceObsInfoInt > 0)
                    {
                        cell = XlsxBase.AddCellString(row, baseEnumService.GetEnumText_PolSourceObsInfoEnum((PolSourceObsInfoEnum)PolSourceObsInfoInt));
                    }
                    else
                    {
                        cell = XlsxBase.AddCellString(row, "Empty");
                    }
                }

                XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Left;
                XlsxBase.WrapText = true;

                if (polSourceObservationModel != null)
                {
                    List <PolSourceObservationIssueModel> polSourceObservationIssueModelList = polSourceSiteService._PolSourceObservationService._PolSourceObservationIssueService.GetPolSourceObservationIssueModelListWithPolSourceObservationIDDB(polSourceObservationModel.PolSourceObservationID);

                    string SelectedObservation = "Selected: \r\n";
                    int    PolSourceObsInfoInt = 0;
                    foreach (PolSourceObservationIssueModel polSourceObservationIssueModel in polSourceObservationIssueModelList)
                    {
                        List <int> observationInfoList = polSourceObservationIssueModel.ObservationInfo.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList().Select(c => int.Parse(c)).ToList();
                        foreach (PolSourceObsInfoEnum polSourceObsInfo in polSourceObservationIssueModel.PolSourceObsInfoList)
                        {
                            SelectedObservation += baseEnumService.GetEnumText_PolSourceObsInfoReportEnum(polSourceObsInfo);
                        }
                        SelectedObservation += "\r\n\r\n";
                    }
                    if (PolSourceObsInfoInt > 0)
                    {
                        cell = XlsxBase.AddCellString(row, "Written: \r\n" + (string.IsNullOrWhiteSpace(polSourceObservationModel.Observation_ToBeDeleted) ? "" : polSourceObservationModel.Observation_ToBeDeleted.ToString()) + "\r\n\r\n"
                                                      + SelectedObservation);
                    }
                    else
                    {
                        cell = XlsxBase.AddCellString(row, "Written: \r\n\r\n" + SelectedObservation);
                    }
                }

                XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;
                Alignment alignment1 = new Alignment()
                {
                    WrapText = true
                };

                if (mapInfoPointModelList.Count > 0)
                {
                    cell = XlsxBase.AddCellString(row, mapInfoPointModelList[0].Lat.ToString("F5"));
                    cell = XlsxBase.AddCellString(row, mapInfoPointModelList[0].Lng.ToString("F5"));
                }
                else
                {
                    cell = XlsxBase.AddCellString(row, "");
                    cell = XlsxBase.AddCellString(row, "");
                }

                TVItemModel tvItemModelPolSource = tvItemService.GetTVItemModelWithTVItemIDDB(polSourceSiteModel.PolSourceSiteTVItemID);

                cell = XlsxBase.AddCellString(row, tvItemModelPolSource.IsActive.ToString());
                cell = XlsxBase.AddCellString(row, polSourceObservationModel.ObservationDate_Local.ToString("yyyy MMM dd"));
                cell = XlsxBase.AddCellString(row, "empty");

                sheetData.Append(row);
            }

            if (countPolSourceSite > 0)
            {
                DefinedNames definedNames1 = new DefinedNames();
                DefinedName  definedName1  = new DefinedName()
                {
                    Name = "_xlnm._FilterDatabase", LocalSheetId = (UInt32Value)0U, Hidden = true
                };
                definedName1.Text = "'" + SheetName + "'" + "!$A$2:$H$" + (countPolSourceSite + 2).ToString();

                definedNames1.Append(definedName1);
                workbook.Append(definedNames1);

                AutoFilter autoFilter = new AutoFilter()
                {
                    Reference = "a2:B" + (countPolSourceSite + 2).ToString()
                };
                worksheet.Append(autoFilter);
            }

            PageMargins pageMargins = new PageMargins()
            {
                Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D
            };
            PageSetup pageSetup = new PageSetup()
            {
                Orientation = OrientationValues.Portrait, Id = "rId" + SheetOrdinal.ToString()
            };

            worksheet.Append(sheetViews);
            worksheet.Append(sheetFormatProperties);

            if (columns.ChildElements.Count > 0)
            {
                worksheet.Append(columns);
            }

            worksheet.Append(sheetData);

            mergeCells.Count = (UInt32Value)((UInt32)mergeCells.ChildElements.Count);
            if (mergeCells.ChildElements.Count > 0)
            {
                worksheet.Append(mergeCells);
            }


            if (XlsxBase.UsedHyperlinkList.Count > 0)
            {
                worksheet.Append(hyperlinks);
            }

            worksheet.Append(pageMargins);
            worksheet.Append(pageSetup);

            worksheetPart.Worksheet = worksheet;
        }
Exemplo n.º 16
0
        public bool CreateQCPolSourceNullAll()
        {
            lblStatus.Text = "Starting ... CreateSanitaryQC - CreateQCPolSourceNullAll";
            Application.DoEvents();

            if (Cancel)
            {
                return(false);
            }

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

            TVItemModel tvItemModelRoot = tvItemServiceR.GetRootTVItemModelDB();

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

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

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

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

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

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

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

            List <MapInfo> mapInfoList = (from c in TVItemModelSubsectorList
                                          from m in tvItemServiceR.db.MapInfos
                                          where c.TVItemID == m.TVItemID &&
                                          m.MapInfoDrawType == (int)MapInfoDrawTypeEnum.Polygon
                                          select m).ToList();

            List <TVItemSubsectorAndCoordCentroid> TVItemSubsectorAndCoordCentroidList = (from c in mapInfoList
                                                                                          let lat = (c.LatMax - c.LatMin) / 2 + c.LatMin
                                                                                                    let lng = (c.LngMax - c.LngMin) / 2 + c.LngMin
                                                                                                              select new TVItemSubsectorAndCoordCentroid
            {
                TVItemID = c.TVItemID,
                Lat = (float)lat,
                Lng = (float)lng,
            }).ToList();

            List <string> sectorList = new List <string>();

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

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

            Application.DoEvents();

            List <PCCSM.geo_pollution_p> polQCList = new List <PCCSM.geo_pollution_p>();

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

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

            foreach (PCCSM.geo_pollution_p pqc in polQCList)
            {
                Count         += 1;
                lblStatus.Text = (Count * 100 / TotalCount).ToString() + "... CreateSanitaryQC for sector " + pqc.secteur;
                Application.DoEvents();

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

                PolSourceSiteModel polSourceSiteModelNew = new PolSourceSiteModel();

                string Code = tvItemService.CleanText(pqc.code.ToUpper());

                List <PolSourceObsInfoEnum> polSourceObsInfoList = GetPolSourceType(Code.Trim(), "", "QC");
                string ObservationInfo = (int)polSourceObsInfoList[0] + "," + (int)polSourceObsInfoList[1] + ",";
                polSourceSiteModelNew.IsPointSource = true;
                //if (pqc.status == "actif")
                //{
                //    polSourceSiteModelNew.IsActive = true;
                //}
                //else
                //{
                //    polSourceSiteModelNew.IsActive = false;
                //}
                polSourceSiteModelNew.InactiveReason = PolSourceInactiveReasonEnum.Error;
                polSourceSiteModelNew.Oldsiteid      = pqc.id_geo_pollution_p;

                // Pollution Source Type
                string PolSourceSiteTVText = tvItemService.CleanText(Code + "      ".Substring(0, 6 - pqc.id_geo_pollution_p.ToString().Length) + pqc.id_geo_pollution_p.ToString());

                List <MapInfoModel> mapInfoModelListSubsector = mapInfoService.GetMapInfoModelWithLatAndLngInPolygonWithTVTypeDB((float)pqc.y, (float)pqc.x, TVTypeEnum.Subsector);
                int TempTVItemID = 0;
                if (mapInfoModelListSubsector.Count == 0)
                {
                    float SmallestDistance = 100000000f;
                    foreach (TVItemSubsectorAndCoordCentroid tvItemSubsectorAndCoordCentroid in TVItemSubsectorAndCoordCentroidList)
                    {
                        float TempDistance = (float)mapInfoService.CalculateDistance((double)pqc.y, (double)pqc.x, (double)tvItemSubsectorAndCoordCentroid.Lat, (double)tvItemSubsectorAndCoordCentroid.Lng, mapInfoService.R);
                        if (SmallestDistance > TempDistance)
                        {
                            TempTVItemID     = tvItemSubsectorAndCoordCentroid.TVItemID;
                            SmallestDistance = TempDistance;
                        }
                    }
                }
                else
                {
                    TempTVItemID = mapInfoModelListSubsector[0].TVItemID;
                }

                if (TempTVItemID == 0)
                {
                    richTextBoxStatus.AppendText("TempTVItemID equal 0");
                    return(false);
                }

                TVItemModel tvItemModelPolSourceSite = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(TempTVItemID, PolSourceSiteTVText, TVTypeEnum.PolSourceSite);
                if (!CheckModelOK <TVItemModel>(tvItemModelPolSourceSite))
                {
                    tvItemModelPolSourceSite = tvItemService.PostCreateTVItem(TempTVItemID, PolSourceSiteTVText, PolSourceSiteTVText, TVTypeEnum.PolSourceSite);
                    if (!CheckModelOK <TVItemModel>(tvItemModelPolSourceSite))
                    {
                        return(false);
                    }
                }
                ;

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

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

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

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

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

                PolSourceObservationModel polSourceObservationModelNew = new PolSourceObservationModel();
                if (pqc.date_observation == null)
                {
                    polSourceObservationModelNew.ObservationDate_Local = new DateTime(1970, 1, 1);
                }
                else
                {
                    polSourceObservationModelNew.ObservationDate_Local = (DateTime)(pqc.date_observation.Value).AddHours(1);
                }
                string Observateur = "";
                if (pqc.observateur != null)
                {
                    if (pqc.observateur.Length > 98)
                    {
                        Observateur = pqc.observateur.Substring(0, 60);
                    }
                    else
                    {
                        Observateur = pqc.observateur;
                    }
                }

                string TVText = "Inspector " + Observateur;
                TVText = (TVText.Length > 50 ? TVText.Substring(0, 50) : TVText);
                TVItemModel tvItemModelContact = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelRoot.TVItemID, TVText, TVTypeEnum.Contact);
                if (!string.IsNullOrWhiteSpace(tvItemModelContact.Error))
                {
                    tvItemModelContact = tvItemService.PostCreateTVItem(tvItemModelRoot.TVItemID, TVText, TVText, TVTypeEnum.Contact);
                    if (!CheckModelOK <TVItemModel>(tvItemModelContact))
                    {
                        return(false);
                    }
                }

                polSourceObservationModelNew.ContactTVItemID         = tvItemModelContact.TVItemID;
                polSourceObservationModelNew.Observation_ToBeDeleted = TVTextObservation;
                polSourceObservationModelNew.PolSourceSiteID         = polSourceSiteModelRet.PolSourceSiteID;

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

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

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

                // do historic PolSourceObservation

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

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

                    PolSourceObservationModel polSourceObservationModelNew2 = new PolSourceObservationModel();
                    if (hist.date_operation == null)
                    {
                        polSourceObservationModelNew2.ObservationDate_Local = new DateTime(1970, 1, 1);
                    }
                    else
                    {
                        polSourceObservationModelNew2.ObservationDate_Local = (DateTime)hist.date_operation;
                    }
                    if (hist.auteur != null)
                    {
                        if (hist.auteur.Length > 98)
                        {
                            Observateur = hist.auteur.Substring(0, 60);
                        }
                        else
                        {
                            Observateur = hist.auteur;
                        }
                    }

                    TVText = "Inspector " + Observateur;
                    TVText = (TVText.Length > 50 ? TVText.Substring(0, 50) : TVText);
                    TVItemModel tvItemModelContact2 = tvItemService.GetChildTVItemModelWithTVItemIDAndTVTextStartWithAndTVTypeDB(tvItemModelRoot.TVItemID, TVText, TVTypeEnum.Contact);
                    if (!string.IsNullOrWhiteSpace(tvItemModelContact.Error))
                    {
                        tvItemModelContact = tvItemService.PostCreateTVItem(tvItemModelRoot.TVItemID, TVText, TVText, TVTypeEnum.Contact);
                        if (!CheckModelOK <TVItemModel>(tvItemModelContact))
                        {
                            return(false);
                        }
                    }

                    polSourceObservationModelNew2.ContactTVItemID = tvItemModelContact2.TVItemID;

                    polSourceObservationModelNew2.Observation_ToBeDeleted = TVTextObservation;
                    polSourceObservationModelNew2.PolSourceSiteID         = polSourceSiteModelRet.PolSourceSiteID;

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

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

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

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

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

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

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

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

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

            string Parameters = _TaskRunnerBaseService._BWObj.appTaskModel.Parameters;

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

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

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

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

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

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

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

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

            FileInfo fi = new FileInfo(ServerPath + FileName);

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

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

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

            #endregion Reading the MWQMSitesAndPolSourceSites_XX.KML

            #region Reading the GroupingInputs__XX.KML

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

            FileInfo fi2 = new FileInfo(ServerPath + FileName2);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                                                    polyObj.coordList.Add(coord);

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

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

            // getting all active MWQMSites and PolSourceSites under the province

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


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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

            #endregion Saving PolSourceSiteEffect in CSSPDB

            appTaskModel.PercentCompleted = 100;
            appTaskService.PostUpdateAppTask(appTaskModel);
        }
        private void GenerateWorksheetAContent(WorksheetPart worksheetPart, int SheetOrdinal)
        {
            MergeCells mergeCells = new MergeCells();
            Row        row        = new Row();
            Cell       cell       = new Cell();
            Hyperlinks hyperlinks = new Hyperlinks();
            string     Id         = XlsxBase.sheetNameAndIDList[SheetOrdinal].SheetID;

            XlsxBase.CurrentColumn     = 0;
            XlsxBase.CurrentRow        = 0;
            XlsxBase.CurrentColumnProp = 0;
            Worksheet worksheet = new Worksheet()
            {
                MCAttributes = new MarkupCompatibilityAttributes()
                {
                    Ignorable = "x14ac"
                }
            };

            worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            worksheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            worksheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");

            SheetViews sheetViews = new SheetViews();

            SheetView sheetView = new SheetView()
            {
                TabSelected = true, WorkbookViewId = (UInt32Value)0U
            };
            Selection selection = new Selection()
            {
                ActiveCell = "A1", SequenceOfReferences = new ListValue <StringValue>()
                {
                    InnerText = "A1"
                }
            };

            sheetView.Append(selection);

            sheetViews.Append(sheetView);
            SheetFormatProperties sheetFormatProperties = new SheetFormatProperties()
            {
                DefaultRowHeight = 15D, DyDescent = 0.25D
            };

            Columns        columns         = new Columns();
            List <double?> columnWidthList = new List <double?>()
            {
                30D
            };

            foreach (double?width in columnWidthList)
            {
                Column colum = XlsxBase.AddColumnProp(columns, width);
            }

            SheetData sheetData = new SheetData();

            BaseEnumService   baseEnumService   = new BaseEnumService(_TaskRunnerBaseService._BWObj.appTaskModel.Language);
            TVItemService     tvItemService     = new TVItemService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);
            TVItemStatService tvItemStatService = new TVItemStatService(_TaskRunnerBaseService._BWObj.appTaskModel.Language, _TaskRunnerBaseService._User);

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

            List <TVItemModel> tvItemModelAreaList = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProvince.TVItemID, TVTypeEnum.Area);


            foreach (TVItemModel tvItemModelArea in tvItemModelAreaList)
            {
                //tvItemStatService.SetTVItemStatForTVItemIDAndParentsTVItemID(tvItemModelArea.TVItemID);

                XlsxBase.CurrentRowHeight                = 24D;
                XlsxBase.CurrentFontSize                 = 18;
                XlsxBase.CurrentBorderStyleValue         = BorderStyleValues.Thick;
                XlsxBase.CurrentBottomBorder             = true;
                XlsxBase.CurrentBorderColor              = System.Drawing.Color.Green;
                XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;

                row = XlsxBase.AddRow();
                string URL = _TaskRunnerBaseService.GetUrlFromTVItem(tvItemModelArea);
                XlsxBase.CurrentFontColor = System.Drawing.Color.Blue;
                cell = XlsxBase.AddCellHyperlink(hyperlinks, row, tvItemModelArea.TVText, URL);
                XlsxBase.CurrentFontColor = null;
                //cell = XlsxBase.AddCellString(row, tvItemModel.TVText);
                cell = XlsxBase.AddCellString(row, null);
                sheetData.Append(row);

                MergeCell mergeCell = new MergeCell()
                {
                    Reference = "A" + XlsxBase.CurrentRow.ToString() + ":B" + XlsxBase.CurrentRow.ToString()
                };

                mergeCells.Append(mergeCell);

                XlsxBase.CurrentRowHeight = 16D;
                XlsxBase.CurrentFontSize  = 12;
                XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;

                List <TVItemStatModel> tvItemStatModelList = tvItemStatService.GetTVItemStatModelListWithTVItemIDDB(tvItemModelArea.TVItemID);

                int count = 0;
                foreach (TVItemStatModel tvItemStatModel in tvItemStatModelList)
                {
                    count += 1;
                    row    = XlsxBase.AddRow();

                    if (count % 5 == 0)
                    {
                        XlsxBase.CurrentBorderStyleValue = BorderStyleValues.Thin;
                        XlsxBase.CurrentBottomBorder     = true;
                    }
                    else
                    {
                        XlsxBase.CurrentBorderStyleValue = null;
                        XlsxBase.CurrentBottomBorder     = false;
                    }
                    XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Right;
                    cell = XlsxBase.AddCellString(row, baseEnumService.GetEnumText_TVTypeEnum(tvItemStatModel.TVType));

                    XlsxBase.CurrentHorizontalAlignmentValue = HorizontalAlignmentValues.Center;
                    cell = XlsxBase.AddCellNumber(row, tvItemStatModel.ChildCount.ToString());

                    sheetData.Append(row);
                }

                XlsxBase.CurrentBorderStyleValue = null;
                XlsxBase.CurrentBottomBorder     = false;

                for (int i = 0; i < 2; i++)
                {
                    row  = XlsxBase.AddRow();
                    cell = XlsxBase.AddCellString(row, null);
                    sheetData.Append(row);
                }
            }

            PageMargins pageMargins = new PageMargins()
            {
                Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D
            };
            PageSetup pageSetup = new PageSetup()
            {
                Orientation = OrientationValues.Portrait, Id = "rId" + SheetOrdinal.ToString()
            };

            worksheet.Append(sheetViews);
            worksheet.Append(sheetFormatProperties);

            if (columns.ChildElements.Count > 0)
            {
                worksheet.Append(columns);
            }

            worksheet.Append(sheetData);

            mergeCells.Count = (UInt32Value)((UInt32)mergeCells.ChildElements.Count);
            if (mergeCells.ChildElements.Count > 0)
            {
                worksheet.Append(mergeCells);
            }


            if (XlsxBase.UsedHyperlinkList.Count > 0)
            {
                worksheet.Append(hyperlinks);
            }

            worksheet.Append(pageMargins);
            worksheet.Append(pageSetup);

            worksheetPart.Worksheet = worksheet;
        }
Exemplo n.º 19
0
        public bool CreateRunsQC()
        {
            if (Cancel)
            {
                return(false);
            }

            TVItemService  tvItemServiceR = new TVItemService(LanguageEnum.en, user);
            TVItemService  tvItemService  = new TVItemService(LanguageEnum.en, user);
            MWQMRunService mwqmRunService = new MWQMRunService(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, "Québec", TVTypeEnum.Province);

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

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

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

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

            int StartQCCreateRunsQC = int.Parse(textBoxQCCreateRunsQC.Text);

            List <Obs>          obsTypeList                     = new List <Obs>();
            List <string>       sectorList                      = new List <string>();
            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>();
            }

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

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

                sectorList = (from s in dbQC.geo_stations_p
                              where s.secteur != null
                              orderby s.secteur
                              select s.secteur).Distinct().ToList();
            }

            List <TVItemModel> tvItemMWQMSiteAll = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProv.TVItemID, TVTypeEnum.MWQMSite);

            List <TVItemModel> tvItemMWQMRunAll = tvItemService.GetChildrenTVItemModelListWithTVItemIDAndTVTypeDB(tvItemModelProv.TVItemID, TVTypeEnum.MWQMRun);

            List <PCCSM.db_mesure>  dbMesureListAll = new List <PCCSM.db_mesure>();
            List <PCCSM.db_tournee> dbtAll          = new List <PCCSM.db_tournee>();

            using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
            {
                dbMesureListAll = (from m in dbQC.db_mesure
                                   select m).ToList <PCCSM.db_mesure>();

                dbtAll = (from t in dbQC.db_tournee
                          select t).ToList();
            }

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

            foreach (string sec in sectorList)
            {
                if (Cancel)
                {
                    return(false);
                }

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

                textBoxQCCreateRunsQC.Text = Count.ToString();

                if (StartQCCreateRunsQC > Count)
                {
                    continue;
                }

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

                if (qcSubsectAss == null)
                {
                    continue;
                }

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

                if (tvItemModelSubsector == null)
                {
                    richTextBoxStatus.AppendText($"could not find tvItemmodelSubsector [{TVText}]\r\n");
                    return(false);
                }

                List <MWQMRunModel> mwqmRunModelAll = mwqmRunService.GetMWQMRunModelListWithSubsectorTVItemIDDB(tvItemModelSubsector.TVItemID);

                List <PCCSM.geo_stations_p> staQCList = (from c in staQCListAll
                                                         where c.secteur == sec
                                                         select c).ToList <PCCSM.geo_stations_p>();

                int countSta      = 0;
                int totalCountsta = staQCList.Count;
                foreach (PCCSM.geo_stations_p geoStat in staQCList)
                {
                    if (Cancel)
                    {
                        return(false);
                    }

                    countSta       += 1;
                    lblStatus2.Text = countSta + " of " + totalCountsta + " ... CreateRunsQC for " + sec;
                    Application.DoEvents();

                    using (PCCSM.pccsmEntities dbQC = new PCCSM.pccsmEntities())
                    {
                        Application.DoEvents();

                        bool IsActive = true;
                        if (geoStat.status != null)
                        {
                            IsActive = (geoStat.status.Substring(0, 1) == "i" ? false : true);
                        }
                        string MWQMSiteTVText = "0000".Substring(0, 4 - geoStat.station.ToString().Length) + geoStat.station.ToString();

                        TVItemModel tvItemMWQMSiteExist = (from c in tvItemMWQMSiteAll
                                                           where c.ParentID == tvItemModelSubsector.TVItemID &&
                                                           c.TVText == MWQMSiteTVText &&
                                                           c.TVType == TVTypeEnum.MWQMSite
                                                           select c).FirstOrDefault();

                        if (tvItemMWQMSiteExist == null)
                        {
                            tvItemMWQMSiteExist = tvItemService.PostAddChildTVItemDB(tvItemModelSubsector.TVItemID, MWQMSiteTVText, TVTypeEnum.MWQMSite);
                            if (!CheckModelOK <TVItemModel>(tvItemMWQMSiteExist))
                            {
                                return(false);
                            }
                        }

                        List <PCCSM.db_mesure> dbMesureList = (from m in dbMesureListAll
                                                               where m.id_geo_station_p == geoStat.id_geo_station_p
                                                               select m).ToList <PCCSM.db_mesure>();


                        foreach (PCCSM.db_mesure dbm in dbMesureList)
                        {
                            Application.DoEvents();

                            // getting Runs
                            PCCSM.db_tournee dbt = (from t in dbtAll
                                                    where t.ID_Tournee == dbm.id_tournee
                                                    select t).FirstOrDefault();

                            DateTime?SampDateTime      = null;
                            DateTime?SampStartDateTime = null;
                            DateTime?SampEndDateTime   = null;
                            if (dbm.hre_echantillonnage != null)
                            {
                                SampDateTime = (DateTime)dbm.hre_echantillonnage.Value.AddHours(1);
                                if (dbt.hre_fin != null)
                                {
                                    SampEndDateTime = ((DateTime)dbt.date_echantillonnage).AddHours(dbt.hre_fin.Value.Hour).AddMinutes(dbt.hre_fin.Value.Minute).AddHours(1);
                                }
                                if (dbt.hre_deb != null)
                                {
                                    SampStartDateTime = ((DateTime)dbt.date_echantillonnage).AddHours(dbt.hre_deb.Value.Hour).AddMinutes(dbt.hre_deb.Value.Minute).AddHours(1);
                                }
                            }
                            else
                            {
                                SampDateTime = (DateTime)dbt.date_echantillonnage;
                                if (dbt.hre_fin != null)
                                {
                                    SampEndDateTime = ((DateTime)dbt.date_echantillonnage).AddHours(dbt.hre_fin.Value.Hour).AddMinutes(dbt.hre_fin.Value.Minute).AddHours(1);
                                    SampDateTime    = SampEndDateTime;
                                }
                                if (dbt.hre_deb != null)
                                {
                                    SampStartDateTime = ((DateTime)dbt.date_echantillonnage).AddHours(dbt.hre_deb.Value.Hour).AddMinutes(dbt.hre_deb.Value.Minute).AddHours(1);
                                    SampDateTime      = SampStartDateTime;
                                }
                            }

                            DateTime DateRun = new DateTime(((DateTime)SampDateTime).Year, ((DateTime)SampDateTime).Month, ((DateTime)SampDateTime).Day);

                            MWQMRunModel mwqmRunModelNew = new MWQMRunModel()
                            {
                                SubsectorTVItemID = tvItemModelSubsector.TVItemID,
                                DateTime_Local    = DateRun,
                                RunSampleType     = SampleTypeEnum.Routine,
                                RunNumber         = 1,
                            };

                            MWQMRunModel wqmRunModelExist = (from c in mwqmRunModelAll
                                                             where c.DateTime_Local == DateRun &&
                                                             c.RunSampleType == SampleTypeEnum.Routine &&
                                                             c.RunNumber == 1
                                                             select c).FirstOrDefault();

                            if (wqmRunModelExist == null)
                            {
                                string TVTextRun = DateRun.Year.ToString()
                                                   + " " + (DateRun.Month > 9 ? DateRun.Month.ToString() : "0" + DateRun.Month.ToString())
                                                   + " " + (DateRun.Day > 9 ? DateRun.Day.ToString() : "0" + DateRun.Day.ToString());

                                TVItemModel tvItemModelRunRet = (from c in tvItemMWQMRunAll
                                                                 where c.ParentID == tvItemModelSubsector.TVItemID &&
                                                                 c.TVText == TVTextRun
                                                                 select c).FirstOrDefault();

                                if (tvItemModelRunRet == null)
                                {
                                    richTextBoxStatus.AppendText($"{tvItemModelSubsector.TVText} --- { TVTextRun } adding TVText\r\n");
                                    tvItemModelRunRet = tvItemService.PostAddChildTVItemDB(tvItemModelSubsector.TVItemID, TVTextRun, TVTypeEnum.MWQMRun);
                                    if (!CheckModelOK <TVItemModel>(tvItemModelRunRet))
                                    {
                                        return(false);
                                    }

                                    tvItemMWQMRunAll.Add(tvItemModelRunRet);
                                }

                                // add the run in the DB
                                mwqmRunModelNew.MWQMRunTVItemID    = tvItemModelRunRet.TVItemID;
                                mwqmRunModelNew.AnalyzeMethod      = null;
                                mwqmRunModelNew.SampleCrewInitials = null;
                                mwqmRunModelNew.DateTime_Local     = DateRun;
                                if (SampEndDateTime == null)
                                {
                                    mwqmRunModelNew.EndDateTime_Local = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.EndDateTime_Local = (DateTime)SampEndDateTime;
                                }
                                if (SampStartDateTime == null)
                                {
                                    mwqmRunModelNew.StartDateTime_Local = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.StartDateTime_Local = (DateTime)SampStartDateTime;
                                }
                                if (dbt.analyse_datetime == null)
                                {
                                    mwqmRunModelNew.LabAnalyzeBath1IncubationStartDateTime_Local = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.LabAnalyzeBath1IncubationStartDateTime_Local = dbt.analyse_datetime;
                                }
                                if (dbt.hre_recep_lab == null)
                                {
                                    mwqmRunModelNew.LabReceivedDateTime_Local = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.LabReceivedDateTime_Local = dbt.hre_recep_lab;
                                }
                                mwqmRunModelNew.Laboratory   = null;
                                mwqmRunModelNew.SampleMatrix = null;
                                if (dbt.mer_etat_fin == null)
                                {
                                    mwqmRunModelNew.SeaStateAtEnd_BeaufortScale = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.SeaStateAtEnd_BeaufortScale = (BeaufortScaleEnum)dbt.mer_etat_fin;
                                }
                                if (dbt.mer_etat == null)
                                {
                                    mwqmRunModelNew.SeaStateAtStart_BeaufortScale = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.SeaStateAtStart_BeaufortScale = (BeaufortScaleEnum)dbt.mer_etat;
                                }
                                mwqmRunModelNew.SampleStatus = null;
                                if (dbt.temp_glace_recep == null)
                                {
                                    mwqmRunModelNew.TemperatureControl1_C = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.TemperatureControl1_C = (float)dbt.temp_glace_recep;
                                }
                                mwqmRunModelNew.SubsectorTVItemID = tvItemModelSubsector.TVItemID;
                                if (dbt.validation_datetime == null)
                                {
                                    mwqmRunModelNew.LabRunSampleApprovalDateTime_Local = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.LabRunSampleApprovalDateTime_Local = dbt.validation_datetime;
                                }
                                if (dbt.validation == null)
                                {
                                    mwqmRunModelNew.LabSampleApprovalContactTVItemID = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.LabSampleApprovalContactTVItemID = null; // 1; // this will be changed in the future to reflect the actuall UserInfoID
                                }
                                if (dbt.niveau_eau == null)
                                {
                                    mwqmRunModelNew.WaterLevelAtBrook_m = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.WaterLevelAtBrook_m = (double)dbt.niveau_eau;
                                }
                                if (dbt.vague_hauteur_fin == null)
                                {
                                    mwqmRunModelNew.WaveHightAtEnd_m = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.WaveHightAtEnd_m = dbt.vague_hauteur_fin;
                                }
                                if (dbt.vague_hauteur == null)
                                {
                                    mwqmRunModelNew.WaveHightAtStart_m = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.WaveHightAtStart_m = dbt.vague_hauteur;
                                }

                                string TextEN = "--";
                                if (!string.IsNullOrWhiteSpace(dbt.commentaire))
                                {
                                    TextEN = dbt.commentaire.Trim();
                                }

                                if (dbt.precipit == null)
                                {
                                    mwqmRunModelNew.RainDay1_mm = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.RainDay1_mm = dbt.precipit;
                                }
                                if (dbt.precipit_3jant == null)
                                {
                                    mwqmRunModelNew.RainDay3_mm = null;
                                }
                                else
                                {
                                    mwqmRunModelNew.RainDay3_mm = dbt.precipit_3jant;
                                }


                                mwqmRunModelNew.Tide_Start = TideTextEnum.MidTide;

                                if (dbt.maree_principale != null)
                                {
                                    if (dbt.maree_principale == 594)
                                    {
                                        mwqmRunModelNew.Tide_Start = TideTextEnum.LowTide;
                                    }
                                    else if (dbt.maree_principale == 593)
                                    {
                                        mwqmRunModelNew.Tide_Start = TideTextEnum.HighTide;
                                    }
                                    else
                                    {
                                    }
                                }

                                mwqmRunModelNew.Tide_End = mwqmRunModelNew.Tide_Start;


                                mwqmRunModelNew.AnalyzeMethod = null;
                                if (dbt.cf_methode_analytique != null)
                                {
                                    switch (dbt.cf_methode_analytique.Value.ToString())
                                    {
                                    case "0":
                                    {
                                        mwqmRunModelNew.AnalyzeMethod = AnalyzeMethodEnum.ZZ_0Q;
                                    }
                                    break;

                                    case "509":
                                    {
                                        mwqmRunModelNew.AnalyzeMethod = AnalyzeMethodEnum.ZZ_509Q;
                                    }
                                    break;

                                    case "510":
                                    {
                                        mwqmRunModelNew.AnalyzeMethod = AnalyzeMethodEnum.ZZ_510Q;
                                    }
                                    break;

                                    case "525":
                                    {
                                        mwqmRunModelNew.AnalyzeMethod = AnalyzeMethodEnum.ZZ_525Q;
                                    }
                                    break;

                                    default:
                                        break;
                                    }
                                }

                                mwqmRunModelNew.SampleMatrix = SampleMatrixEnum.MPNQ;

                                mwqmRunModelNew.Laboratory = null;

                                if (dbt.laboratoire_operateur_id != null)
                                {
                                    switch (dbt.laboratoire_operateur_id.ToString())
                                    {
                                    case "1":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_0;
                                    }
                                    break;

                                    case "2":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_1;
                                    }
                                    break;

                                    case "3":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_2;
                                    }
                                    break;

                                    case "4":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_3;
                                    }
                                    break;

                                    case "5":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_4;
                                    }
                                    break;

                                    case "6":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_1Q;
                                    }
                                    break;

                                    case "7":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_2Q;
                                    }
                                    break;

                                    case "8":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_3Q;
                                    }
                                    break;

                                    case "9":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_4Q;
                                    }
                                    break;

                                    case "10":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_5Q;
                                    }
                                    break;

                                    case "11":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_11BC;
                                    }
                                    break;

                                    case "12":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_12BC;
                                    }
                                    break;

                                    case "14":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_14BC;
                                    }
                                    break;

                                    case "15":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_15BC;
                                    }
                                    break;

                                    case "16":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_16BC;
                                    }
                                    break;

                                    case "17":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_17BC;
                                    }
                                    break;

                                    case "18":
                                    {
                                        mwqmRunModelNew.Laboratory = LaboratoryEnum.ZZ_18BC;
                                    }
                                    break;

                                    default:
                                        break;
                                    }
                                }

                                // Doing Status
                                mwqmRunModelNew.SampleStatus = null;
                                if (dbt.status != null)
                                {
                                    if (dbt.status == 11)
                                    {
                                        mwqmRunModelNew.SampleStatus = SampleStatusEnum.Active;
                                    }
                                    else if (dbt.status == 606)
                                    {
                                        mwqmRunModelNew.SampleStatus = SampleStatusEnum.Archived;
                                    }
                                    else
                                    {
                                    }
                                }

                                if (mwqmRunModelNew.StartDateTime_Local > mwqmRunModelNew.EndDateTime_Local)
                                {
                                    mwqmRunModelNew.EndDateTime_Local = mwqmRunModelNew.StartDateTime_Local;
                                }

                                MWQMRunModel mwqmRunModel = (from c in mwqmRunModelAll
                                                             where c.SubsectorTVItemID == tvItemModelSubsector.TVItemID &&
                                                             c.MWQMRunTVText == TVTextRun &&
                                                             c.RunSampleType == mwqmRunModelNew.RunSampleType
                                                             select c).FirstOrDefault();

                                if (mwqmRunModel == null)
                                {
                                    richTextBoxStatus.AppendText($"{tvItemModelSubsector.TVText} --- { TVTextRun } adding MWQMRun\r\n");
                                    MWQMRunModel mwqmRunModelRet = mwqmRunService.PostAddMWQMRunDB(mwqmRunModelNew);
                                    if (!CheckModelOK <MWQMRunModel>(mwqmRunModelRet))
                                    {
                                        return(false);
                                    }

                                    mwqmRunModelAll.Add(mwqmRunModelRet);
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }